from __future__ import annotations

from tkinter import messagebox, ttk

from gui.widgets import Page


class ServicesPage(Page):
    def __init__(self, parent, action_callback):
        super().__init__(parent, "Driver & Relay", "Read-only driver inspection and persistent relay controls")
        self.action_callback = action_callback
        body = ttk.Frame(self, style="Panel.TFrame", padding=18); body.grid(row=2, column=0, sticky="new")
        body.columnconfigure(1, weight=1)
        self.values = {}
        fields = ["Driver state", "Driver installed", "Service name", "Binary path", "Start type", "Driver error",
                  "Relay state", "Relay PID", "Poll interval", "JSONL path", "Database path"]
        for row, name in enumerate(fields):
            ttk.Label(body, text=name, style="PanelMuted.TLabel").grid(row=row, column=0, sticky="nw", padx=(0, 25), pady=5)
            label = ttk.Label(body, text="—", style="Panel.TLabel", wraplength=750); label.grid(row=row, column=1, sticky="w", pady=5); self.values[name] = label
        controls = ttk.Frame(self); controls.grid(row=3, column=0, sticky="w", pady=16)
        ttk.Button(controls, text="Refresh", command=lambda: action_callback("refresh")).pack(side="left")
        ttk.Button(controls, text="Start Relay", style="Accent.TButton", command=lambda: action_callback("start")).pack(side="left", padx=8)
        ttk.Button(controls, text="Stop Relay", style="Danger.TButton", command=self._stop).pack(side="left")
        ttk.Label(self, text="Driver start/stop is intentionally not exposed; use an elevated, authorized lab workflow.", style="Muted.TLabel").grid(row=4, column=0, sticky="w")

    def _stop(self):
        if messagebox.askyesno("Stop telemetry relay", "Stop the persistent telemetry relay cleanly?"):
            self.action_callback("stop")

    def refresh(self, snapshot):
        driver, relay = snapshot["driver"], snapshot["relay"]
        values = {"Driver state": driver["state"], "Driver installed": "Yes" if driver["installed"] else "No",
                  "Service name": driver["service_name"], "Binary path": driver["binary_path"], "Start type": driver["start_type"],
                  "Driver error": driver.get("error") or "None", "Relay state": "Running" if relay["running"] else "Stopped",
                  "Relay PID": relay.get("pid") or "—", "Poll interval": f"{relay['poll_interval']} seconds",
                  "JSONL path": relay["output_path"], "Database path": snapshot["database_path"]}
        for key, value in values.items(): self.values[key].configure(text=value)

