from __future__ import annotations

import sqlite3
import time
from pathlib import Path


class HistoryStore:
    def __init__(self, path: str) -> None:
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with sqlite3.connect(self.path) as connection:
            connection.execute("create table if not exists snapshots (at integer primary key, events integer, anomalies integer, critical integer, high integer, baseline_ready integer, mcp_events integer)")

    def record(self, status: dict[str, object]) -> None:
        summary = status.get("summary", {}) if isinstance(status.get("summary"), dict) else {}
        anomalies = status.get("anomaly_summary", {}) if isinstance(status.get("anomaly_summary"), dict) else {}
        baseline = status.get("baseline", {}) if isinstance(status.get("baseline"), dict) else {}
        capabilities = status.get("capabilities", {}) if isinstance(status.get("capabilities"), dict) else {}
        mcp = capabilities.get("graylog_mcp", {}) if isinstance(capabilities.get("graylog_mcp"), dict) else {}
        with sqlite3.connect(self.path) as connection:
            connection.execute("insert or replace into snapshots values (?, ?, ?, ?, ?, ?, ?)", (int(time.time()), int(summary.get("total", 0) or 0), int(anomalies.get("total", 0) or 0), int(anomalies.get("critical", 0) or 0), int(anomalies.get("high", 0) or 0), int(baseline.get("sources_ready", 0) or 0), int(mcp.get("events_fetched", 0) or 0)))
            connection.execute("delete from snapshots where at < ?", (int(time.time()) - 7 * 86400,))

    def recent(self, limit: int = 288) -> list[dict[str, int]]:
        with sqlite3.connect(self.path) as connection:
            rows = connection.execute("select at, events, anomalies, critical, high, baseline_ready, mcp_events from snapshots order by at desc limit ?", (limit,)).fetchall()
        return [dict(zip(("at", "events", "anomalies", "critical", "high", "baseline_ready", "mcp_events"), row)) for row in reversed(rows)]
