"""
FastAPI authentication dependency chain for DocuVault.

Provides two reusable FastAPI dependencies:
  - get_current_user: validates the Bearer JWT and returns the User ORM object
  - get_current_admin: requires user.role == 'admin' (T-02-07)

Usage in route handlers:
    from deps.auth import get_current_user, get_current_admin
    from db.models import User

    @router.get("/me")
    async def get_me(current_user: User = Depends(get_current_user)):
        return {"id": str(current_user.id), "email": current_user.email}

    @router.get("/admin/users")
    async def list_users(
        _admin: User = Depends(get_current_admin),
        session: AsyncSession = Depends(get_db),
    ):
        ...
"""
import hmac
import logging
import uuid

from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession

from db.models import User
from deps.db import get_db
from services import auth as auth_service

_logger = logging.getLogger(__name__)

# HTTPBearer parses the Authorization: Bearer <token> header.
# auto_error=True (default) raises 403 if no Authorization header is present.
security = HTTPBearer()


async def get_current_user(
    request: Request,
    credentials: HTTPAuthorizationCredentials = Depends(security),
    session: AsyncSession = Depends(get_db),
) -> User:
    """Validate the Bearer JWT and return the active User ORM object.

    Raises HTTP 401 if:
      - Token is missing, expired, or tampered (handled by HTTPBearer + decode)
      - User does not exist in the database
      - User account is deactivated (is_active=False)
    """
    try:
        payload = auth_service.decode_access_token(credentials.credentials)
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired token",
            headers={"WWW-Authenticate": "Bearer"},
        ) from exc

    # ── user_nbf check (D-02, D-03, D-04) ──────────────────────────────────────
    # Reject tokens issued before a security event (password change, TOTP enroll,
    # deactivation). The user_nbf:{user_id} key is written by Wave 2 (Plan 03).
    # Fail-open on Redis errors (D-04): a Redis outage must never deny service.
    # CRITICAL: the `except HTTPException: raise` guard MUST precede the broad
    # `except Exception` — otherwise the intentional 401 is swallowed (T-7.2-02).
    try:
        redis_client = request.app.state.redis
        nbf_bytes = await redis_client.get(f"user_nbf:{payload['sub']}")
        if nbf_bytes is not None:
            # Tolerate both bytes and str returns (FakeRedis in tests may return
            # either depending on what was stored; real aioredis returns bytes).
            nbf_str = nbf_bytes.decode() if isinstance(nbf_bytes, (bytes, bytearray)) else nbf_bytes
            if payload["iat"] < int(nbf_str):
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="Session invalidated",
                    headers={"WWW-Authenticate": "Bearer"},
                )
    except HTTPException:
        raise  # re-raise the 401 we just constructed (T-7.2-02: Pitfall 1 guard)
    except Exception as exc:
        _logger.warning("Redis user_nbf check failed (fail-open): %s", exc)
    # ── end user_nbf check ──────────────────────────────────────────────────────

    # ── fgp check (D-06, Phase 7.4) ────────────────────────────────────────────
    # Validates the fgp claim embedded by create_access_token. Empty claim means
    # the token predates Phase 7.4 — allow gracefully (migration window, D-06).
    # NOT wrapped in try/except: _compute_fgp is pure computation with no I/O.
    fgp_claim = payload.get("fgp", "")
    if fgp_claim:
        fgp_actual = auth_service._compute_fgp(
            request.headers.get("User-Agent", ""),
            request.headers.get("Accept-Language", ""),
        )
        if not hmac.compare_digest(fgp_claim, fgp_actual):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token fingerprint mismatch",
                headers={"WWW-Authenticate": "Bearer"},
            )
    # ── end fgp check ───────────────────────────────────────────────────────────

    try:
        user_uuid = uuid.UUID(payload["sub"])
    except (KeyError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token subject",
            headers={"WWW-Authenticate": "Bearer"},
        ) from exc

    user = await session.get(User, user_uuid)
    if user is None or not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="User not found or deactivated",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Set on request.state so the per-account rate-limiter key_func (_account_key)
    # can read it. The dependency resolves before @account_limiter.limit() calls
    # key_func, so this must live here — not in the handler body (too late).
    request.state.current_user = user
    return user


async def get_current_admin(
    user: User = Depends(get_current_user),
) -> User:
    """Require admin role; raises HTTP 403 otherwise (T-02-07).

    Admin impersonation is architecturally excluded (ADMIN-07, T-02-08):
    no code path sets a JWT sub to a different user's id. This dependency
    only checks that the authenticated user's role is 'admin'.
    """
    if user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Admin access required",
        )
    return user


async def get_regular_user(
    user: User = Depends(get_current_user),
) -> User:
    """Reject admin accounts on all /api/documents/* endpoints (D-16, SC4).

    Admin accounts cannot access document content (CLAUDE.md + SEC-04).
    Returns 403 (not 404) — the admin knows document endpoints exist.
    Regular users are passed through unchanged.
    """
    if user.role == "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Admin accounts cannot access document content",
        )
    return user
