from __future__ import annotations

from typing import Optional

from fastapi import Depends, Header, HTTPException, Request, status
from pydantic import BaseModel

from app.services import api_keys


class RequestContext(BaseModel):
    user_id: Optional[str] = None
    api_key: Optional[str] = None
    api_key_id: Optional[str] = None
    auth_scheme: str = "anonymous"


async def get_request_context(
    request: Request,
    authorization: Optional[str] = Header(default=None, convert_underscores=False),
    x_user_id: Optional[str] = Header(default=None, alias="X-User-ID"),
) -> RequestContext:
    ctx = RequestContext()

    if x_user_id:
        ctx.user_id = x_user_id
        ctx.auth_scheme = "user"

    if authorization:
        parts = authorization.split(" ", 1)
        if len(parts) == 2 and parts[0].lower() == "bearer":
            token = parts[1].strip()
            if token.startswith("tano_"):
                validation = api_keys.validate_api_key(token)
                if not validation.valid:
                    raise HTTPException(
                        status_code=status.HTTP_401_UNAUTHORIZED,
                        detail=validation.message or "Invalid API key",
                    )
                ctx.api_key = token
                ctx.api_key_id = validation.key_id
                ctx.user_id = validation.user_id
                ctx.auth_scheme = "api_key"
            else:
                # For now we accept Bearer tokens as user JWTs and rely on X-User-ID fallback
                ctx.auth_scheme = "bearer"
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Unsupported Authorization header format",
            )

    if not ctx.user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="User identity required",
        )

    return ctx
