from __future__ import annotations

import copy
import tkinter as tk
from tkinter import messagebox, ttk

from gui.widgets import Page, labeled_entry


class ConfigurationPage(Page):
    def __init__(self, parent, adapter):
        super().__init__(parent, "Configuration", "Validated settings with automatic backup before save")
        self.adapter = adapter; self.payload = {}
        panel = ttk.Frame(self, style="Panel.TFrame", padding=18); panel.grid(row=2, column=0, sticky="new"); panel.columnconfigure(1, weight=1)
        self.enabled = tk.BooleanVar(); self.poll = tk.StringVar(); self.heartbeat = tk.StringVar(); self.path = tk.StringVar(); self.retention = tk.StringVar()
        self.allow = tk.StringVar(); self.watch = tk.StringVar(); self.keywords = tk.StringVar(); self.minimum = tk.StringVar()
        ttk.Checkbutton(panel, text="Monitoring enabled", variable=self.enabled).grid(row=0, column=0, columnspan=2, sticky="w", pady=6)
        for row, (label, var) in enumerate((("Poll interval (seconds)", self.poll), ("Heartbeat interval (seconds)", self.heartbeat),
                                            ("Telemetry JSONL path", self.path), ("Retention (days)", self.retention),
                                            ("Allowlist (comma-separated)", self.allow), ("Watchlist (comma-separated)", self.watch),
                                            ("High-risk keywords (comma-separated)", self.keywords), ("Minimum severity", self.minimum)), 1):
            labeled_entry(panel, label, var, row)
        controls = ttk.Frame(self); controls.grid(row=3, column=0, sticky="w", pady=14)
        ttk.Button(controls, text="Reload", command=self.load).pack(side="left")
        ttk.Button(controls, text="Validate & Save", style="Accent.TButton", command=self.save).pack(side="left", padx=8)
        self.message = ttk.Label(self, text="", style="Muted.TLabel"); self.message.grid(row=4, column=0, sticky="w")
        self.load()

    def load(self):
        try:
            self.payload = self.adapter.load(); telemetry = self.payload["Telemetry"]; rules = self.payload.get("AlertRules", {})
            self.enabled.set(self.payload.get("Enabled", True)); self.poll.set(telemetry["PollIntervalSeconds"])
            self.heartbeat.set(telemetry["HeartbeatIntervalSeconds"]); self.path.set(telemetry["Path"]); self.retention.set(telemetry["RetentionDays"])
            self.allow.set(", ".join(self.payload.get("AllowList", []))); self.watch.set(", ".join(self.payload.get("WatchList", [])))
            self.keywords.set(", ".join(rules.get("HighRiskKeywords", []))); self.minimum.set(rules.get("MinSeverity", "low")); self.message.configure(text="Configuration loaded.")
        except Exception as exc: self.message.configure(text=f"Configuration error: {exc}")

    def save(self):
        try:
            payload = copy.deepcopy(self.payload); payload["Enabled"] = self.enabled.get(); telemetry = payload.setdefault("Telemetry", {})
            telemetry.update({"PollIntervalSeconds": int(self.poll.get()), "HeartbeatIntervalSeconds": int(self.heartbeat.get()),
                              "Path": self.path.get().strip(), "RetentionDays": int(self.retention.get())})
            split = lambda value: [item.strip() for item in value.split(",") if item.strip()]
            payload["AllowList"] = split(self.allow.get()); payload["WatchList"] = split(self.watch.get())
            rules = payload.setdefault("AlertRules", {}); rules["HighRiskKeywords"] = split(self.keywords.get()); rules["MinSeverity"] = self.minimum.get().strip()
            backup = self.adapter.save(payload); self.payload = payload
            messagebox.showinfo("Configuration saved", f"Validated configuration saved.\nBackup: {backup}")
        except Exception as exc: messagebox.showerror("Configuration not saved", str(exc))

    def refresh(self, snapshot): pass

