"""API routes for evaluation scenarios."""

from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session

from agenteval.models import Scenario
from agenteval.scenarios.templates import get_template, list_templates
from agenteval.services.model_configs import ModelConfigError
from agenteval.storage.repository import ScenarioRepository
from agenteval.web.deps import get_db

router = APIRouter()


@router.get("/templates")
def list_scenario_templates() -> list[dict]:
    """Return built-in scenario templates (no auth required for discovery)."""
    return list_templates()


@router.get("/templates/{template_id}")
def get_scenario_template(template_id: str) -> dict:
    tpl = get_template(template_id)
    if not tpl:
        raise HTTPException(status_code=404, detail="template not found")
    return tpl


@router.get("")
def list_scenarios(session: Session = Depends(get_db)) -> list[dict]:
    return [s.model_dump() for s in ScenarioRepository(session).list_all()]


@router.post("")
def create_scenario(scenario: Scenario, session: Session = Depends(get_db)) -> dict:
    try:
        created = ScenarioRepository(session).create(scenario)
    except ModelConfigError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    return created.model_dump()


@router.get("/{scenario_id}")
def get_scenario(scenario_id: str, session: Session = Depends(get_db)) -> dict:
    scenario = ScenarioRepository(session).get(scenario_id)
    if not scenario:
        raise HTTPException(status_code=404, detail="scenario not found")
    return scenario.model_dump()


@router.put("/{scenario_id}")
def update_scenario(scenario_id: str, scenario: Scenario, session: Session = Depends(get_db)) -> dict:
    scenario.id = scenario_id
    try:
        updated = ScenarioRepository(session).update(scenario)
    except ModelConfigError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    if not updated:
        raise HTTPException(status_code=404, detail="scenario not found")
    return updated.model_dump()


@router.delete("/{scenario_id}")
def delete_scenario(scenario_id: str, session: Session = Depends(get_db)) -> dict:
    if not ScenarioRepository(session).delete(scenario_id):
        raise HTTPException(status_code=404, detail="scenario not found")
    return {"ok": True}
