from __future__ import annotations

import json
import tkinter as tk
from tkinter import ttk

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


class LogsPage(Page):
    def __init__(self, parent):
        super().__init__(parent, "Logs", "Recent JSONL telemetry (view only)")
        controls = ttk.Frame(self); controls.grid(row=2, column=0, sticky="ew", pady=(0, 10))
        self.search = tk.StringVar(); self.severity = tk.StringVar(value="All"); self.event = tk.StringVar(value="All"); self.auto = tk.BooleanVar(value=True)
        ttk.Entry(controls, textvariable=self.search, width=30).pack(side="left")
        ttk.Combobox(controls, textvariable=self.severity, values=["All", "info", "low", "medium", "high", "critical"], state="readonly", width=12).pack(side="left", padx=8)
        self.event_box = ttk.Combobox(controls, textvariable=self.event, values=["All"], state="readonly", width=18); self.event_box.pack(side="left")
        ttk.Button(controls, text="Apply", command=self._render).pack(side="left", padx=8)
        ttk.Checkbutton(controls, text="Auto refresh", variable=self.auto).pack(side="right")
        self.table = DataTable(self, [("timestamp", "Timestamp", 155), ("event", "Event", 130), ("pid", "PID", 65),
                                      ("image", "Process", 150), ("severity", "Severity", 80), ("source", "Source", 110),
                                      ("details", "Entry", 300)])
        self.table.grid(row=3, column=0, sticky="nsew"); self.rowconfigure(3, weight=1); self.rows = []
        controls2 = ttk.Frame(self); controls2.grid(row=4, column=0, sticky="e", pady=8)
        ttk.Button(controls2, text="Copy selected", command=self.copy).pack(side="left")
        ttk.Button(controls2, text="Jump to newest", command=lambda: self.table.tree.yview_moveto(0)).pack(side="left", padx=8)

    def refresh(self, snapshot):
        if not self.auto.get() and self.rows: return
        self.rows = [{**item, "timestamp": format_timestamp(item.get("timestamp")), "details": metadata_summary(item, 140)} for item in snapshot["jsonl_events"]]
        self.event_box.configure(values=["All"] + sorted({str(x.get("event")) for x in self.rows if x.get("event")})); self._render()

    def _render(self): self.table.set_rows(filter_rows(self.rows, self.search.get(), severity=self.severity.get(), event=self.event.get()))

    def copy(self):
        selected = self.table.tree.selection()
        if selected:
            text = "\t".join(self.table.tree.item(selected[0], "values")); self.clipboard_clear(); self.clipboard_append(text)

