from __future__ import annotations

from tkinter import ttk

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


class RemediationPage(Page):
    def __init__(self, parent):
        super().__init__(parent, "Remediation", "Read-only recovery, transaction, and audit visibility")
        cards = ttk.Frame(self); cards.grid(row=2, column=0, sticky="ew")
        for i in range(3): cards.columnconfigure(i, weight=1)
        self.total = Card(cards, "Recovery items"); self.total.grid(row=0, column=0, sticky="ew", padx=4)
        self.restore = Card(cards, "Restorable"); self.restore.grid(row=0, column=1, sticky="ew", padx=4)
        self.pending = Card(cards, "Needs review"); self.pending.grid(row=0, column=2, sticky="ew", padx=4)
        ttk.Label(self, text="Transactions", font=("Segoe UI Semibold", 12)).grid(row=3, column=0, sticky="w", pady=(16, 6))
        self.transactions = DataTable(self, [("transaction_id", "Transaction", 150), ("timestamp", "Timestamp", 150),
                                             ("requested_action", "Requested action", 180), ("status", "Status", 90),
                                             ("rollback", "Rollback", 90), ("finding_id", "Finding", 100)], 7)
        self.transactions.grid(row=4, column=0, sticky="nsew")
        ttk.Label(self, text="Audit log", font=("Segoe UI Semibold", 12)).grid(row=5, column=0, sticky="w", pady=(14, 6))
        self.audit = DataTable(self, [("timestamp", "Timestamp", 150), ("action", "Action", 140), ("actor", "Actor", 90),
                                      ("object", "Object", 150), ("details", "Details", 280)], 6)
        self.audit.grid(row=6, column=0, sticky="nsew"); self.rowconfigure(4, weight=1); self.rowconfigure(6, weight=1)

    def refresh(self, snapshot):
        data = snapshot["remediation"]; summary = data["recovery_summary"]
        self.total.set(summary["total_items"]); self.restore.set(summary["restorable_count"]); self.pending.set(summary["needs_review"])
        self.transactions.set_rows([{**item, "timestamp": format_timestamp(item.get("timestamp")),
                                     "rollback": "Available" if item.get("rollback_available") else "None"} for item in data["transactions"]])
        self.audit.set_rows([{**item, "timestamp": format_timestamp(item.get("timestamp")),
                              "details": metadata_summary(item.get("details"))} for item in data["audit"]])

