"""Core API 角色鉴权 — owner / authorized_corrector / guest。"""

from __future__ import annotations

from pathlib import Path
from typing import Any

from fastapi import HTTPException, Request

from niannian.tenant.context import _session_header

CORE_ACCESS_ROLES = frozenset({"owner", "authorized_corrector"})
BASELINE_ROLES = frozenset({"owner"})


def parse_user_role(request: Request) -> str:
    raw = request.headers.get("x-niannian-role") or request.headers.get("X-NianNian-Role")
    if raw is None or not str(raw).strip():
        return "owner"
    return str(raw).strip().lower()


def require_core_access(request: Request) -> str:
    role = parse_user_role(request)
    if role not in CORE_ACCESS_ROLES:
        raise HTTPException(
            status_code=403,
            detail={"code": "core_forbidden", "message": "仅主人及授权者可访问核心页"},
        )
    return role


def require_baseline_owner(request: Request) -> str:
    role = require_core_access(request)
    if role not in BASELINE_ROLES:
        raise HTTPException(
            status_code=403,
            detail={"code": "baseline_forbidden", "message": "仅 owner 可创建纠偏基线"},
        )
    return role


def require_admin_owner(request: Request) -> str:
    """pinn 用户管理 — 仅 header owner，且非 tenant session。"""
    if _session_header(request):
        raise HTTPException(
            status_code=403,
            detail={"code": "admin_forbidden", "message": "tenant session cannot access admin API"},
        )
    return require_baseline_owner(request)


def require_core_docker_user(
    request: Request,
    *,
    config: dict[str, Any],
    home: Path,
) -> str:
    """Core 运维 API — Docker profile · 返回 RequestContext user_id。"""
    role = require_core_access(request)
    from niannian.tenant.context import resolve_request_context

    ctx = resolve_request_context(request, config, home=home)
    if "core.*" in ctx.capabilities:
        return ctx.user_id
    # Legacy Console：仅 X-NianNian-Role、无 session → 内网 owner
    if role in CORE_ACCESS_ROLES and _session_header(request) is None:
        return ctx.user_id
    raise HTTPException(
        status_code=403,
        detail={"code": "core_forbidden", "message": "core API not available on this profile"},
    )
