"""
Authentication Dependencies for V2 API

Shared authentication utilities to avoid circular imports.
"""

from fastapi import Header, HTTPException

from mumla.app.models.session import Session
from mumla.app.services.session_service import get_session_service
from mumla.app.utils.errors import (
    InvalidSessionTokenError,
    SessionExpiredError,
    SessionNotFoundError,
    map_error_to_http_exception,
)


def get_moorcheh_api_key(authorization: str = Header(...)) -> str:
    """
    Extract Moorcheh API key from Authorization header

    Args:
        authorization: Authorization header (Bearer {api_key})

    Returns:
        API key

    Raises:
        HTTPException: If authorization header is invalid
    """
    if not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail="Invalid authorization header. Use: Bearer {api_key}",
        )

    api_key = authorization.replace("Bearer ", "").strip()
    if not api_key:
        raise HTTPException(
            status_code=401, detail="Missing API key in authorization header"
        )

    return api_key


def get_current_session(
    authorization: str = Header(...), x_session_token: str | None = Header(None)
) -> Session:
    """
    Get and validate current session

    Args:
        authorization: Authorization header with Moorcheh API key
        x_session_token: Session token header

    Returns:
        Validated Session

    Raises:
        HTTPException: If session is invalid or expired
    """
    moorcheh_api_key = get_moorcheh_api_key(authorization)

    if not x_session_token:
        raise HTTPException(
            status_code=401, detail="Missing session token. Use X-Session-Token header."
        )

    session_service = get_session_service()

    try:
        token_payload = session_service.validate_session(
            x_session_token, moorcheh_api_key
        )

        # Get session from storage
        session = session_service.get_session(token_payload.agent_id)
        if not session:
            raise SessionNotFoundError(
                f"Session for agent {token_payload.agent_id} not found"
            )

        # Auto-renew session if near expiry
        renewed = session_service.check_and_auto_renew(
            agent_id=token_payload.agent_id,
            moorcheh_api_key=moorcheh_api_key,
        )
        if renewed:
            session = renewed

        return session

    except (SessionExpiredError, SessionNotFoundError, InvalidSessionTokenError) as e:
        raise map_error_to_http_exception(e)
