from __future__ import annotations

from fastapi import APIRouter, Header, HTTPException

from app.generation.llm_client import LLMClientError
from app.models.agent import AgentTurnRequest, AgentTurnResponse
from app.services.agent_turn_service import AgentTurnService

router = APIRouter(prefix="/agent/turn", tags=["Agent"])

_agent_turn_service = AgentTurnService()


@router.post("/", response_model=AgentTurnResponse)
async def agent_turn(
    body: AgentTurnRequest,
    x_user_id: str | None = Header(default=None, alias="X-User-Id"),
    x_request_id: str | None = Header(default=None, alias="X-Request-Id"),
) -> AgentTurnResponse:
    try:
        return await _agent_turn_service.run_turn(
            body,
            request_id=x_request_id,
            user_id=x_user_id,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except LLMClientError as exc:
        status = 503 if exc.status_code in (429, 503, 504, None) else 502
        raise HTTPException(status_code=status, detail=str(exc)) from exc
