"""Pydantic models for agent session endpoints."""

from __future__ import annotations

from datetime import datetime
from typing import Literal, Optional

from pydantic import BaseModel

EVENT_TYPES = Literal[
    "tool_call", "tool_result", "file_read", "file_write",
    "git_op", "error", "info", "message", "checkpoint", "start",
]


class SessionCreate(BaseModel):
    project_id: str
    task_id: Optional[int] = None
    loop_id: str = ""
    model: str = ""
    hostname: str = ""


class SessionUpdate(BaseModel):
    task_id: Optional[int] = None
    status: Optional[str] = None
    exit_code: Optional[int] = None
    tokens_input: Optional[int] = None
    tokens_output: Optional[int] = None
    cost_usd: Optional[float] = None
    error_summary: Optional[str] = None
    ended_at: Optional[datetime] = None


class SessionResponse(BaseModel):
    id: int
    project_id: str
    task_id: Optional[int]
    loop_id: str
    model: str
    hostname: str
    status: str
    exit_code: Optional[int]
    tokens_input: int
    tokens_output: int
    cost_usd: float
    error_summary: str
    started_at: Optional[datetime]
    ended_at: Optional[datetime]
    updated_at: Optional[datetime] = None
    duration_seconds: Optional[float] = None


class SessionEventCreate(BaseModel):
    session_id: int
    event_type: EVENT_TYPES
    tool_name: str = ""
    detail: str = ""
    tool_args: Optional[dict] = None


class SessionEventResponse(BaseModel):
    id: int
    session_id: int
    event_type: EVENT_TYPES
    tool_name: str
    detail: str
    tool_args: Optional[dict] = None
    timestamp: datetime


class SessionDetailResponse(BaseModel):
    id: int
    project_id: str
    task_id: Optional[int]
    loop_id: str
    model: str
    hostname: str
    status: str
    exit_code: Optional[int]
    tokens_input: int
    tokens_output: int
    cost_usd: float
    error_summary: str
    started_at: Optional[datetime]
    ended_at: Optional[datetime]
    updated_at: Optional[datetime] = None
    duration_seconds: Optional[float] = None
    events: list[SessionEventResponse] = []
    task_title: Optional[str] = None


class SessionStatsResponse(BaseModel):
    project_id: str
    total_sessions: int
    completed_sessions: int
    failed_sessions: int
    success_rate: float
    avg_duration_seconds: Optional[float]
    total_tokens_input: int
    total_tokens_output: int
    total_cost_usd: float
    sessions_by_model: dict
