from typing import Annotated, Optional
from uuid import UUID
from fastapi import Depends, Header, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from core.constants import SystemRole
from core.exceptions import UnauthorizedError, ForbiddenError, TenantAccessError
from core.security import decode_token
from core.tenant_context import set_current_user_id, set_current_tenant_id
from infrastructure.database.session import get_db
from modules.identity.models import User
from modules.identity.repository import UserRepository
from modules.tenants.models import Tenant, TenantMember
from modules.tenants.service import TenantService
from modules.permissions.service import PermissionService

security_scheme = HTTPBearer(auto_error=False)


async def get_current_user(
    credentials: Annotated[Optional[HTTPAuthorizationCredentials], Depends(security_scheme)],
    db: Annotated[AsyncSession, Depends(get_db)],
) -> User:
    if not credentials or not credentials.credentials:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication token is required",
            headers={"WWW-Authenticate": "Bearer"},
        )

    try:
        payload = decode_token(credentials.credentials, expected_type="access")
    except UnauthorizedError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=str(exc.message),
            headers={"WWW-Authenticate": "Bearer"},
        )

    user_id_str = payload.get("sub")
    if not user_id_str:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token payload")

    user_repo = UserRepository(db)
    user = await user_repo.get_by_id(UUID(user_id_str))
    if not user or user.status != "active":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or suspended")

    set_current_user_id(user.id)
    return user


async def get_current_tenant(
    user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
    x_tenant_id: Annotated[Optional[str], Header()] = None,
) -> tuple[Tenant, TenantMember | None]:
    """
    Resolves tenant context from X-Tenant-ID header.
    If header is omitted, auto-resolves to the user's primary workspace.
    Verifies that the authenticated user has access to this tenant.
    """
    tenant_service = TenantService(db)

    if not x_tenant_id:
        # Auto-resolve user's first tenant workspace if not explicitly provided
        user_tenants = await tenant_service.get_user_tenants(user.id)
        if user_tenants:
            tenant = user_tenants[0]
            membership = None
            if not user.is_superuser:
                membership = await tenant_service.verify_member_access(tenant.id, user.id)
            set_current_tenant_id(tenant.id)
            return tenant, membership

        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Header 'X-Tenant-ID' is required for tenant-scoped operations, or user has no workspace",
        )

    try:
        tenant_uuid = UUID(x_tenant_id)
    except ValueError:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid tenant UUID format")

    tenant = await tenant_service.get_tenant_by_id(tenant_uuid)

    membership = None
    if not user.is_superuser:
        try:
            membership = await tenant_service.verify_member_access(tenant_uuid, user.id)
        except TenantAccessError:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You do not have access to this tenant workspace",
            )

    set_current_tenant_id(tenant.id)
    return tenant, membership


def require_role(allowed_roles: list[str]):
    """Enforces specific workspace roles."""
    async def role_checker(
        tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
        user: Annotated[User, Depends(get_current_user)],
    ) -> None:
        if user.is_superuser:
            return

        _, membership = tenant_context
        if not membership or membership.role not in allowed_roles:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Operation requires one of the following roles: {', '.join(allowed_roles)}",
            )
    return role_checker


def require_permission(permission_code: str):
    """Enforces fine-grained permission code via RBAC."""
    async def perm_checker(
        tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
        user: Annotated[User, Depends(get_current_user)],
    ) -> None:
        if user.is_superuser:
            return

        _, membership = tenant_context
        if not membership or not PermissionService.has_permission(membership.role, permission_code):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Missing required permission: '{permission_code}'",
            )
    return perm_checker


def require_superuser(user: Annotated[User, Depends(get_current_user)]) -> User:
    if not user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Superadmin privileges required for this endpoint",
        )
    return user
