"""API routes for evaluation targets."""

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

from agenteval.channels.factory import ChannelFactory
from agenteval.models import EvalTarget
from agenteval.storage.repository import TargetRepository
from agenteval.web.deps import get_db

router = APIRouter()


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


@router.post("")
def create_target(target: EvalTarget, session: Session = Depends(get_db)) -> dict:
    created = TargetRepository(session).create(target)
    return created.model_dump()


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


@router.put("/{target_id}")
def update_target(target_id: str, target: EvalTarget, session: Session = Depends(get_db)) -> dict:
    target.id = target_id
    updated = TargetRepository(session).update(target)
    if not updated:
        raise HTTPException(status_code=404, detail="target not found")
    return updated.model_dump()


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


@router.post("/{target_id}/test")
async def test_target(target_id: str, session: Session = Depends(get_db)) -> dict:
    target = TargetRepository(session).get(target_id)
    if not target:
        raise HTTPException(status_code=404, detail="target not found")

    channel = ChannelFactory.create(target)
    health = await channel.health_check()
    return {"ok": health.ok, "message": health.message}
