"""Main CyberFlage orchestration class."""

from __future__ import annotations

import logging
from typing import Any

from .alerts.manager import AlertManager
from .core.decision_engine import DecisionEngine
from .core.signals import events_to_signals
from .dashboard.server import DashboardServer
from .deception.engine import DeceptionEngine
from .network.monitor import NetworkMonitor
from .persistence.manager import PersistenceManager


class CyberFlage:
    """Orchestrates scanning, decisioning, deception, alerts, and persistence."""

    def __init__(self, config: dict[str, Any]) -> None:
        self.config = config
        self.logger = logging.getLogger("cyberflage.app")
        self.decision_engine = DecisionEngine(config)
        self.network_monitor = NetworkMonitor(config)
        self.deception_engine = DeceptionEngine(config)
        self.alert_manager = AlertManager(config)
        self.persistence_manager = PersistenceManager(config)
        self.dashboard_server = DashboardServer(config)
        self.last_state: dict[str, Any] = {}

    def start_dashboard(self) -> None:
        """Start optional dashboard when enabled."""
        self.dashboard_server.start()

    def run_once(self) -> dict[str, Any]:
        """Run one explicit pipeline cycle: Event -> Signal -> Feature -> Risk -> Action."""
        try:
            events = self.network_monitor.scan()
            signals = events_to_signals(events)
            level, features, risk_score, explanation = self.decision_engine.ingest_signals(signals)
            action = self.deception_engine.evaluate(level)
            self.alert_manager.dispatch_explanation(explanation)
            self.alert_manager.dispatch(level, action)
        except Exception as exc:
            self.logger.exception("run_once failed: %s", exc)
            events = []
            signals = []
            features = []
            level = "LOW"
            risk_score = self.decision_engine.risk_manager.score
            action = "Monitoring continued due to safe-fail mode."

        state = {
            "events": [event.event_type for event in events],
            "signals": [signal.name for signal in signals],
            "features": {feature.name: feature.value for feature in features},
            "explanation": explanation if "explanation" in locals() else [],
            "risk_score": risk_score,
            "level": level,
            "action": action,
        }
        self.dashboard_server.update_status(state)
        try:
            self.persistence_manager.save(state)
        except Exception as exc:
            self.logger.exception("state save failed: %s", exc)
        self.last_state = state
        return state
