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, require_platform_admin_user
from app.schemas.agent_trace import (
    AgentConversationTraceRead,
    AgentTraceDetailRead,
    AgentTraceListItem,
)
from app.schemas.common import ErrorResponse
from app.services.agent_traces import AgentTraceService

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


@router.get(
    "",
    response_model=list[AgentTraceListItem],
    summary="查询 Agent Trace 列表",
    description="按 Agent、状态、来源、会话或关键字查询 Agent 链路追踪记录。",
)
def list_agent_traces(
    db: DbSession,
    _: Annotated[object, Depends(require_platform_admin_user)],
    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,
    conversation_id: Annotated[str | None, Query(description="会话 ID 过滤。")] = None,
    keyword: Annotated[str | None, Query(description="Run ID、摘要或语义关键字。")] = None,
    limit: Annotated[int, Query(ge=1, le=100, description="返回记录上限。")] = 30,
) -> list[AgentTraceListItem]:
    return AgentTraceService(db).list_traces(
        agent=agent,
        status=status_value,
        source=source,
        conversation_id=conversation_id,
        keyword=keyword,
        limit=limit,
    )


@router.get(
    "/conversations/{conversation_id}",
    response_model=AgentConversationTraceRead,
    summary="读取会话 Agent Trace",
    description="按 `conversation_id` 返回该会话下多轮运行的 trace 详情。",
)
def get_conversation_trace(
    conversation_id: str,
    db: DbSession,
    _: Annotated[object, Depends(require_platform_admin_user)],
) -> AgentConversationTraceRead:
    return AgentTraceService(db).get_conversation_trace(conversation_id)


@router.get(
    "/{run_id}",
    response_model=AgentTraceDetailRead,
    summary="读取单次 Agent Trace",
    description="按 `run_id` 返回运行摘要、事件时间线、语义解析、工具调用和关联会话消息。",
    responses={
        status.HTTP_404_NOT_FOUND: {
            "model": ErrorResponse,
            "description": "Trace 运行记录不存在。",
        }
    },
)
def get_agent_trace(
    run_id: str,
    db: DbSession,
    _: Annotated[object, Depends(require_platform_admin_user)],
) -> AgentTraceDetailRead:
    trace = AgentTraceService(db).get_trace(run_id)
    if trace is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Agent trace not found")
    return trace
