import uuid
from dataclasses import dataclass

from fastapi import Depends, Header, HTTPException, Query, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jose import JWTError
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.actors import ActorType, GuestSessionStatus
from app.core.config import settings
from app.core.security import verify_token
from app.db.database import get_async_session

_bearer = HTTPBearer()
_optional_bearer = HTTPBearer(auto_error=False)

# ── Role constants ─────────────────────────────────────────────────────────────
GESTIONNAIRE_PLUS = ("GESTIONNAIRE", "ADMIN_SYSTEME")
ADMIN_ONLY = ("ADMIN_SYSTEME",)


@dataclass(slots=True)
class ActorPrincipal:
    actor_type: str
    actor_id: uuid.UUID
    user: object | None = None


def _build_401() -> HTTPException:
    return HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Token invalide ou expiré",
        headers={"WWW-Authenticate": "Bearer"},
    )


async def _resolve_user_from_credentials(
    credentials: HTTPAuthorizationCredentials,
    db: AsyncSession,
):
    from app.models.utilisateur import Session as UserSession, Utilisateur

    _401 = _build_401()

    try:
        payload = verify_token(credentials.credentials)
        user_id: str | None = payload.get("sub")
        jti: str | None = payload.get("jti")
        if not user_id or not jti:
            raise _401
        user_uuid = uuid.UUID(user_id)
    except (JWTError, ValueError):
        raise _401

    stmt = (
        select(Utilisateur)
        .join(UserSession, UserSession.utilisateur_id == Utilisateur.id)
        .where(
            UserSession.jti == jti,
            UserSession.est_actif == True,
            Utilisateur.id == user_uuid,
            Utilisateur.est_actif == True,
        )
    )
    user = (await db.execute(stmt)).scalar_one_or_none()
    if user is None:
        raise _401

    if user.type_utilisateur == "SUPERVISEUR":
        user.type_utilisateur = "ADMIN_SYSTEME"

    user._jti = jti

    return user


async def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(_bearer),
    db: AsyncSession = Depends(get_async_session),
):
    """Validates the Bearer token and returns the active Utilisateur."""
    return await _resolve_user_from_credentials(credentials, db)


async def get_optional_user(
    credentials: HTTPAuthorizationCredentials | None = Depends(_optional_bearer),
    db: AsyncSession = Depends(get_async_session),
):
    """Returns the current user when JWT is present, otherwise None."""
    if credentials is None:
        return None
    return await _resolve_user_from_credentials(credentials, db)


async def ensure_guest_mode_enabled() -> None:
    if not settings.guest_mode_enabled:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="GUEST_MODE_DISABLED",
        )


async def get_guest_id(
    x_guest_id: str | None = Header(default=None, alias="X-Guest-Id"),
    guest_id_query: str | None = Query(default=None, alias="guestId"),
) -> uuid.UUID | None:
    """Resolves guest UUID from header or query parameter."""
    candidate = x_guest_id or guest_id_query
    if x_guest_id and guest_id_query and x_guest_id != guest_id_query:
        raise HTTPException(status_code=400, detail="GUEST_ID_MISMATCH")
    if not candidate:
        return None
    try:
        return uuid.UUID(candidate)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail="GUEST_ID_INVALID") from exc


async def get_guest_session(
    guest_id: uuid.UUID | None = Depends(get_guest_id),
    db: AsyncSession = Depends(get_async_session),
):
    """Returns an active guest session when guest id is supplied, otherwise None."""
    from app.models.guest_session import GuestSession

    if guest_id is None:
        return None
    if not settings.guest_mode_enabled:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="GUEST_MODE_DISABLED",
        )

    session = (
        await db.execute(select(GuestSession).where(GuestSession.id == guest_id))
    ).scalar_one_or_none()

    if session is None:
        raise HTTPException(status_code=404, detail="GUEST_SESSION_NOT_FOUND")
    if session.statut == GuestSessionStatus.MERGED.value:
        raise HTTPException(status_code=409, detail="GUEST_SESSION_MERGED")
    if session.statut != GuestSessionStatus.ACTIVE.value:
        raise HTTPException(status_code=409, detail="GUEST_SESSION_INVALID")

    return session


async def get_current_guest_session(
    session=Depends(get_guest_session),
):
    if not settings.guest_mode_enabled:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="GUEST_MODE_DISABLED",
        )
    if session is None:
        raise HTTPException(status_code=401, detail="GUEST_ACCESS_DENIED")
    return session


async def get_current_actor(
    user=Depends(get_optional_user),
    guest_id: uuid.UUID | None = Depends(get_guest_id),
    db: AsyncSession = Depends(get_async_session),
) -> ActorPrincipal:
    if user is not None:
        return ActorPrincipal(
            actor_type=ActorType.AUTH_USER.value,
            actor_id=user.id,
            user=user,
        )
    if guest_id is not None:
        guest_session = await get_guest_session(guest_id=guest_id, db=db)
        if guest_session is not None:
            return ActorPrincipal(
                actor_type=ActorType.GUEST.value,
                actor_id=guest_session.id,
                user=None,
            )
    raise HTTPException(status_code=401, detail="AUTH_OR_GUEST_REQUIRED")


async def get_current_guest_actor(
    guest_session=Depends(get_current_guest_session),
) -> ActorPrincipal:
    return ActorPrincipal(
        actor_type=ActorType.GUEST.value,
        actor_id=guest_session.id,
        user=None,
    )


def require_role(*roles: str):
    """
    Dependency factory that restricts access to users with one of the given roles.

    Usage::

        current_user = Depends(require_role("GESTIONNAIRE", "ADMIN_SYSTEME"))
    """

    async def _check(current_user=Depends(get_current_user)):
        if current_user.type_utilisateur not in roles:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Permission insuffisante",
            )
        return current_user

    return _check


async def get_current_token_jti(
    credentials: HTTPAuthorizationCredentials = Depends(_bearer),
) -> str:
    """Returns the JTI claim from the current Bearer token (no DB check)."""
    from jose import JWTError

    try:
        payload = verify_token(credentials.credentials)
        jti: str | None = payload.get("jti")
        if not jti:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token invalide",
            )
        return jti
    except JWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token invalide",
        )
