from __future__ import annotations

from typing import Annotated

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

from app.api.deps import get_db
from app.schemas.agent_run import AgentRunRead
from app.schemas.common import ErrorResponse
from app.services.agent_runs import AgentRunService

router = APIRouter(prefix="/agent-runs")
DbSession = Annotated[Session, Depends(get_db)]


@router.get(
    "",
    response_model=list[AgentRunRead],
    summary="查询 Agent 运行日志",
    description="按 Agent、运行状态、来源和数量限制筛选运行日志。",
)
def list_agent_runs(
    db: DbSession,
    agent: Annotated[
        str | None,
        Query(description="Agent 名称筛选。"),
    ] = None,
    status_value: Annotated[
        str | None,
        Query(alias="status", description="运行状态筛选。"),
    ] = None,
    source: Annotated[
        str | None,
        Query(description="运行来源筛选。"),
    ] = None,
    limit: Annotated[
        int,
        Query(ge=1, le=100, description="返回记录上限。"),
    ] = 20,
) -> list[AgentRunRead]:
    return AgentRunService(db).list_runs(
        agent=agent, status=status_value, source=source, limit=limit
    )


@router.get(
    "/{run_id}",
    response_model=AgentRunRead,
    summary="读取单次 Agent 运行详情",
    description="按 `run_id` 返回单次执行的路由结果、工具调用和语义解析信息。",
    responses={
        status.HTTP_404_NOT_FOUND: {
            "model": ErrorResponse,
            "description": "运行记录不存在。",
        }
    },
)
def get_agent_run(run_id: str, db: DbSession) -> AgentRunRead:
    run = AgentRunService(db).get_run(run_id)
    if run is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Run not found")
    return run
