from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional

from core.reporting import ReportBuilder


class Dashboard:
    """Small local dashboard interface for the monitoring baseline."""

    def __init__(self, events: Optional[Iterable[Dict[str, Any]]] = None, alerts: Optional[Iterable[Dict[str, Any]]] = None):
        self.events = list(events or [])
        self.alerts = list(alerts or [])

    def load_jsonl(self, path: str | Path) -> None:
        file_path = Path(path)
        if not file_path.exists():
            self.events = []
            self.alerts = []
            return

        entries: List[Dict[str, Any]] = []
        with file_path.open("r", encoding="utf-8") as handle:
            for line in handle:
                if not line.strip():
                    continue
                try:
                    entries.append(json.loads(line))
                except json.JSONDecodeError:
                    continue

        self.events = [item for item in entries if item.get("event")]
        self.alerts = [item for item in entries if item.get("rule_id") or item.get("alert_id")]

    def summary(self) -> Dict[str, Any]:
        return ReportBuilder(self.events, self.alerts).build_summary()

    def render(self) -> str:
        return ReportBuilder(self.events, self.alerts).render_text()
