from __future__ import annotations

from gui.adapters import format_timestamp
from gui.widgets import DataTable, Page


class AlertsPage(Page):
    def __init__(self, parent, details_callback=None):
        super().__init__(parent, "Alerts", "Stored alerts and high-risk telemetry requiring review")
        self.details_callback = details_callback
        self.table = DataTable(self, [("severity", "Severity", 85), ("timestamp", "Timestamp", 150),
                                      ("process", "Process", 150), ("pid", "PID", 65), ("rule", "Rule", 100),
                                      ("reason", "Reason", 260), ("status", "Status", 90)])
        self.table.grid(row=2, column=0, sticky="nsew"); self.rowconfigure(2, weight=1)
        self.rows = []
        self.table.tree.bind("<Double-1>", lambda _event: self._show_details())

    def refresh(self, snapshot):
        rows = []
        for item in snapshot["alerts"]:
            rows.append({**item, "severity": item.get("severity", "info"), "timestamp": format_timestamp(item.get("timestamp")),
                         "process": item.get("process_name") or item.get("title", ""), "pid": item.get("pid") or item.get("process_id", ""),
                         "rule": item.get("rule_id", ""), "reason": item.get("description") or "Rule finding",
                         "status": item.get("status", "New")})
        self.rows = rows
        self.table.set_rows(rows)

    def _show_details(self):
        selected = self.table.tree.selection()
        if not selected or self.details_callback is None:
            return
        alert_id = str(self.table.tree.set(selected[0], "rule"))
        timestamp = str(self.table.tree.set(selected[0], "timestamp"))
        alert = next((item for item in self.rows if str(item.get("rule_id")) == alert_id
                      and str(item.get("timestamp")) == timestamp), None)
        if alert is not None:
            self.details_callback(alert)
