from datetime import datetime, timezone

from fastapi import APIRouter, Depends
from pydantic import BaseModel

from app.auth.keycloak_dependencies import get_current_keycloak_payload
from app.auth.metadata_dependencies import get_current_metadata_user
from app.auth.project_dependencies import (
    ProjectContext,
    get_project_context,
)

router = APIRouter()


class AgentAuthContextResponse(BaseModel):
    user_id: str
    keycloak_sub: str
    username: str
    role: str
    is_superuser: bool
    project_id: str
    network: str
    project_role: str
    token_expires_at: str | None = None


@router.get("/agent/auth/context", response_model=AgentAuthContextResponse)
async def get_agent_auth_context(
    ctx: ProjectContext = Depends(get_project_context),
    current_user=Depends(get_current_metadata_user),
    keycloak_payload: dict = Depends(get_current_keycloak_payload),
) -> AgentAuthContextResponse:
    exp = keycloak_payload.get("exp")
    token_expires_at = (
        datetime.fromtimestamp(exp, tz=timezone.utc).isoformat()
        if isinstance(exp, int)
        else None
    )
    return AgentAuthContextResponse(
        user_id=str(current_user.id),
        keycloak_sub=str(current_user.keycloak_id),
        username=current_user.username,
        role=current_user.role,
        is_superuser=current_user.is_superuser,
        project_id=str(ctx.project_id),
        network=ctx.project_code,
        project_role=ctx.project_role,
        token_expires_at=token_expires_at,
    )
