"""AI analysis routes."""

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.core.db import get_db
from app.schemas.ai_analysis import AIAnalysisRead
from app.services import ai_analysis_service

router = APIRouter(prefix="/ai", tags=["ai"])


@router.post("/analyze", response_model=AIAnalysisRead)
def analyze_engagement(
    engagement_id: int | None = Query(default=None, ge=1),
    db: Session = Depends(get_db),
) -> AIAnalysisRead:
    """Run AI analysis over engagement events and coverage state."""
    if engagement_id is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="engagement_id is required",
        )

    try:
        result = ai_analysis_service.analyze_engagement(db=db, engagement_id=engagement_id)
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
    except ai_analysis_service.AIConfigError as exc:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc
    except ai_analysis_service.AIAnalysisError as exc:
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc

    return AIAnalysisRead.model_validate(result)
