"""客服后台菜单可见性（侧栏展示，不影响各页面原有权限校验）。"""
from backend.utils import _AllPermissions, verify_kefu_permission
from jituan.models import KefuMenuPage
from jituan.services.admin_context import build_admin_club_context, can_manage_admin_assignments


def _is_super_permissions(permissions):
    return isinstance(permissions, _AllPermissions)


def _page_visible(page, permissions, user, is_super):
    if is_super:
        return True
    if page.require_super:
        return False
    if page.require_group_manage:
        perms_list = list(permissions) if not _is_super_permissions(permissions) else ['000001']
        return can_manage_admin_assignments(user, perms_list)
    codes = page.perm_codes or []
    if not codes:
        return False
    return any(code in permissions for code in codes)


def build_menu_access_payload(request, username=None):
    """
    根据用户 gvsdsdk 权限计算可见菜单 page_id 列表。
    返回 (payload, error_response)；error_response 非空时表示校验失败。
    """
    phone = (username or getattr(request.user, 'Phone', '') or '').strip()
    kefu, permissions = verify_kefu_permission(request, phone)
    if kefu is None:
        return None, permissions

    is_super = _is_super_permissions(permissions)
    pages = list(KefuMenuPage.query.all().order_by('sort_order', 'page_id'))
    if not pages:
        try:
            from django.core.management import call_command
            call_command('seed_kefu_menu')
            pages = list(KefuMenuPage.query.all().order_by('sort_order', 'page_id'))
        except Exception:
            pages = []
    visible_ids = []

    for page in pages:
        if not page.path:
            continue
        if _page_visible(page, permissions, request.user, is_super):
            visible_ids.append(page.page_id)

    for page in pages:
        if page.path:
            continue
        children = [p for p in pages if p.parent_id == page.page_id and p.path]
        if any(child.page_id in visible_ids for child in children):
            visible_ids.append(page.page_id)

    club_ctx = build_admin_club_context(request.user)
    path_by_id = {p.page_id: p.path for p in pages if p.path}
    visible_paths = [path_by_id[pid] for pid in visible_ids if pid in path_by_id]
    return {
        'visible_page_ids': sorted(set(visible_ids)),
        'visible_paths': visible_paths,
        'can_switch_club': bool(club_ctx.get('can_switch_club')),
        'is_group_admin': bool(club_ctx.get('is_group_admin')),
        'menu_ready': bool(pages),
    }, None
