"""Monitoring and tracking models for Mission Control."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID, uuid4

from sqlalchemy import JSON, Column, Index
from sqlmodel import Field

from app.core.time import utcnow
from app.models.base import QueryModel

RUNTIME_ANNOTATION_TYPES = (datetime,)


class CostSnapshot(QueryModel, table=True):
    """Timestamped cost readings from the gateway RPC."""

    __tablename__ = "cost_snapshots"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    gateway_id: UUID = Field(default=None, foreign_key="gateways.id", index=True)
    period_start: datetime = Field(nullable=False)
    period_end: datetime = Field(nullable=False)
    total_cost: float = Field(nullable=False, default=0.0)
    model_costs: dict | None = Field(default=None, sa_column=Column(JSON))
    provider_costs: dict | None = Field(default=None, sa_column=Column(JSON))
    token_counts: dict | None = Field(default=None, sa_column=Column(JSON))
    collected_at: datetime = Field(default_factory=utcnow)
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_cost_snapshots_org_created", "organization_id", "created_at"),
        Index("ix_cost_snapshots_org_gateway", "organization_id", "gateway_id"),
    )


class CronJobStatus(QueryModel, table=True):
    """Cron job state tracked from gateway RPC cron.list/cron.status."""

    __tablename__ = "cron_job_statuses"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    gateway_id: UUID = Field(default=None, foreign_key="gateways.id", index=True)
    job_name: str = Field(nullable=False, index=True)
    schedule: str = Field(nullable=False)
    enabled: bool = Field(default=True)
    last_run_at: datetime | None = Field(default=None)
    next_run_at: datetime | None = Field(default=None)
    status: str = Field(nullable=False, default="idle")
    failure_count: int = Field(default=0)
    last_error: str | None = Field(default=None)
    metadata_: dict | None = Field(default=None, sa_column=Column(JSON))
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_cron_job_statuses_org_created", "organization_id", "created_at"),
        Index("ix_cron_job_statuses_org_gateway", "organization_id", "gateway_id"),
    )


class SessionEvent(QueryModel, table=True):
    """Session lifecycle events from gateway RPC sessions.list/preview."""

    __tablename__ = "session_events"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    gateway_id: UUID = Field(default=None, foreign_key="gateways.id", index=True)
    session_key: str = Field(nullable=False, index=True)
    event_type: str = Field(nullable=False)
    model: str | None = Field(default=None)
    agent_id: str | None = Field(default=None)
    channel: str | None = Field(default=None)
    context_percent: float | None = Field(default=None)
    token_counts: dict | None = Field(default=None, sa_column=Column(JSON))
    cost: float | None = Field(default=None)
    metadata_: dict | None = Field(default=None, sa_column=Column(JSON))
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_session_events_org_created", "organization_id", "created_at"),
        Index("ix_session_events_org_gateway", "organization_id", "gateway_id"),
    )


class SubAgentRun(QueryModel, table=True):
    """Sub-agent execution records."""

    __tablename__ = "sub_agent_runs"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    gateway_id: UUID = Field(default=None, foreign_key="gateways.id", index=True)
    parent_session_key: str = Field(nullable=False, index=True)
    session_event_id: UUID | None = Field(default=None, foreign_key="session_events.id", index=True)
    agent: str | None = Field(default=None)
    model: str | None = Field(default=None)
    status: str = Field(nullable=False, default="pending")
    duration_ms: int | None = Field(default=None)
    cost: float | None = Field(default=None)
    token_counts: dict | None = Field(default=None, sa_column=Column(JSON))
    metadata_: dict | None = Field(default=None, sa_column=Column(JSON))
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_sub_agent_runs_org_created", "organization_id", "created_at"),
        Index("ix_sub_agent_runs_org_gateway", "organization_id", "gateway_id"),
    )


class SystemHealthMetric(QueryModel, table=True):
    """System metrics from gateway health/status endpoints and host collection."""

    __tablename__ = "system_health_metrics"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    gateway_id: UUID = Field(default=None, foreign_key="gateways.id", index=True)
    cpu_percent: float | None = Field(default=None)
    cpu_cores: int | None = Field(default=None)
    ram_used_bytes: int | None = Field(default=None)
    ram_total_bytes: int | None = Field(default=None)
    ram_percent: float | None = Field(default=None)
    swap_used_bytes: int | None = Field(default=None)
    swap_total_bytes: int | None = Field(default=None)
    swap_percent: float | None = Field(default=None)
    disk_path: str = Field(default="/")
    disk_used_bytes: int | None = Field(default=None)
    disk_total_bytes: int | None = Field(default=None)
    disk_percent: float | None = Field(default=None)
    gateway_live: bool | None = Field(default=None)
    gateway_ready: bool | None = Field(default=None)
    gateway_uptime_ms: int | None = Field(default=None)
    gateway_pid: int | None = Field(default=None)
    gateway_version: str | None = Field(default=None)
    metadata_: dict | None = Field(default=None, sa_column=Column(JSON))
    collected_at: datetime = Field(default_factory=utcnow)
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_system_health_metrics_org_created", "organization_id", "created_at"),
        Index("ix_system_health_metrics_org_gateway", "organization_id", "gateway_id"),
    )
