"""Schemas for Claude Code Integration API endpoints."""

from __future__ import annotations

from datetime import datetime
from typing import Any

from sqlmodel import SQLModel


# ── Session messages ──────────────────────────────────────────────────────────

class TextBlock(SQLModel):
    text: str
    truncated: bool


class ThinkingBlock(SQLModel):
    text: str
    truncated: bool


class ToolUseBlock(SQLModel):
    tool_use_id: str
    tool_name: str
    input: dict[str, Any]
    input_truncated: bool
    result: str | None = None
    result_truncated: bool = False
    is_error: bool = False


class SessionTokenUsageRead(SQLModel):
    input: int
    output: int
    cache_read: int
    cache_write: int


class SessionMessage(SQLModel):
    uuid: str
    role: str  # "user" | "assistant"
    timestamp: datetime | None = None
    text_blocks: list[TextBlock]
    thinking_blocks: list[ThinkingBlock]
    tool_uses: list[ToolUseBlock]
    model: str | None = None
    tokens: SessionTokenUsageRead | None = None


class SessionMessagesResponse(SQLModel):
    session_id: str
    messages: list[SessionMessage]
    total: int
    has_more: bool


# ── Tool analytics ───────────────────────────────────────────────────────────

class FileEntry(SQLModel):
    path: str
    count: int


class CommandEntry(SQLModel):
    command: str
    count: int


class ToolAnalyticsResponse(SQLModel):
    tool_counts: dict[str, int]
    top_files_read: list[FileEntry]
    top_files_written: list[FileEntry]
    top_commands: list[CommandEntry]
    session_count: int
    date_range_days: int


# ── Session token totals (used in list/detail) ────────────────────────────────

class SessionTokensRead(SQLModel):
    input: int
    output: int
    cache_read: int
    cache_write: int
    total: int


class ClaudeSessionRead(SQLModel):
    session_id: str
    project_dir: str
    cwd: str | None = None
    title: str | None = None
    models: list[str]
    tokens: SessionTokensRead
    cost_usd: float
    message_count: int
    first_message_at: datetime | None = None
    last_message_at: datetime | None = None
    is_active: bool
    entrypoints: list[str]
    git_branch: str | None = None
    version: str | None = None


class ClaudeSessionStatsRead(SQLModel):
    session_count: int
    active_sessions: int
    total_tokens: int
    total_cost_usd: float
    models: list[str]


class ClaudeSessionListResponse(SQLModel):
    sessions: list[ClaudeSessionRead]
    total: int
    stats: ClaudeSessionStatsRead


class ClaudeProjectRead(SQLModel):
    project_dir: str
    cwd: str | None = None
    session_count: int
    total_tokens: int
    total_cost_usd: float
    last_active_at: datetime | None = None
    is_active: bool


class ClaudeConfigRead(SQLModel):
    claude_settings: dict[str, Any]
    codex_config: dict[str, Any]
    codex_rules: list[str]
    claude_credentials_configured: bool
    codex_credentials_configured: bool
