"""AegisTrade AI Health & Diagnostic Checks."""
from __future__ import annotations

import time
from datetime import datetime, timezone
from typing import Any

from backend.app.config.settings import settings
from backend.app.database.session import db_manager


class HealthService:
    """Continuously evaluates system components and operational readiness."""

    def __init__(self) -> None:
        self.last_market_tick_time: float = time.time()
        self.market_feed_connected: bool = True

    def record_market_tick(self) -> None:
        self.last_market_tick_time = time.time()
        self.market_feed_connected = True

    def check_health(self) -> dict[str, Any]:
        # 1. Database check
        db_ok = False
        try:
            row = db_manager.execute_read_one("SELECT 1 as ping")
            db_ok = bool(row and row["ping"] == 1)
        except Exception:
            db_ok = False

        # 2. Kill switch check
        kill_switch_state = db_manager.get_system_state("KILL_SWITCH_ACTIVE")
        kill_switch_active = kill_switch_state == "true"

        # 3. Data freshness check (30 seconds threshold)
        data_lag = time.time() - self.last_market_tick_time
        if data_lag > 30.0:
            self.market_feed_connected = False

        # 4. Open positions count
        pos_row = db_manager.execute_read_one("SELECT COUNT(*) as count FROM positions WHERE is_open = 1")
        open_positions = pos_row["count"] if pos_row else 0

        # Determine overall system status
        if kill_switch_active:
            status = "HALTED"
        elif not db_ok or not self.market_feed_connected:
            status = "DEGRADED"
        else:
            status = "HEALTHY"

        return {
            "status": status,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "trading_mode": settings.TRADING_MODE.value,
            "kill_switch_active": kill_switch_active,
            "live_trading_enabled": settings.ENABLE_LIVE_TRADING,
            "database_connected": db_ok,
            "market_feed_connected": self.market_feed_connected,
            "data_lag_seconds": round(data_lag, 2),
            "open_positions": open_positions,
            "risk_per_trade_pct": settings.RISK_PER_TRADE_PCT,
            "max_positions_limit": settings.MAX_POSITIONS,
        }


health_service = HealthService()
