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 CurrentUserContext, get_current_user, get_db
from app.schemas.agent_run import AgentRunRead, AgentRunStatsRead
from app.schemas.common import ErrorResponse
from app.services.agent_run_access_policy import AgentRunAccessPolicy
from app.services.agent_runs import AgentRunService

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


@router.get(
    "",
    response_model=list[AgentRunRead],
    summary="查询 Agent 运行日志",
    description="按 Agent、运行状态、来源和数量限制筛选运行日志。",
)
def list_agent_runs(
    db: DbSession,
    current_user: CurrentUser,
    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]:
    tenant_id = AgentRunAccessPolicy.require_current_tenant_id(current_user)
    scope_clause = AgentRunAccessPolicy.build_query_scope(current_user)
    runs = AgentRunService(db).list_runs_for_tenant(
        tenant_id=tenant_id,
        agent=agent,
        status=status_value,
        source=source,
        limit=limit,
        scope_clause=scope_clause,
    )
    return AgentRunAccessPolicy.filter_list_items(runs, current_user, db)


@router.get(
    "/summary",
    response_model=AgentRunStatsRead,
    summary="查询 Agent 运行统计",
    description="按最近运行记录实时汇总 Agent、工具调用、模型调用和错误统计。",
)
def summarize_agent_runs(
    db: DbSession,
    current_user: CurrentUser,
    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=500, description="统计最近记录数。"),
    ] = 200,
) -> AgentRunStatsRead:
    tenant_id = AgentRunAccessPolicy.require_current_tenant_id(current_user)
    scope_clause = AgentRunAccessPolicy.build_query_scope(current_user)
    return AgentRunService(db).summarize_runs_for_tenant(
        tenant_id=tenant_id,
        agent=agent,
        status=status_value,
        source=source,
        limit=limit,
        scope_clause=scope_clause,
    )


@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,
    current_user: CurrentUser,
) -> AgentRunRead:
    tenant_id = AgentRunAccessPolicy.require_current_tenant_id(current_user)
    run = AgentRunService(db).get_run_for_tenant(
        run_id,
        tenant_id=tenant_id,
    )
    if run is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Run not found")
    AgentRunAccessPolicy.require_detail_read(run, current_user)
    return run
