from __future__ import annotations

from datetime import datetime
from typing import Any

from pydantic import BaseModel, ConfigDict, Field

from app.schemas.agent_run import AgentRunRead, AgentToolCallRead, SemanticParseRead
from app.schemas.orchestrator import ConversationMessageRead


class AgentTraceEventRead(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: str
    run_id: str
    conversation_id: str | None = None
    sequence: int
    stage: str
    event_name: str
    title: str
    summary: str | None = None
    status: str
    input_json: dict[str, Any] = Field(default_factory=dict)
    output_json: dict[str, Any] = Field(default_factory=dict)
    error_message: str | None = None
    started_at: datetime
    finished_at: datetime | None = None
    duration_ms: int = 0
    created_at: datetime


class AgentTraceListItem(BaseModel):
    run_id: str
    conversation_id: str | None = None
    agent: str
    source: str
    status: str
    scenario: str | None = None
    intent: str | None = None
    title: str
    summary: str | None = None
    event_count: int = 0
    tool_call_count: int = 0
    failed_tool_call_count: int = 0
    started_at: datetime
    finished_at: datetime | None = None
    duration_ms: int = 0


class AgentTraceDetailRead(BaseModel):
    run: AgentRunRead
    conversation_id: str | None = None
    events: list[AgentTraceEventRead] = Field(default_factory=list)
    semantic_parse: SemanticParseRead | None = None
    tool_calls: list[AgentToolCallRead] = Field(default_factory=list)
    conversation_messages: list[ConversationMessageRead] = Field(default_factory=list)
    fallback_generated: bool = False


class AgentConversationTraceRead(BaseModel):
    conversation_id: str
    runs: list[AgentTraceDetailRead] = Field(default_factory=list)
