"""Optional dashboard server."""

from __future__ import annotations

import logging
from typing import Any

try:
    from flask import Flask, jsonify
except Exception:  # pragma: no cover
    Flask = None


class DashboardServer:
    """Starts a simple dashboard only when enabled and Flask is available."""

    def __init__(self, config: dict[str, Any]) -> None:
        dashboard = config.get("dashboard", {})
        self.enabled = bool(dashboard.get("enabled", False))
        self.host = str(dashboard.get("host", "127.0.0.1"))
        self.port = int(dashboard.get("port", 5000))
        self.app = Flask(__name__) if self.enabled and Flask is not None else None
        self._recent_events: list[str] = []
        self._recent_signals: list[str] = []
        self._risk_level = "LOW"
        self._current_state = "Monitoring"

        if self.app is not None:
            self._register_routes()

    def update_status(self, state: dict[str, Any]) -> None:
        """Update dashboard status using last pipeline state."""
        events = state.get("events", [])
        signals = state.get("signals", [])
        self._recent_events = [str(item) for item in events][-5:]
        self._recent_signals = [str(item) for item in signals][-5:]
        self._risk_level = str(state.get("level", "LOW"))

        level_to_state = {
            "LOW": "Monitoring",
            "MEDIUM": "Alert",
            "HIGH": "Alert",
            "CRITICAL": "Decoy",
        }
        self._current_state = level_to_state.get(self._risk_level, "Monitoring")

    def _register_routes(self) -> None:
        assert self.app is not None

        @self.app.get("/health")
        def health() -> dict[str, str]:
            return {"status": "ok"}

        @self.app.get("/status")
        def status() -> Any:
            return jsonify(
                {
                    "risk_level": self._risk_level,
                    "current_state": self._current_state,
                    "recent_events": self._recent_events,
                    "recent_signals": self._recent_signals,
                }
            )

    def start(self) -> None:
        """Start dashboard server or no-op."""
        if not self.enabled or self.app is None:
            logging.getLogger("cyberflage.dashboard").info("Dashboard disabled or Flask unavailable.")
            return

        self.app.run(host=self.host, port=self.port)
