from datetime import datetime
from pydantic import BaseModel


class DbSizeItem(BaseModel):
    name: str
    size_bytes: int


class TableSizeItem(BaseModel):
    schema: str
    table: str
    size_bytes: int


class ReplicationClientItem(BaseModel):
    application_name: str | None = None
    client_addr: str | None = None
    state: str | None = None
    sync_state: str | None = None
    write_lag_seconds: float | None = None
    flush_lag_seconds: float | None = None
    replay_lag_seconds: float | None = None
    replay_lag_bytes: float | None = None


class DiskSpaceInfo(BaseModel):
    source: str
    status: str
    free_bytes: int | None = None
    message: str | None = None


class InstanceOverview(BaseModel):
    server_version: str | None = None
    role: str
    postmaster_start_time: datetime | None = None
    uptime_seconds: float | None = None
    current_database: str | None = None
    port: int | None = None


class StorageOverview(BaseModel):
    current_database_size_bytes: int | None = None
    all_databases: list[DbSizeItem]
    largest_tables: list[TableSizeItem]
    wal_directory_size_bytes: int | None = None
    disk_space: DiskSpaceInfo


class ReplicationOverview(BaseModel):
    mode: str
    replay_lag_seconds: float | None = None
    replication_slots_count: int | None = None
    active_replication_clients: int | None = None
    clients: list[ReplicationClientItem]


class PerformanceOverview(BaseModel):
    xact_commit: int | None = None
    xact_rollback: int | None = None
    deadlocks: int | None = None
    temp_files: int | None = None
    temp_bytes: int | None = None
    blk_read_time: float | None = None
    blk_write_time: float | None = None
    checkpoints_timed: int | None = None
    checkpoints_req: int | None = None
    autovacuum_workers: int | None = None


class DatabaseOverviewOut(BaseModel):
    collected_at: datetime
    cache_ttl_seconds: int
    instance: InstanceOverview
    storage: StorageOverview
    replication: ReplicationOverview
    performance: PerformanceOverview
    partial_failures: list[str]
