"""Health and system status model."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, List, Optional


@dataclass
class HealthStatus:
    """System health and connection status returned by GET /api/health.

    Attributes
    ----------
    status : str
        "ok" when the service is healthy.
    ticks_received : int
        Total tick count received since server start.
    last_tick_at : str | None
        ISO timestamp of the most recent tick.
    symbols_cached : int
        Number of symbols currently cached in memory.
    symbols : List[str]
        Up to 20 cached symbol names.
    db_ok : bool
        Whether MySQL is reachable.
    has_mysql : bool
        Whether pymysql is installed.
    server_time_shanghai : str
        Current server time in Shanghai timezone.
    server_ts_ms : int
        Server timestamp in milliseconds.
    buffer_pending : int
        Number of quotes waiting in the write buffer.
    latest_flush_age_ms : int
        Milliseconds since the last database flush.
    """

    status: str
    ticks_received: int
    last_tick_at: Optional[str]
    symbols_cached: int
    symbols: List[str]
    db_ok: bool
    has_mysql: bool
    server_time_shanghai: str
    server_ts_ms: int
    buffer_pending: int
    latest_flush_age_ms: int

    @classmethod
    def from_api(cls, data: Dict[str, Any]) -> "HealthStatus":
        return cls(
            status=data.get("status", ""),
            ticks_received=int(data.get("ticks_received", 0)),
            last_tick_at=data.get("last_tick_at"),
            symbols_cached=int(data.get("symbols_cached", 0)),
            symbols=list(data.get("symbols", [])),
            db_ok=bool(data.get("db_ok", False)),
            has_mysql=bool(data.get("has_mysql", False)),
            server_time_shanghai=data.get("server_time_shanghai", ""),
            server_ts_ms=int(data.get("server_ts_ms", 0)),
            buffer_pending=int(data.get("buffer_pending", 0)),
            latest_flush_age_ms=int(data.get("latest_flush_age_ms", 0)),
        )

    @property
    def is_healthy(self) -> bool:
        return self.status == "ok"
