"""Results and recommendations API routes."""

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from mixlift.deps import get_current_user, get_db
from mixlift.projects.models import ModelRun, Project, User
from mixlift.results.schemas import RecommendationItem, RecommendationsResponse

router = APIRouter(tags=["results"])


@router.get("/runs/{run_id}/recommendations", response_model=RecommendationsResponse)
async def get_recommendations(
    run_id: str,
    user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_db),
):
    result = await session.execute(select(ModelRun).where(ModelRun.id == run_id))
    run = result.scalar_one_or_none()
    if not run:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Run not found")

    # Verify ownership
    project_result = await session.execute(
        select(Project).where(Project.id == run.project_id, Project.user_id == user.id)
    )
    if not project_result.scalar_one_or_none():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Run not found")

    if run.status != "completed":
        return RecommendationsResponse(
            run_id=str(run.id),
            status=run.status,
            expected_lift_pct=None,
            summary=run.error_message if run.status == "failed" else "Model is still training...",
            recommendations=[],
            current_allocation=None,
            optimal_allocation=None,
        )

    recs = [RecommendationItem(**r) for r in (run.recommendations or [])]

    return RecommendationsResponse(
        run_id=str(run.id),
        status=run.status,
        expected_lift_pct=run.expected_lift_pct,
        summary=run.summary_text,
        recommendations=recs,
        current_allocation=run.current_allocation,
        optimal_allocation=run.optimal_allocation,
    )
