from __future__ import annotations

from datetime import datetime
from typing import Any

from pydantic import BaseModel, ConfigDict, Field


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

    id: str
    run_id: str
    tool_type: str
    tool_name: str
    request_json: dict[str, Any]
    response_json: dict[str, Any]
    status: str
    duration_ms: int
    error_message: str | None
    created_at: datetime


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

    id: str
    run_id: str
    user_id: str | None
    raw_query: str
    scenario: str
    intent: str
    entities_json: list[Any]
    time_range_json: dict[str, Any]
    metrics_json: list[Any]
    constraints_json: list[Any]
    risk_flags_json: list[Any]
    permission_json: dict[str, Any]
    confidence: float
    created_at: datetime


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

    id: str
    run_id: str
    agent: str
    source: str
    user_id: str | None
    task_id: str | None
    ontology_json: dict[str, Any]
    route_json: dict[str, Any]
    permission_level: str
    status: str
    result_summary: str | None
    error_message: str | None
    started_at: datetime
    finished_at: datetime | None
    tool_calls: list[AgentToolCallRead] = Field(default_factory=list)
    semantic_parse: SemanticParseRead | None = None


class AgentRunStatsRead(BaseModel):
    window_limit: int
    total_runs: int
    succeeded_runs: int
    blocked_runs: int
    failed_runs: int
    tool_call_count: int
    failed_tool_call_count: int
    llm_call_count: int
    failed_llm_call_count: int
    model_fallback_count: int
    model_guardrail_count: int
    agents: dict[str, int] = Field(default_factory=dict)
    statuses: dict[str, int] = Field(default_factory=dict)
    tool_statuses: dict[str, int] = Field(default_factory=dict)
    recent_errors: list[dict[str, Any]] = Field(default_factory=list)
