#!/usr/bin/env python3
"""
Monkey Monitor - Development Service Monitor with D2C Theme
Visual interface for managing development services with auto-stop capabilities

Themed with D2C Neon Electric colors for a vibrant, modern developer experience
"""

import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
gi.require_version('Gdk', '4.0')
from gi.repository import Gtk, Adw, GLib, Gdk
import subprocess
import sys
import os
import threading
import time
from html import escape
from typing import Dict

from monkey_pc_page import PcControlsPage, _heading_markup
from monkey_monitor_common import monitor_autostart_status, set_monitor_autostart

# Add src directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
    from monkey_monitor_common import (get_mcp_instances,
                                       terminate_mcp_instance, MCP_PATTERNS)
    MCP_SUPPORT = True
except ImportError:
    MCP_SUPPORT = False

try:
    from monkey_mcp_policy import (PolicyError, allow_now as allow_mcp_now,
                                   set_policy as set_mcp_policy,
                                   status as mcp_policy_status)
    MCP_POLICY_SUPPORT = True
except ImportError:
    MCP_POLICY_SUPPORT = False

# D2C Neon Electric Theme Colors
# D2C Neon Electric tokens — sourced from desktop_monkey.theme (single source
# of truth). Fallback hexes keep the standalone install rendering correctly
# when the desktop-monkey wheel is not importable.
try:
    from desktop_monkey.theme.tokens import BRAND as _DM_BRAND

    def _brand(name: str) -> str:
        return _DM_BRAND[name]
except ImportError:  # standalone monitor install without the desktop-monkey wheel
    _DM_BRAND_FALLBACK = {
        'blue': '#2563eb',
        'cyan': '#01cec9',
        'purple': '#6c5ce7',
        'pink': '#ec4899',
        'orange': '#ff7675',
        'amber': '#f5ae39',
        'yellow': '#fdcb6e',
        'green': '#22c55e',
        'lavender': '#a29bfe',
    }

    def _brand(name: str) -> str:
        return _DM_BRAND_FALLBACK[name]

THEME_COLORS = {
    'electric_blue': _brand('blue'),
    'electric_cyan': _brand('cyan'),
    'electric_purple': _brand('purple'),
    'electric_pink': _brand('pink'),
    'electric_orange': _brand('orange'),
    'electric_amber': _brand('amber'),
    'electric_yellow': _brand('yellow'),
    'electric_green': _brand('green'),   # decorative only — never a state colour
    'electric_lavender': _brand('lavender'),
    'dark_bg': '#0a0e1a',
    'dark_bg_secondary': '#1a1f2e',
    'dark_bg_tertiary': '#2c3447',
}

# Semantic status tokens — colourblind-safe blue / cyan / purple / amber set
# (zero red/green state pairs). Every state ALSO carries an explicit
# non-colour badge: [OK], [WARN], [HIGH], [RUN], [STOP].
STATUS_OK = _brand('blue')     # normal / low tier — electric blue
STATUS_RUN = _brand('cyan')    # running / active — electric cyan
STATUS_WARN = _brand('amber')  # warning tier — electric amber
STATUS_HIGH = _brand('purple') # high / critical tier — electric purple

# Service definitions (shared with CLI)
SERVICES = {
    'mysql': {
        'service': 'mysql.service',
        'monitor': 'mysql-idle-monitor.service',
        'port': 3306,
        'description': 'MySQL Database Server'
    },
    'docker': {
        'service': 'docker.service',
        'description': 'Docker Container Engine',
        'observe_only': True,
    },
    'postgresql': {
        'service': 'postgresql.service',
        'port': 5432,
        'description': 'PostgreSQL Database Server'
    },
}


def run_cmd(cmd: list) -> tuple:
    """Run command and return (returncode, stdout, stderr)"""
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=4)
        return result.returncode, result.stdout, result.stderr
    except Exception as e:
        return 1, '', str(e)


def get_service_status(service_name: str) -> Dict:
    """Get detailed status of a systemd service"""
    ret, out, err = run_cmd(['systemctl', 'show', service_name,
                             '--no-pager',
                             '-p', 'ActiveState',
                             '-p', 'SubState',
                             '-p', 'MemoryCurrent',
                             '-p', 'MemoryPeak',
                             '-p', 'MainPID'])

    status = {}
    for line in out.split('\n'):
        if '=' in line:
            key, value = line.split('=', 1)
            status[key] = value

    # Parse memory
    try:
        mem_current = int(status.get('MemoryCurrent', '0'))
    except ValueError:
        mem_current = 0

    try:
        mem_peak = int(status.get('MemoryPeak', '0'))
    except ValueError:
        mem_peak = 0

    return {
        'active': status.get('ActiveState', 'unknown'),
        'sub': status.get('SubState', 'unknown'),
        'memory_mb': mem_current / 1024 / 1024 if mem_current > 0 else 0,
        'memory_peak_mb': mem_peak / 1024 / 1024 if mem_peak > 0 else 0,
        'pid': int(status.get('MainPID', '0')),
    }


def get_connection_count(port: int) -> int:
    """Get number of active connections to a port"""
    ret, out, err = run_cmd(['ss', '-tn'])
    if ret != 0:
        return -1

    count = 0
    for line in out.split('\n'):
        if f':{port}' in line and 'ESTAB' in line:
            count += 1
    return count


def get_thermal_info() -> Dict:
    """Get CPU/GPU temperatures and fan speeds from sensors"""
    ret, out, err = run_cmd(['sensors'])

    thermal = {
        'cpu_temp': 0,
        'gpu_temp': 0,
        'fan1_rpm': 0,
        'fan2_rpm': 0,
        'nvme_temp': 0,
    }

    if ret != 0:
        return thermal

    current_adapter = ''
    for line in out.split('\n'):
        line = line.strip()

        # Track which adapter we're in
        if 'coretemp' in line:
            current_adapter = 'cpu'
        elif 'ath10k' in line or 'nvidia' in line or 'amdgpu' in line:
            current_adapter = 'gpu'
        elif 'dell_smm' in line:
            current_adapter = 'fans'
        elif 'nvme' in line:
            current_adapter = 'nvme'

        # Parse temperature/fan data
        if 'Package id 0:' in line and current_adapter == 'cpu':
            try:
                thermal['cpu_temp'] = float(line.split('+')[1].split('°')[0])
            except:
                pass
        elif 'temp1:' in line and current_adapter == 'gpu':
            try:
                thermal['gpu_temp'] = float(line.split('+')[1].split('°')[0])
            except:
                pass
        elif 'fan1:' in line and current_adapter == 'fans':
            try:
                thermal['fan1_rpm'] = int(line.split(':')[1].split('RPM')[0].strip())
            except:
                pass
        elif 'fan2:' in line and current_adapter == 'fans':
            try:
                thermal['fan2_rpm'] = int(line.split(':')[1].split('RPM')[0].strip())
            except:
                pass
        elif 'Composite:' in line and current_adapter == 'nvme':
            try:
                thermal['nvme_temp'] = float(line.split('+')[1].split('°')[0])
            except:
                pass

    return thermal


def get_thermal_mode() -> str:
    """Get current thermal/power mode"""
    try:
        with open('/sys/firmware/acpi/platform_profile', 'r') as f:
            return f.read().strip()
    except:
        return 'unknown'


class ServiceRow(Gtk.ListBoxRow):
    """A row representing a single service"""

    def __init__(self, service_name: str, config: dict, parent_window,
                 *, startup_only: bool = False):
        super().__init__()
        self.service_name = service_name
        self.config = config
        self.parent_window = parent_window
        self.startup_only = startup_only

        # Main horizontal box
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        hbox.set_margin_start(12)
        hbox.set_margin_end(12)
        hbox.set_margin_top(8)
        hbox.set_margin_bottom(8)

        # Left side: Service info
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
        vbox.set_hexpand(True)

        # Service name
        self.name_label = Gtk.Label()
        self.name_label.set_markup(f"<b>{service_name}</b>")
        self.name_label.set_xalign(0)
        vbox.append(self.name_label)

        # Description
        desc_label = Gtk.Label(label=config['description'])
        desc_label.set_xalign(0)
        desc_label.add_css_class('dim-label')
        desc_label.set_wrap(True)
        vbox.append(desc_label)

        self.control_row = None
        if not config.get('observe_only'):
            self.startup_label = Gtk.Label(label="Startup policy unavailable")
            self.startup_label.set_xalign(0)
            self.startup_label.set_wrap(True)
            self.startup_label.add_css_class('dim-label')
            vbox.append(self.startup_label)

        # Status info
        self.status_label = Gtk.Label()
        self.status_label.set_xalign(0)
        self.status_label.add_css_class('caption')
        vbox.append(self.status_label)

        hbox.append(vbox)

        # Memory label
        self.memory_label = Gtk.Label()
        self.memory_label.set_width_chars(12)
        self.memory_label.set_visible(not startup_only)
        hbox.append(self.memory_label)

        # Action buttons box
        button_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        button_box.set_valign(Gtk.Align.CENTER)

        self.start_button = Gtk.Button(label="Start")
        self.start_button.add_css_class('suggested-action')
        self.start_button.connect('clicked', self.on_start_clicked)
        button_box.append(self.start_button)

        self.stop_button = Gtk.Button(label="Stop")
        self.stop_button.add_css_class('destructive-action')
        self.stop_button.connect('clicked', self.on_stop_clicked)
        button_box.append(self.stop_button)

        if config.get('observe_only'):
            self.start_button.set_visible(False)
            self.stop_button.set_visible(False)
            button_box.append(Gtk.Label(label="Use Containers"))

        self.logs_button = Gtk.Button(label="Logs")
        self.logs_button.connect('clicked', self.on_logs_clicked)
        button_box.append(self.logs_button)

        hbox.append(button_box)
        button_box.set_visible(not startup_only)
        self.status_label.set_visible(not startup_only)

        if not config.get('observe_only'):
            policy_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
            policy_box.set_margin_start(12)
            policy_box.set_margin_bottom(8)
            policy_box.append(Gtk.Label(label="At startup"))
            self.startup_dropdown = Gtk.DropDown.new_from_strings(
                ["Automatic", "Manual", "Blocked"])
            self.startup_dropdown.add_css_class("work-type-dropdown")
            self.startup_dropdown.connect('notify::selected', self.on_startup_draft)
            policy_box.append(self.startup_dropdown)
            self.apply_startup_button = Gtk.Button(label="Apply startup policy")
            self.apply_startup_button.connect('clicked', self.on_apply_startup)
            policy_box.append(self.apply_startup_button)
            vbox.append(policy_box)
            self._startup_modes = ("automatic", "manual", "blocked")
            self._updating_startup = False
            self._startup_dirty = False
            self.startup_dropdown.set_sensitive(False)
            self.apply_startup_button.set_sensitive(False)

        self.set_child(hbox)

        self.status_label.set_text("Checking service…")
        self.memory_label.set_text("--")
        self.start_button.set_sensitive(False)
        self.stop_button.set_sensitive(False)

    def on_startup_draft(self, dropdown, _param):
        if self._updating_startup or self.control_row is None:
            return
        index = dropdown.get_selected()
        self._startup_dirty = (index < len(self._startup_modes) and
                               self._startup_modes[index] != self.control_row.get("startup_mode"))
        self.apply_startup_button.set_sensitive(self._startup_dirty and
                                                self.parent_window.service_controls_ready())

    def on_apply_startup(self, _button):
        index = self.startup_dropdown.get_selected()
        if index < len(self._startup_modes) and self._startup_dirty:
            self.parent_window.submit_service("set_service_startup", self.service_name,
                                              mode=self._startup_modes[index])

    def update_control_status(self, row: dict, *, ready: bool):
        self.control_row = row
        loaded = row.get("loaded") is True
        active = row.get("active") == "active"
        mode = row.get("startup_mode")
        draft_index = self.startup_dropdown.get_selected()
        if (self._startup_dirty and draft_index < len(self._startup_modes) and
                self._startup_modes[draft_index] == mode):
            self._startup_dirty = False
        if not self._startup_dirty and mode in self._startup_modes:
            self._updating_startup = True
            try:
                self.startup_dropdown.set_selected(self._startup_modes.index(mode))
            finally:
                self._updating_startup = False
        mode_name = {"automatic": "Automatic at boot", "manual": "Manual at boot",
                     "blocked": "Blocked from starting"}.get(mode, "Startup policy unknown")
        reason = row.get("reason")
        self.startup_label.set_text(mode_name + (f" · {reason}" if reason else ""))
        state = "Running" if active else "Stopped" if row.get("active") == "inactive" else \
                str(row.get("active") or "Unknown").capitalize()
        clients = row.get("connection_count")
        detail = f"{state} · TCP clients: {clients if isinstance(clients, int) else 'unknown'}"
        if row.get("connection_metric"):
            detail += " · Unix socket clients not counted"
        self.status_label.set_text(detail)
        self.memory_label.set_text("--")
        can_act = ready and loaded
        self.start_button.set_sensitive(can_act and not active and mode != "blocked")
        self.stop_button.set_sensitive(can_act and active)
        self.startup_dropdown.set_sensitive(can_act)
        self.apply_startup_button.set_sensitive(can_act and self._startup_dirty)

    def set_control_unavailable(self):
        self.status_label.set_text("PC controls unavailable · Retry services")
        self.startup_label.set_text("Startup policy unavailable")
        self.start_button.set_sensitive(False)
        self.stop_button.set_sensitive(False)
        self.startup_dropdown.set_sensitive(False)
        self.apply_startup_button.set_sensitive(False)

    def update_status(self, status: dict, conn_count: int = -1,
                      monitor_active: bool = False):
        """Render a worker-collected status without blocking GTK."""

        # Update status text
        is_running = status['active'] == 'active'

        if is_running:
            # Check for connections
            conn_info = ""
            if 'port' in self.config:
                if conn_count == 0:
                    conn_info = " • No connections"
                elif conn_count > 0:
                    conn_info = f" • {conn_count} connection{'s' if conn_count > 1 else ''}"

            # Check if monitored
            monitor_info = ""
            if monitor_active:
                monitor_info = " • Monitored"

            self.status_label.set_markup(
                f"<span color='{STATUS_RUN}'>● [RUN] Running</span>{conn_info}{monitor_info}")
            self.start_button.set_sensitive(False)
            self.stop_button.set_sensitive(not self.config.get('observe_only', False))
        else:
            self.status_label.set_markup("<span color='#999999'>○ [STOP] Stopped</span>")
            self.start_button.set_sensitive(not self.config.get('observe_only', False))
            self.stop_button.set_sensitive(False)

        # Update memory
        mem_mb = status['memory_mb']
        if mem_mb == 0:
            self.memory_label.set_markup("<span color='#999999'>0 MB</span>")
        elif mem_mb < 100:
            self.memory_label.set_markup(f"<span color='{STATUS_OK}'>[OK] {mem_mb:.1f} MB</span>")
        elif mem_mb < 500:
            self.memory_label.set_markup(f"<span color='{STATUS_WARN}'>[WARN] {mem_mb:.1f} MB</span>")
        else:
            self.memory_label.set_markup(f"<span color='{STATUS_HIGH}'>[HIGH] {mem_mb:.1f} MB</span>")

    def show_unavailable(self):
        self.status_label.set_text("Service status unavailable")
        self.memory_label.set_text("--")
        self.start_button.set_sensitive(False)
        self.stop_button.set_sensitive(False)

    def on_start_clicked(self, button):
        """Handle start button click"""
        if self.config.get('observe_only'):
            return
        self.parent_window.submit_service("service_action", self.service_name,
                                          operation="start")

    def on_stop_clicked(self, button):
        """Handle stop button click"""
        if self.config.get('observe_only'):
            return
        self.parent_window.submit_service("service_action", self.service_name,
                                          operation="stop")

    def on_logs_clicked(self, button):
        """Handle logs button click"""
        self.parent_window.show_logs(self.service_name)


class MCPInstanceRow(Gtk.ListBoxRow):
    """A row for an individual MCP instance with detailed information"""

    def __init__(self, instance: dict, parent_window):
        super().__init__()
        self.instance = instance
        self.parent_window = parent_window

        main_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        main_box.set_margin_start(24)  # Indent for child
        main_box.set_margin_end(12)
        main_box.set_margin_top(6)
        main_box.set_margin_bottom(6)

        # Left side: Instance details
        info_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
        info_vbox.set_hexpand(True)

        # Process arguments and paths can contain access tokens; only safe identity is shown.
        owner = instance.get('owner_label') if isinstance(instance.get('owner_label'), str) else 'Client'
        owner_pid = instance.get('owner_pid')
        owner_text = f"{owner} PID {owner_pid}" if type(owner_pid) is int else owner
        process_label = Gtk.Label(label=f"{instance.get('mcp_name', 'MCP')} · "
                                        f"PID {instance['pid']} · {owner_text}")
        process_label.set_xalign(0)
        info_vbox.append(process_label)

        # Row 3: PID, Running time, Activity
        status_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)

        # PID
        pid_label = Gtk.Label()
        pid_label.set_markup(f"<small><tt>PID {instance['pid']}</tt></small>")
        status_box.append(pid_label)

        # Running time
        etime = instance.get('etime', '?')
        time_label = Gtk.Label()
        time_label.set_markup(f"<small>⏱ {escape(str(etime))}</small>")
        status_box.append(time_label)

        # Activity indicator (CPU usage)
        cpu = instance.get('cpu', 0.0)
        activity_label = Gtk.Label()
        if cpu > 0.5:
            activity_label.set_markup(f"<small><span color='{STATUS_RUN}'>● [RUN] Active</span></small>")
        elif cpu > 0.0:
            activity_label.set_markup(f"<small><span color='{STATUS_OK}'>◐ [OK] Recently used</span></small>")
        else:
            activity_label.set_markup("<small><span color='#999999'>○ [STOP] Idle</span></small>")
        status_box.append(activity_label)

        info_vbox.append(status_box)
        main_box.append(info_vbox)

        # Right side: Memory and Kill button
        right_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)

        # Memory
        mem_label = Gtk.Label()
        mem_mb = instance['memory_mb']
        if mem_mb < 50:
            mem_label.set_markup(f"<span color='{STATUS_OK}'>[OK] {mem_mb:.1f} MB</span>")
        else:
            mem_label.set_markup(f"<span color='{STATUS_WARN}'>[WARN] {mem_mb:.1f} MB</span>")
        mem_label.set_width_chars(10)
        right_box.append(mem_label)

        # Kill button
        kill_btn = Gtk.Button(label="Stop process")
        kill_btn.add_css_class('destructive-action')
        kill_btn.set_tooltip_text("This process may relaunch; use Block and stop above to close new launches")
        kill_btn.connect('clicked', self.on_kill_clicked)
        right_box.append(kill_btn)
        self.kill_button = kill_btn

        main_box.append(right_box)
        self.set_child(main_box)

    def on_kill_clicked(self, button):
        """Stop only the still-identical same-user process via pidfd."""
        if terminate_mcp_instance(self.instance):
            self.kill_button.set_sensitive(False)
            self.kill_button.set_label("Stop sent")
            GLib.timeout_add(1000, self.parent_window.refresh_services_once)
        else:
            self.kill_button.set_label("Changed; refresh")
            GLib.timeout_add(500, self.parent_window.refresh_services_once)


class MCPExpanderRow(Gtk.ListBoxRow):
    """An expandable row for an MCP type showing all its instances"""

    def __init__(self, mcp_name: str, instances: list, parent_window):
        super().__init__()
        self.set_activatable(False)  # Don't capture clicks - let expander handle them
        self.mcp_name = mcp_name
        self.instances = instances
        self.parent_window = parent_window

        # Main vertical box
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)

        # Create expander
        expander = Gtk.Expander()
        expander.set_expanded(False)  # Collapsed by default

        # Expander label (header with summary)
        header_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)

        # MCP info
        info_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        info_box.set_hexpand(True)

        # Name with count
        count = len(instances)
        instances_text = f" ({count} instances)" if count > 1 else ""
        name_label = Gtk.Label()
        name_label.set_markup(f"<b>{escape(mcp_name)}</b>{escape(instances_text)}")
        name_label.set_xalign(0)
        info_box.append(name_label)

        # Description
        pattern = MCP_PATTERNS.get(mcp_name, {})
        desc = pattern.get('description', 'Unknown MCP')
        desc_label = Gtk.Label(label=desc)
        desc_label.set_xalign(0)
        desc_label.add_css_class('dim-label')
        info_box.append(desc_label)

        header_box.append(info_box)

        # Total memory
        total_mem = sum(inst['memory_mb'] for inst in instances)
        mem_label = Gtk.Label()
        if total_mem < 100:
            mem_label.set_markup(f"<span color='{STATUS_OK}'>[OK] {total_mem:.1f} MB</span>")
        elif total_mem < 500:
            mem_label.set_markup(f"<span color='{STATUS_WARN}'>[WARN] {total_mem:.1f} MB</span>")
        else:
            mem_label.set_markup(f"<span color='{STATUS_HIGH}'>[HIGH] {total_mem:.1f} MB</span>")
        mem_label.set_width_chars(12)
        header_box.append(mem_label)

        # Each instance is revalidated through a pidfd before stop.
        kill_all_btn = Gtk.Button(label="Stop all")
        kill_all_btn.add_css_class('destructive-action')
        kill_all_btn.set_tooltip_text(
            f"Stop {count} verified instance(s) of {mcp_name}; client relaunch is still possible. "
            "Use Block and stop above to close new launches")
        kill_all_btn.connect('clicked', self.on_kill_all_clicked)
        header_box.append(kill_all_btn)
        self.kill_all_button = kill_all_btn

        expander.set_label_widget(header_box)

        # Content (instance list)
        instance_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        instance_box.set_margin_top(8)

        for instance in instances:
            inst_row = MCPInstanceRow(instance, parent_window)
            instance_box.append(inst_row)

        expander.set_child(instance_box)

        vbox.append(expander)
        vbox.set_margin_start(12)
        vbox.set_margin_end(12)
        vbox.set_margin_top(8)
        vbox.set_margin_bottom(8)

        self.set_child(vbox)

    def on_kill_all_clicked(self, button):
        """Stop still-identical, same-user instances only."""
        stopped_count = 0
        for instance in self.instances:
            if terminate_mcp_instance(instance):
                stopped_count += 1

        # Update button to show action completed
        self.kill_all_button.set_sensitive(False)
        self.kill_all_button.set_label(f"Stop sent to {stopped_count}")

        # Refresh the services list after a short delay
        GLib.timeout_add(1000, self.parent_window.refresh_services_once)


class McpPolicyRow(Gtk.Frame):
    """Persistent local-client launch policy, including zero-instance providers."""

    MODES = ("automatic", "manual", "disabled")

    def __init__(self, provider: str, parent_window, *, startup_only: bool = False):
        super().__init__()
        self.provider = provider
        self.parent_window = parent_window
        self.startup_only = startup_only
        self._saved_mode = None
        self._saved_cap = None
        self._updating = False
        self._dirty = False
        self.add_css_class("card")
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        for setter in (box.set_margin_top, box.set_margin_bottom,
                       box.set_margin_start, box.set_margin_end):
            setter(12)
        title = Gtk.Label(label={"context7": "Context7", "memory": "Memory"}[provider])
        title.set_xalign(0)
        title.add_css_class("heading")
        box.append(title)
        self.status_label = Gtk.Label(label="Checking local launch policy…")
        self.status_label.set_xalign(0)
        self.status_label.set_wrap(True)
        self.status_label.set_max_width_chars(38)
        box.append(self.status_label)
        if provider == "memory":
            risk_label = Gtk.Label(label="Shared memory graph: keep the client limit at 1.")
            risk_label.set_xalign(0)
            risk_label.set_wrap(True)
            risk_label.set_max_width_chars(38)
            risk_label.add_css_class("dim-label")
            box.append(risk_label)
        controls = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        choices = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        choices.append(Gtk.Label(label="New launches"))
        self.mode_dropdown = Gtk.DropDown.new_from_strings(
            ["Automatic", "Manual", "Blocked"])
        self.mode_dropdown.add_css_class("work-type-dropdown")
        self.mode_dropdown.connect("notify::selected", self._on_draft)
        choices.append(self.mode_dropdown)
        choices.append(Gtk.Label(label="Max clients"))
        self.cap_dropdown = Gtk.DropDown.new_from_strings(
            [str(value) for value in range(1, 17)])
        self.cap_dropdown.add_css_class("work-type-dropdown")
        self.cap_dropdown.set_selected(2)
        self.cap_dropdown.connect("notify::selected", self._on_draft)
        choices.append(self.cap_dropdown)
        controls.append(choices)
        self.apply_button = Gtk.Button(label="Apply policy")
        self.apply_button.connect("clicked", self._on_apply)
        controls.append(self.apply_button)
        box.append(controls)
        actions = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        self.allow_button = Gtk.Button(label="Allow 15 min")
        self.allow_button.set_tooltip_text("Allow new local client launches for 15 minutes")
        self.allow_button.connect("clicked", lambda _: parent_window.submit_mcp(
            "allow", self.provider))
        actions.append(self.allow_button)
        self.block_button = Gtk.Button(label="Block and stop")
        self.block_button.set_tooltip_text("Block new local launches and stop observed current clients")
        self.block_button.add_css_class("destructive-action")
        self.block_button.connect("clicked", lambda _: parent_window.submit_mcp(
            "block_stop", self.provider, cap=self.cap_dropdown.get_selected() + 1))
        actions.append(self.block_button)
        actions.set_visible(not startup_only)
        box.append(actions)
        self.set_child(box)
        self.update_policy(None, [], busy=True)

    def _on_draft(self, *_args):
        if self._updating:
            return
        index = self.mode_dropdown.get_selected()
        if index < len(self.MODES):
            self._dirty = (self.MODES[index] != self._saved_mode or
                           self.cap_dropdown.get_selected() + 1 != self._saved_cap)
        self.apply_button.set_sensitive(self._dirty and
                                        not self.parent_window._mcp_action_busy and
                                        self._saved_mode is not None)

    def _on_apply(self, _button):
        index = self.mode_dropdown.get_selected()
        if self._dirty and index < len(self.MODES):
            self.parent_window.submit_mcp("set", self.provider,
                                          mode=self.MODES[index],
                                          cap=self.cap_dropdown.get_selected() + 1)

    def update_policy(self, policy, instances, *, busy: bool):
        if not isinstance(policy, dict):
            self.status_label.set_text("Local launch policy unavailable · Retry services")
            self.mode_dropdown.set_sensitive(False)
            self.cap_dropdown.set_sensitive(False)
            self.apply_button.set_sensitive(False)
            self.allow_button.set_sensitive(False)
            self.block_button.set_sensitive(False)
            return
        mode, cap = policy.get("mode"), policy.get("cap")
        if mode not in self.MODES or type(cap) is not int:
            self.status_label.set_text("Local launch policy response invalid · Retry services")
            for widget in (self.mode_dropdown, self.cap_dropdown, self.apply_button,
                           self.allow_button, self.block_button):
                widget.set_sensitive(False)
            return
        self._saved_mode, self._saved_cap = mode, cap
        draft_index = self.mode_dropdown.get_selected()
        if (self._dirty and draft_index < len(self.MODES) and
                self.MODES[draft_index] == mode and
                self.cap_dropdown.get_selected() + 1 == cap):
            self._dirty = False
        if not self._dirty:
            self._updating = True
            try:
                self.mode_dropdown.set_selected(self.MODES.index(mode))
                self.cap_dropdown.set_selected(cap - 1)
            finally:
                self._updating = False
        observed = len(instances)
        mode_label = {"automatic": "Automatic", "manual": "Manual", "disabled": "Blocked"}[mode]
        detail = (f"{mode_label} · "
                  f"{observed} observed local server{'s' if observed != 1 else ''} · "
                  f"concurrency limit {cap}")
        unmanaged = policy.get("unmanaged_pids")
        if isinstance(unmanaged, list) and unmanaged:
            detail += f" · {len(unmanaged)} existing outside guarded launcher"
        if observed >= cap:
            detail += " · Launch limit reached"
        if mode == "manual":
            remaining = policy.get("grant_until", 0) - time.time()
            detail += (f" · New launches allowed for {max(1, int(remaining // 60) + 1)} min"
                       if remaining > 0 else " · New launches closed until Allow now")
        elif mode == "disabled":
            detail += " · New launches blocked"
        self.status_label.set_text(detail)
        self.mode_dropdown.set_sensitive(not busy)
        self.cap_dropdown.set_sensitive(not busy)
        self.apply_button.set_sensitive(not busy and self._dirty)
        self.allow_button.set_sensitive(not busy and mode == "manual" and not self._dirty)
        self.block_button.set_sensitive(not busy and (mode != "disabled" or observed > 0))


class LogsView(Gtk.Box):
    """Logs viewer with live tail"""

    def __init__(self):
        super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)

        # Header with service selector
        header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        header.set_margin_start(12)
        header.set_margin_end(12)
        header.set_margin_top(6)
        header.set_margin_bottom(6)

        label = Gtk.Label(label="Service:")
        header.append(label)

        self.service_combo = Gtk.DropDown()
        service_names = Gtk.StringList()
        for name in SERVICES.keys():
            service_names.append(name)
        self.service_combo.set_model(service_names)
        self.service_combo.connect('notify::selected', self.on_service_changed)
        header.append(self.service_combo)

        retry_button = Gtk.Button(label="Retry logs")
        retry_button.connect('clicked', lambda _: self._request_logs())
        header.append(retry_button)

        self.follow_switch = Gtk.Switch()
        self.follow_switch.set_active(True)
        self.follow_switch.connect('notify::active', self.on_follow_changed)
        follow_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        follow_box.append(Gtk.Label(label="Follow"))
        follow_box.append(self.follow_switch)
        header.append(follow_box)

        self.append(header)

        # Scrolled window for logs
        scrolled = Gtk.ScrolledWindow()
        scrolled.set_vexpand(True)

        self.text_view = Gtk.TextView()
        self.text_view.set_editable(False)
        self.text_view.set_monospace(True)
        self.text_view.set_margin_start(12)
        self.text_view.set_margin_end(12)
        self.text_view.set_margin_top(6)
        self.text_view.set_margin_bottom(6)

        scrolled.set_child(self.text_view)
        self.append(scrolled)

        self.current_service = None
        self.follow_enabled = True
        self.update_timeout_id = None
        self._log_request_in_flight = False
        self._log_generation = 0

        # Start with first service
        if len(SERVICES) > 0:
            self.load_logs(list(SERVICES.keys())[0])

    def on_service_changed(self, combo, param):
        """Handle service selection change"""
        selected = combo.get_selected()
        service_name = list(SERVICES.keys())[selected]
        self.load_logs(service_name)

    def on_follow_changed(self, switch, param):
        """Handle follow toggle"""
        self.follow_enabled = switch.get_active()
        if self.follow_enabled and self.current_service:
            self.start_following()
        else:
            self.stop_following()

    def load_logs(self, service_name: str):
        """Load logs for a service"""
        self.current_service = service_name
        self.stop_following()
        self._log_generation += 1
        self.text_view.get_buffer().set_text("Loading recent logs…")
        self._request_logs()

        if self.follow_enabled:
            self.start_following()

    def start_following(self):
        """Start auto-updating logs"""
        if self.update_timeout_id is None:
            self.update_timeout_id = GLib.timeout_add(2000, self.update_logs)

    def stop_following(self):
        """Stop auto-updating logs"""
        if self.update_timeout_id is not None:
            GLib.source_remove(self.update_timeout_id)
            self.update_timeout_id = None

    def update_logs(self):
        """Update logs (called periodically)"""
        if not self.follow_enabled or not self.current_service:
            return False
        self._request_logs()
        return True

    def _request_logs(self):
        if self._log_request_in_flight or not self.current_service:
            return
        self._log_request_in_flight = True
        generation = self._log_generation
        service_name = self.current_service

        def worker():
            try:
                service = SERVICES[service_name]['service']
                ret, out, err = run_cmd(['journalctl', '-u', service, '-n', '50', '--no-pager'])
            except Exception as exc:
                ret, out, err = 1, '', str(exc)
            GLib.idle_add(self._apply_logs, generation, service_name, ret, out, err)

        threading.Thread(target=worker, name='monkey-logs', daemon=True).start()

    def _apply_logs(self, generation, service_name, ret, out, err):
        self._log_request_in_flight = False
        if generation != self._log_generation or service_name != self.current_service:
            self._request_logs()
            return False
        buffer = self.text_view.get_buffer()
        buffer.set_text(out if ret == 0 else f"Error loading logs:\n{err}")

        # Auto-scroll to bottom
        end_iter = buffer.get_end_iter()
        self.text_view.scroll_to_iter(end_iter, 0.0, False, 0.0, 0.0)

        return False


class DevMonWindow(Adw.ApplicationWindow):
    """Main application window"""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._thermal_refresh_in_flight = False

        self.set_title("Monkey Monitor")
        self.set_default_size(1080, 720)
        self.set_resizable(True)  # Allow window resizing

        # Set window class for dock icon
        self.set_startup_id("monkey-monitor")

        # Set application icon for dock/taskbar
        icon_theme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default())
        icon_theme.add_search_path("/usr/local/share/icons/hicolor")

        # Try to set icon from theme
        if icon_theme.has_icon("monkey-monitor"):
            self.set_icon_name("monkey-monitor")
            print("✅ App icon set: monkey-monitor")
        else:
            print("⚠️  Icon 'monkey-monitor' not found in theme")

        # Header bar with theme switcher (no icons)
        header = Adw.HeaderBar()

        # Theme toggle button (right side)
        self.dark_mode = True  # Start in dark mode
        theme_button = Gtk.Button()
        theme_button.set_icon_name("weather-clear-night-symbolic")  # Moon icon for dark mode
        theme_button.set_tooltip_text("Toggle Light/Dark Mode")
        theme_button.connect("clicked", self.on_theme_toggle)
        header.pack_end(theme_button)
        self.theme_button = theme_button

        guide_button = Gtk.Button(label="User Guide")
        guide_button.set_tooltip_text("Open Monkey Monitor & QIG Mesh User Guide")
        guide_button.connect("clicked", lambda _: self.stack.set_visible_child_name("guides"))
        header.pack_end(guide_button)
        self.guide_button = guide_button

        # Main content
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)

        # Toolbar with monkey logo on the right
        toolbar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
        toolbar.add_css_class('toolbar')
        toolbar.set_margin_top(8)
        toolbar.set_margin_bottom(8)

        app_title = Gtk.Label(label="MONKEY MONITOR")
        app_title.set_hexpand(True)
        app_title.set_xalign(0)
        app_title.add_css_class("title-3")
        app_title.set_margin_start(18)
        app_title.set_markup(_heading_markup("MONKEY MONITOR", dark=True))
        self.app_title = app_title
        toolbar.append(app_title)

        # Monkey logo on the right side (128px for sharp display)
        monkey_icon_path = "/usr/local/share/monkey-monitor/monkey-monitor-tran-128.png"
        if os.path.exists(monkey_icon_path):
            monkey_icon = Gtk.Image()
            monkey_icon.set_from_file(monkey_icon_path)
            monkey_icon.set_pixel_size(64)  # Display at 64px but use 128px source for clarity
            monkey_icon.set_margin_end(12)
            monkey_icon.add_css_class('monkey-logo')
            toolbar.append(monkey_icon)
            print(f"🐵 Monkey logo loaded in toolbar: {monkey_icon_path}")
        else:
            print(f"⚠️  Monkey logo not found at: {monkey_icon_path}")

        vbox.append(toolbar)

        # Stack for different views
        self.stack = Gtk.Stack()
        self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
        self.stack.set_hexpand(True)
        self.stack.set_vexpand(True)

        # One status controller feeds the PC sections without blocking GTK.
        self.pc_page = PcControlsPage()
        for slug, title, page in self.pc_page.pages:
            self.stack.add_titled(page, slug, title)

        # Services page
        self._service_connection_ready = False
        self._service_requesting = False
        self._service_request_started = 0.0
        self._service_control_state = "idle"
        self._mcp_action_busy = False
        self._mcp_receipt_pending = False
        services_page = self.create_services_page()
        self.stack.add_titled(services_page, "services", "Services")
        self.create_startup_controls()
        self.pc_page.set_connection_callback(self._on_pc_connection)
        self.pc_page.set_status_callback(self._on_pc_service_status)
        self.pc_page.on_action_result = self._on_pc_action_result

        # Logs page
        self.logs_view = LogsView()
        self.stack.add_titled(self.logs_view, "logs", "Logs")

        # System page (Thermal Monitoring)
        system_page = self.create_system_page()
        self.stack.add_titled(system_page, "sensors", "Sensors")

        # User Guide page
        guides_page = self.create_user_guide_page()
        self.stack.add_titled(guides_page, "guides", "User Guide")
        self.stack.set_visible_child_name("overview")

        navigation = Gtk.StackSidebar()
        navigation.set_stack(self.stack)
        navigation.set_size_request(180, -1)
        navigation.add_css_class("navigation-sidebar")
        content = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
        content.append(navigation)
        content.append(self.stack)
        vbox.append(content)

        # Wrap in Adw.ToolbarView
        toolbar_view = Adw.ToolbarView()
        toolbar_view.add_top_bar(header)
        toolbar_view.set_content(vbox)

        self.set_content(toolbar_view)

        # Start auto-refresh; all subprocess collection happens off the GTK thread.
        self._service_refresh_in_flight = False
        self.refresh_services()
        GLib.timeout_add(3000, self.refresh_services)
        GLib.timeout_add(2000, self.refresh_thermal)  # Update thermal info every 2 seconds

    def create_services_page(self):
        """Create the services list page"""
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_start(12)
        vbox.set_margin_end(12)
        vbox.set_margin_top(12)
        vbox.set_margin_bottom(12)

        # Status bar
        status_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)

        self.total_memory_label = Gtk.Label()
        self.total_memory_label.set_text("Checking service status…")
        status_box.append(self.total_memory_label)

        retry_button = Gtk.Button(label="Retry services")
        retry_button.connect('clicked', self._retry_services)
        status_box.append(retry_button)

        vbox.append(status_box)

        self.service_policy_label = Gtk.Label(label="Connecting to PC controls…")
        self.service_policy_label.set_xalign(0)
        self.service_policy_label.set_wrap(True)
        vbox.append(self.service_policy_label)
        self.service_action_label = Gtk.Label(label="No service action requested")
        self.service_action_label.set_xalign(0)
        self.service_action_label.set_wrap(True)
        self.service_action_label.set_visible(False)
        vbox.append(self.service_action_label)

        mcp_intro = Gtk.Label(label="Local Memory and Context7 clients: Manual needs Allow now; "
                              "Blocked closes new launches. Existing clients continue unless stopped.")
        mcp_intro.set_xalign(0)
        mcp_intro.set_wrap(True)
        vbox.append(mcp_intro)
        self.mcp_policy_message = Gtk.Label(label="Checking local MCP policy…")
        self.mcp_policy_message.set_xalign(0)
        self.mcp_policy_message.set_wrap(True)
        vbox.append(self.mcp_policy_message)
        self.mcp_action_label = Gtk.Label(label="No local MCP policy action requested")
        self.mcp_action_label.set_xalign(0)
        self.mcp_action_label.set_wrap(True)
        self.mcp_action_label.set_visible(False)
        vbox.append(self.mcp_action_label)
        self.mcp_policy_rows = {}
        policy_cards = Gtk.FlowBox()
        policy_cards.set_selection_mode(Gtk.SelectionMode.NONE)
        policy_cards.set_min_children_per_line(1)
        policy_cards.set_max_children_per_line(2)
        policy_cards.set_column_spacing(12)
        policy_cards.set_row_spacing(12)
        policy_cards.set_homogeneous(True)
        for provider in ("memory", "context7"):
            row = McpPolicyRow(provider, self)
            self.mcp_policy_rows[provider] = row
            policy_cards.append(row)
        vbox.append(policy_cards)

        # Service list
        scrolled = Gtk.ScrolledWindow()
        scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scrolled.set_vexpand(True)

        self.service_list = Gtk.ListBox()
        self.service_list.set_selection_mode(Gtk.SelectionMode.NONE)
        self.service_list.add_css_class('boxed-list')

        # Add service rows
        self.service_rows = {}
        for name, config in SERVICES.items():
            row = ServiceRow(name, config, self)
            self.service_rows[name] = row
            self.service_list.append(row)

        # Add MCP rows (if support enabled)
        self.mcp_rows = {}
        self.mcp_separator = None
        self.mcp_header_row = None
        vbox.append(self.service_list)
        scrolled.set_child(vbox)

        return scrolled

    def create_startup_controls(self):
        """Expose the same typed policies where startup decisions are made."""
        recommendation = Gtk.Label(label=(
            "Recommended: keep essential display and controller services enabled. "
            "Use Manual for databases needed only on demand; choose Automatic when a "
            "boot workflow needs them. For local MCP clients, Manual allows a short "
            "launch window on request; Automatic allows regular launches. Blocked "
            "prevents database starts or new local MCP launches."))
        recommendation.set_xalign(0)
        recommendation.set_wrap(True)
        self.pc_page.add_startup_controls(recommendation)

        login_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        login_name = Gtk.Label(label="Open Monkey Monitor at login")
        login_name.set_xalign(0)
        login_name.set_hexpand(True)
        login_row.append(login_name)
        self.login_switch = Gtk.Switch()
        self.login_switch.set_valign(Gtk.Align.CENTER)
        self.login_switch.connect("state-set", self._on_login_state_set)
        self.login_switch.set_sensitive(False)
        login_row.append(self.login_switch)
        self.pc_page.add_startup_controls(login_row)
        self.login_status_label = Gtk.Label(label="Checking login startup…")
        self.login_status_label.set_xalign(0)
        self.login_status_label.set_wrap(True)
        self.pc_page.add_startup_controls(self.login_status_label)
        self.login_action_label = Gtk.Label(label="")
        self.login_action_label.set_xalign(0)
        self.login_action_label.set_wrap(True)
        self.login_action_label.set_visible(False)
        self.pc_page.add_startup_controls(self.login_action_label)
        self._login_generation = 0
        self._login_busy = False
        self._login_status_in_flight = False
        self._login_available = False
        self._updating_login = False
        self._refresh_login_status()

        self.startup_service_action_label = Gtk.Label(label="")
        self.startup_service_action_label.set_xalign(0)
        self.startup_service_action_label.set_wrap(True)
        self.startup_service_action_label.set_visible(False)
        self.pc_page.add_startup_controls(self.startup_service_action_label)
        self.startup_mcp_action_label = Gtk.Label(label="")
        self.startup_mcp_action_label.set_xalign(0)
        self.startup_mcp_action_label.set_wrap(True)
        self.startup_mcp_action_label.set_visible(False)
        self.pc_page.add_startup_controls(self.startup_mcp_action_label)

        database_title = Gtk.Label(label="Databases")
        database_title.add_css_class("heading")
        database_title.set_xalign(0)
        self.pc_page.add_startup_controls(database_title)
        databases = Gtk.ListBox()
        databases.set_selection_mode(Gtk.SelectionMode.NONE)
        databases.add_css_class("boxed-list")
        self.startup_service_rows = {}
        for name in ("mysql", "postgresql"):
            row = ServiceRow(name, SERVICES[name], self, startup_only=True)
            self.startup_service_rows[name] = row
            databases.append(row)
        self.pc_page.add_startup_controls(databases)

        mcp_title = Gtk.Label(label="Local MCP clients")
        mcp_title.add_css_class("heading")
        mcp_title.set_xalign(0)
        self.pc_page.add_startup_controls(mcp_title)
        self.startup_mcp_policy_rows = {}
        cards = Gtk.FlowBox()
        cards.set_selection_mode(Gtk.SelectionMode.NONE)
        cards.set_min_children_per_line(1)
        cards.set_max_children_per_line(2)
        cards.set_column_spacing(12)
        cards.set_row_spacing(12)
        cards.set_homogeneous(True)
        for provider in ("memory", "context7"):
            row = McpPolicyRow(provider, self, startup_only=True)
            self.startup_mcp_policy_rows[provider] = row
            cards.append(row)
        self.pc_page.add_startup_controls(cards)

    def _set_service_action(self, message: str):
        for label in (self.service_action_label, self.startup_service_action_label):
            label.set_text(message)
            label.set_visible(True)

    def _set_mcp_action(self, message: str):
        for label in (self.mcp_action_label, self.startup_mcp_action_label):
            label.set_text(message)
            label.set_visible(True)

    def _refresh_login_status(self):
        if self._login_status_in_flight or self._login_busy:
            return
        self._login_status_in_flight = True
        generation = self._login_generation

        def worker():
            try:
                result, error = monitor_autostart_status(), None
            except Exception as exc:
                result, error = None, str(exc)
            GLib.idle_add(self._apply_login_status, generation, result, error)

        threading.Thread(target=worker, name="monkey-login-startup", daemon=True).start()

    def _apply_login_status(self, generation, result, error):
        self._login_status_in_flight = False
        if generation != self._login_generation:
            self._refresh_login_status()
            return False
        self._login_available = (not error and isinstance(result, dict) and
                                 result.get("available") is True and
                                 isinstance(result.get("enabled"), bool))
        if self._login_available:
            enabled = result["enabled"]
            self._updating_login = True
            try:
                self.login_switch.set_active(enabled)
                self.login_switch.set_state(enabled)
            finally:
                self._updating_login = False
            self.login_status_label.set_text(
                "Window opens at login; PC policy runs independently" if enabled else
                "Window stays closed at login; PC policy still runs independently")
        else:
            detail = error or (result.get("message") if isinstance(result, dict) else
                               "Login startup readback unavailable")
            self.login_status_label.set_text(f"Login startup unavailable: {str(detail)[:180]}")
        self.login_switch.set_sensitive(self._login_available and not self._login_busy)
        return False

    def _on_login_state_set(self, _switch, enabled):
        if self._updating_login or not self._login_available or self._login_busy:
            return True
        self._login_busy = True
        self._login_generation += 1
        generation = self._login_generation
        self.login_switch.set_sensitive(False)
        self.login_action_label.set_text("Applying login startup choice…")
        self.login_action_label.set_visible(True)

        def worker():
            try:
                result, error = set_monitor_autostart(bool(enabled)), None
            except Exception as exc:
                result, error = None, str(exc)
            GLib.idle_add(self._finish_login_change, generation, bool(enabled), result, error)

        threading.Thread(target=worker, name="monkey-login-startup-change", daemon=True).start()
        return True

    def _finish_login_change(self, generation, enabled, result, error):
        if generation != self._login_generation:
            return False
        self._login_busy = False
        if error:
            self.login_action_label.set_text(
                f"Login startup change refused: {error[:180]}. Current choice is kept.")
        elif (not isinstance(result, dict) or result.get("available") is not True or
              result.get("enabled") is not enabled):
            self.login_action_label.set_text(
                "Login startup gave no matching readback; checking current state")
        else:
            self.login_action_label.set_text(
                "Monkey Monitor will open at login" if enabled else
                "Monkey Monitor will stay closed at login")
        self._refresh_login_status()
        return False

    def _retry_services(self, _button):
        self.pc_page.refresh_status()
        self.refresh_services()

    def service_controls_ready(self):
        return (self._service_connection_ready and not self._service_requesting and
                self._service_control_state != "running" and not self.pc_page._busy)

    def _on_pc_connection(self, connected: bool):
        self._service_connection_ready = connected
        if not connected:
            if self._service_requesting:
                self._service_requesting = False
                self._set_service_action(
                    "Controller disconnected before the service action finished. "
                    "Outcome unknown; check current readback after reconnect.")
            self.service_policy_label.set_text(
                "PC controls unavailable. Retry services; policies and service actions are disabled.")
            for name in ("mysql", "postgresql"):
                self.service_rows[name].set_control_unavailable()
                self.startup_service_rows[name].set_control_unavailable()

    def _on_pc_service_status(self, data: dict):
        rows = data.get("system_services")
        if not isinstance(rows, list):
            self.service_policy_label.set_text(
                "Service startup policy readback unavailable. Retry services.")
            for name in ("mysql", "postgresql"):
                self.service_rows[name].set_control_unavailable()
                self.startup_service_rows[name].set_control_unavailable()
            return
        by_name = {row.get("name"): row for row in rows if isinstance(row, dict)}
        control = data.get("service_control") if isinstance(data.get("service_control"), dict) else {}
        self._service_control_state = str(control.get("state") or "idle")
        if self._service_control_state in ("completed", "failed"):
            self._service_requesting = False
        elif (self._service_requesting and self._service_control_state == "idle" and
              time.monotonic() - self._service_request_started > 30):
            self._service_requesting = False
            self._set_service_action(
                "Service completion readback timed out. Current state is shown below; retry services.")
        self.service_policy_label.set_text(
            "Automatic enables boot startup; Manual removes boot enablement but dependencies "
            "may still start it; Blocked stops and masks the service. Stop changes the "
            "current session only. Docker stacks are under Containers.")
        if self._service_control_state != "idle":
            self._set_service_action(
                f"Service action {self._service_control_state}: "
                f"{str(control.get('message') or 'Readback pending')[:240]}")
        for name in ("mysql", "postgresql"):
            row = by_name.get(name)
            if isinstance(row, dict):
                for view_row in (self.service_rows[name], self.startup_service_rows[name]):
                    view_row.update_control_status(row, ready=self.service_controls_ready())
            else:
                self.service_rows[name].set_control_unavailable()
                self.startup_service_rows[name].set_control_unavailable()

    def _on_pc_action_result(self, action: str, result, error):
        if action not in ("set_service_startup", "service_action"):
            return
        if error:
            self._service_requesting = False
            self._set_service_action(f"Service change refused: {str(error)[:240]}")
        elif isinstance(result, dict) and result.get("accepted") is True:
            self._set_service_action("Service change accepted; waiting for system readback…")
        else:
            self._service_requesting = False
            self._set_service_action("Service gave no acceptance receipt; checking status")
        for name in ("mysql", "postgresql"):
            for view_row in (self.service_rows[name], self.startup_service_rows[name]):
                if view_row.control_row:
                    view_row.update_control_status(view_row.control_row,
                                                   ready=self.service_controls_ready())

    def submit_service(self, action: str, service: str, **fields):
        if service not in ("mysql", "postgresql") or not self.service_controls_ready():
            return
        self._service_requesting = True
        self._service_request_started = time.monotonic()
        self._set_service_action(f"Requesting {service} change…")
        self.pc_page.submit(action, service=service, **fields)
        for name in ("mysql", "postgresql"):
            for view_row in (self.service_rows[name], self.startup_service_rows[name]):
                if view_row.control_row:
                    view_row.update_control_status(view_row.control_row, ready=False)

    def submit_mcp(self, action: str, provider: str, **fields):
        if (provider not in ("memory", "context7") or self._mcp_action_busy or
                not MCP_POLICY_SUPPORT):
            return
        if action == "block_stop" and not MCP_SUPPORT:
            self.mcp_policy_message.set_text(
                "Cannot stop current clients because process identity checks are unavailable")
            return
        self._mcp_action_busy = True
        self._set_mcp_action(f"Applying {provider} local launch policy…")
        for row in (*self.mcp_policy_rows.values(), *self.startup_mcp_policy_rows.values()):
            for widget in (row.mode_dropdown, row.cap_dropdown, row.apply_button,
                           row.allow_button, row.block_button):
                widget.set_sensitive(False)

        def worker():
            try:
                if action == "set":
                    result = set_mcp_policy(provider, fields["mode"], fields["cap"])
                elif action == "allow":
                    result = allow_mcp_now(provider)
                elif action == "block_stop":
                    result = set_mcp_policy(provider, "disabled", fields["cap"])
                    instances = get_mcp_instances().get(f"{provider}-mcp", [])
                    stopped = sum(bool(terminate_mcp_instance(instance))
                                  for instance in instances)
                    result = {**result, "observed": len(instances), "stop_sent": stopped}
                else:
                    raise ValueError("Unknown MCP action")
                error = None
            except Exception as exc:
                result, error = None, str(exc)
            GLib.idle_add(self._apply_mcp_action, provider, action, result, error)

        threading.Thread(target=worker, name=f"monkey-mcp-{provider}", daemon=True).start()

    def _apply_mcp_action(self, provider, action, result, error):
        self._mcp_action_busy = False
        if error:
            self._set_mcp_action(
                f"{provider} policy change refused: {error[:160]}. Your choice is preserved.")
        elif action == "block_stop":
            sent, observed = result["stop_sent"], result["observed"]
            self._set_mcp_action(
                f"{provider} new launches blocked; stop sent to {sent} of {observed} "
                "observed processes. Checking live readback…")
        else:
            self._set_mcp_action(
                f"{provider} policy saved; checking live readback…")
        self._mcp_receipt_pending = error is None
        self.refresh_services()
        return False

    def _rebuild_mcp_section(self, mcp_instances: dict):
        """Rebuild the MCP section with current instances"""
        # Remove old MCP rows (check parent first to avoid GTK warnings)
        for row in list(self.mcp_rows.values()):
            if row.get_parent():
                self.service_list.remove(row)
        self.mcp_rows.clear()

        # Remove old separator and header if they exist
        if self.mcp_separator and self.mcp_separator.get_parent():
            self.service_list.remove(self.mcp_separator)
            self.mcp_separator = None
        if self.mcp_header_row and self.mcp_header_row.get_parent():
            self.service_list.remove(self.mcp_header_row)
            self.mcp_header_row = None

        # Only add MCP section if there are instances
        if mcp_instances:
            # Add separator
            self.mcp_separator = Gtk.ListBoxRow()
            self.mcp_separator.set_selectable(False)
            separator = Gtk.Separator()
            separator.set_margin_top(12)
            separator.set_margin_bottom(12)
            self.mcp_separator.set_child(separator)
            self.service_list.append(self.mcp_separator)

            # Add header
            self.mcp_header_row = Gtk.ListBoxRow()
            self.mcp_header_row.set_selectable(False)
            header_label = Gtk.Label()
            header_label.set_markup("<b>MCP SERVERS</b>")
            header_label.set_margin_start(12)
            header_label.set_margin_top(8)
            header_label.set_margin_bottom(4)
            header_label.set_xalign(0)
            self.mcp_header_row.set_child(header_label)
            self.service_list.append(self.mcp_header_row)

            # Add expandable MCP rows
            for name, instances in mcp_instances.items():
                row = MCPExpanderRow(name, instances, self)
                self.mcp_rows[name] = row
                self.service_list.append(row)

    def create_system_page(self):
        """Create the system/thermal monitoring page"""
        # Create scrolled window for System page content
        scrolled = Gtk.ScrolledWindow()
        scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scrolled.set_vexpand(True)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=16)
        vbox.set_margin_start(16)
        vbox.set_margin_end(16)
        vbox.set_margin_top(16)
        vbox.set_margin_bottom(16)

        # Temperature section
        temp_frame = Gtk.Frame()
        temp_frame.add_css_class('card')
        temp_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        temp_box.set_margin_start(16)
        temp_box.set_margin_end(16)
        temp_box.set_margin_top(16)
        temp_box.set_margin_bottom(16)

        # Header
        temp_header = Gtk.Label()
        temp_header.set_markup("<b>🌡️  Temperature Monitoring</b>")
        temp_header.set_xalign(0)
        temp_header.add_css_class('section-header')
        temp_box.append(temp_header)

        # CPU temp
        self.cpu_temp_label = Gtk.Label()
        self.cpu_temp_label.set_markup("<span size='large'>CPU: <b>--°C</b></span>")
        self.cpu_temp_label.set_xalign(0)
        self.cpu_temp_label.add_css_class('system-label')
        temp_box.append(self.cpu_temp_label)

        # GPU temp
        self.gpu_temp_label = Gtk.Label()
        self.gpu_temp_label.set_markup("<span size='large'>GPU: <b>--°C</b></span>")
        self.gpu_temp_label.set_xalign(0)
        self.gpu_temp_label.add_css_class('system-label')
        temp_box.append(self.gpu_temp_label)

        # NVMe temp
        self.nvme_temp_label = Gtk.Label()
        self.nvme_temp_label.set_markup("<span size='large'>NVMe SSD: <b>--°C</b></span>")
        self.nvme_temp_label.set_xalign(0)
        self.nvme_temp_label.add_css_class('system-label')
        temp_box.append(self.nvme_temp_label)

        temp_frame.set_child(temp_box)
        vbox.append(temp_frame)

        # Fan section
        fan_frame = Gtk.Frame()
        fan_frame.add_css_class('card')
        fan_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        fan_box.set_margin_start(16)
        fan_box.set_margin_end(16)
        fan_box.set_margin_top(16)
        fan_box.set_margin_bottom(16)

        # Header
        fan_header = Gtk.Label()
        fan_header.set_markup("<b>🌀  Fan Speed</b>")
        fan_header.set_xalign(0)
        fan_header.add_css_class('section-header')
        fan_box.append(fan_header)

        # Fan 1
        self.fan1_label = Gtk.Label()
        self.fan1_label.set_markup("<span size='large'>Fan 1: <b>-- RPM</b></span>")
        self.fan1_label.set_xalign(0)
        self.fan1_label.add_css_class('system-label')
        fan_box.append(self.fan1_label)

        # Fan 2
        self.fan2_label = Gtk.Label()
        self.fan2_label.set_markup("<span size='large'>Fan 2: <b>-- RPM</b></span>")
        self.fan2_label.set_xalign(0)
        self.fan2_label.add_css_class('system-label')
        fan_box.append(self.fan2_label)

        fan_frame.set_child(fan_box)
        vbox.append(fan_frame)

        # Thermal mode section
        mode_frame = Gtk.Frame()
        mode_frame.add_css_class('card')
        mode_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        mode_box.set_margin_start(16)
        mode_box.set_margin_end(16)
        mode_box.set_margin_top(16)
        mode_box.set_margin_bottom(16)

        # Header
        mode_header = Gtk.Label()
        mode_header.set_markup("<b>⚡  Dell firmware thermal mode</b>")
        mode_header.set_xalign(0)
        mode_header.add_css_class('section-header')
        mode_box.append(mode_header)

        # Current mode display
        self.thermal_mode_label = Gtk.Label()
        self.thermal_mode_label.set_markup("<span size='large'>Firmware setting: <b>--</b></span>")
        self.thermal_mode_label.set_xalign(0)
        self.thermal_mode_label.add_css_class('system-label')
        mode_box.append(self.thermal_mode_label)

        mode_explanation = Gtk.Label(label="This firmware setting is separate from Quner's CPU governor "
                                           "and power limits. Quner manages work modes and the thermal guard.")
        mode_explanation.set_xalign(0)
        mode_explanation.set_wrap(True)
        mode_box.append(mode_explanation)
        pc_button = Gtk.Button(label="Open Work modes")
        pc_button.connect('clicked', lambda _: self.stack.set_visible_child_name("work-modes"))
        mode_box.append(pc_button)

        mode_frame.set_child(mode_box)
        vbox.append(mode_frame)

        # Temperature Thresholds section
        threshold_frame = Gtk.Frame()
        threshold_frame.add_css_class('card')
        threshold_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        threshold_box.set_margin_start(16)
        threshold_box.set_margin_end(16)
        threshold_box.set_margin_top(16)
        threshold_box.set_margin_bottom(16)

        # Header
        threshold_header = Gtk.Label()
        threshold_header.set_markup("<b>🌡️  Temperature Thresholds</b>")
        threshold_header.set_xalign(0)
        threshold_header.add_css_class('section-header')
        threshold_box.append(threshold_header)

        # CPU threshold
        cpu_thresh_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        cpu_thresh_label = Gtk.Label(label="CPU Warning Temp (°C)")
        cpu_thresh_label.set_xalign(0)
        cpu_thresh_label.set_hexpand(True)
        cpu_thresh_label.add_css_class('system-label')
        cpu_thresh_row.append(cpu_thresh_label)

        self.cpu_threshold = Gtk.SpinButton()
        self.cpu_threshold.set_range(60, 100)
        self.cpu_threshold.set_increments(1, 5)
        self.cpu_threshold.set_value(80)
        cpu_thresh_row.append(self.cpu_threshold)
        threshold_box.append(cpu_thresh_row)

        # GPU threshold
        gpu_thresh_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        gpu_thresh_label = Gtk.Label(label="GPU Warning Temp (°C)")
        gpu_thresh_label.set_xalign(0)
        gpu_thresh_label.set_hexpand(True)
        gpu_thresh_label.add_css_class('system-label')
        gpu_thresh_row.append(gpu_thresh_label)

        self.gpu_threshold = Gtk.SpinButton()
        self.gpu_threshold.set_range(60, 100)
        self.gpu_threshold.set_increments(1, 5)
        self.gpu_threshold.set_value(80)
        gpu_thresh_row.append(self.gpu_threshold)
        threshold_box.append(gpu_thresh_row)

        # NVMe threshold
        nvme_thresh_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        nvme_thresh_label = Gtk.Label(label="NVMe Warning Temp (°C)")
        nvme_thresh_label.set_xalign(0)
        nvme_thresh_label.set_hexpand(True)
        nvme_thresh_label.add_css_class('system-label')
        nvme_thresh_row.append(nvme_thresh_label)

        self.nvme_threshold = Gtk.SpinButton()
        self.nvme_threshold.set_range(40, 80)
        self.nvme_threshold.set_increments(1, 5)
        self.nvme_threshold.set_value(60)
        nvme_thresh_row.append(self.nvme_threshold)
        threshold_box.append(nvme_thresh_row)

        threshold_frame.set_child(threshold_box)
        vbox.append(threshold_frame)

        # Warning label for high temps
        self.warning_label = Gtk.Label()
        self.warning_label.set_markup("")
        self.warning_label.set_xalign(0)
        self.warning_label.add_css_class('dim-label')
        vbox.append(self.warning_label)

        retry_button = Gtk.Button(label="Retry sensors")
        retry_button.set_halign(Gtk.Align.START)
        retry_button.connect('clicked', lambda _: self.refresh_thermal())
        vbox.append(retry_button)

        # Update thermal info immediately
        self.refresh_thermal()

        # Set vbox as the scrolled window child
        scrolled.set_child(vbox)
        return scrolled

    def create_user_guide_page(self):
        """Create the built-in Monkey Monitor & QIG Mesh User Guide page."""
        scrolled = Gtk.ScrolledWindow()
        scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scrolled.set_vexpand(True)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_start(16)
        vbox.set_margin_end(16)
        vbox.set_margin_top(16)
        vbox.set_margin_bottom(16)

        header_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        title_lbl = Gtk.Label()
        title_lbl.set_markup(_heading_markup("MONKEY MONITOR & QIG MESH USER GUIDE", dark=self.dark_mode))
        title_lbl.set_xalign(0)
        title_lbl.set_hexpand(True)
        header_row.append(title_lbl)

        web_docs_btn = Gtk.Button(label="Open Web User Guides (/docs)")

        def _open_web_docs(_btn) -> None:
            server = os.environ.get("DMONKEY_SERVER", "").strip()
            if not server:
                state_file = Path(os.environ.get("DMONKEY_HOME") or (Path.home() / ".dmonkey")) / "device.json"
                if state_file.is_file():
                    try:
                        server = str(json.loads(state_file.read_text(encoding="utf-8")).get("server") or "").strip()
                    except (OSError, ValueError):
                        server = ""
            if server:
                subprocess.Popen(
                    ["xdg-open", f"{server.rstrip('/')}/docs"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )

        web_docs_btn.connect(
            "clicked",
            _open_web_docs,
        )
        header_row.append(web_docs_btn)
        vbox.append(header_row)

        sections = (
            (
                "1. Overview & Quner Hardware Power Policy",
                "Use Overview and Work modes to switch between General development and QIG compute. "
                "Monkey Monitor reads live CPU governor, RAPL package power limits (W), and GPU watt caps "
                "from Quner while keeping interactive desktop responsiveness protected (8% warn / 4% floor).",
            ),
            (
                "2. Managed Docker Stacks & Verified Idle Cleanup",
                "Toggle 'Idle cleanup' on request-driven Docker stacks so containers automatically stop after "
                "10 minutes of verified socket/query inactivity. Toggle 'Keep running' to pin active training or "
                "background workloads so idle cleanup never interrupts them.",
            ),
            (
                "3. Systemd Databases & Boot Startup Controls",
                "In Services and Startup, start or stop PostgreSQL (port 5432) and MySQL (port 3306) on demand, "
                "inspect live memory and active connection counts, and set boot policy to Automatic, Manual, or Blocked.",
            ),
            (
                "4. Local MCP Launch Guard (Memory & Context7)",
                "Prevent runaway local MCP server processes by setting concurrency limits (1–8) and launch mode: "
                "Automatic, Manual ('Allow now' grants a 10-minute launch window), or Blocked.",
            ),
            (
                "5. Connecting Remote MCP Clients & Enrolling Troop Devices",
                "Point Claude, Cursor, Hermes, or VS Code at <your-relay-url>/mcp "
                "and approve the OAuth 2.1 consent prompt. To enrol this workstation into your troop, use the Agent page or run "
                "'uvx --from desktop-monkey dmonkey remote --server <your-relay-url>' "
                "and enter the XXXX-XXXX code in the Dashboard's Link Device tab.",
            ),
            (
                "6. Bidirectional AI <-> Human Field Resonance Trainer",
                "Open the Web User Guides (/docs) to use the Blind Frequency & Field Intuition Trainer: "
                "the AI guides your probe across the 64-D manifold via continuous stereo binaural beat detuning "
                "(Delta_f -> 0 Hz at phase-lock) and standing-wave consonance without reading text or using voice.",
            ),
        )

        for sec_title, sec_body in sections:
            frame = Gtk.Frame()
            frame.add_css_class("card")
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
            box.set_margin_start(14)
            box.set_margin_end(14)
            box.set_margin_top(10)
            box.set_margin_bottom(10)

            h_lbl = Gtk.Label()
            h_lbl.set_markup(f"<b>{escape(sec_title)}</b>")
            h_lbl.set_xalign(0)
            box.append(h_lbl)

            b_lbl = Gtk.Label(label=sec_body)
            b_lbl.set_xalign(0)
            b_lbl.set_wrap(True)
            box.append(b_lbl)

            frame.set_child(box)
            vbox.append(frame)

        scrolled.set_child(vbox)
        return scrolled

    def refresh_thermal(self):
        """Collect sensors without blocking the GTK event loop."""
        if self._thermal_refresh_in_flight:
            return True
        self._thermal_refresh_in_flight = True

        def worker():
            try:
                thermal = get_thermal_info()
                mode = get_thermal_mode()
            except Exception as exc:
                GLib.idle_add(self._apply_thermal_error, str(exc))
            else:
                GLib.idle_add(self._apply_thermal, thermal, mode)

        threading.Thread(target=worker, name='monkey-thermal', daemon=True).start()
        return True

    def _apply_thermal_error(self, message: str):
        self._thermal_refresh_in_flight = False
        self.warning_label.set_text(f"Sensor readings unavailable: {message[:160]}. Retry sensors.")
        return False

    def _apply_thermal(self, thermal: dict, mode: str):
        self._thermal_refresh_in_flight = False

        # Update temperature labels with color coding + explicit tier badges
        cpu_color = self.get_temp_color(thermal['cpu_temp'])
        cpu_text = f"{thermal['cpu_temp']:.1f}°C" if thermal['cpu_temp'] else "Unavailable"
        self.cpu_temp_label.set_markup(
            f"<span size='large'>CPU: <b><span color='{cpu_color}'>{self.get_temp_tier(thermal['cpu_temp'])}{cpu_text}</span></b></span>"
        )

        gpu_color = self.get_temp_color(thermal['gpu_temp'])
        gpu_text = f"{thermal['gpu_temp']:.1f}°C" if thermal['gpu_temp'] else "Unavailable"
        self.gpu_temp_label.set_markup(
            f"<span size='large'>GPU: <b><span color='{gpu_color}'>{self.get_temp_tier(thermal['gpu_temp'])}{gpu_text}</span></b></span>"
        )

        nvme_color = self.get_temp_color(thermal['nvme_temp'], hot_threshold=50)
        nvme_text = f"{thermal['nvme_temp']:.1f}°C" if thermal['nvme_temp'] else "Unavailable"
        self.nvme_temp_label.set_markup(
            f"<span size='large'>NVMe SSD: <b><span color='{nvme_color}'>{self.get_temp_tier(thermal['nvme_temp'], hot_threshold=50)}{nvme_text}</span></b></span>"
        )

        # Update fan labels
        self.fan1_label.set_markup(
            f"<span size='large'>Fan 1: <b>{thermal['fan1_rpm']} RPM</b></span>"
        )
        self.fan2_label.set_markup(
            f"<span size='large'>Fan 2: <b>{thermal['fan2_rpm']} RPM</b></span>"
        )

        # Update mode label
        mode_display = mode.capitalize()
        mode_color = THEME_COLORS['electric_cyan']
        if mode == 'performance':
            mode_color = STATUS_HIGH
        elif mode == 'cool':
            mode_color = THEME_COLORS['electric_blue']

        self.thermal_mode_label.set_markup(
            f"<span size='large'>Firmware setting: <b><span color='{mode_color}'>{escape(mode_display)}</span></b></span>"
        )

        # Update warning if temps are high (using custom thresholds)
        warnings = []
        cpu_thresh = self.cpu_threshold.get_value()
        gpu_thresh = self.gpu_threshold.get_value()
        nvme_thresh = self.nvme_threshold.get_value()

        if thermal['cpu_temp'] > cpu_thresh:
            warnings.append(f"⚠️  CPU temperature is HIGH ({thermal['cpu_temp']:.1f}°C > {cpu_thresh:.0f}°C)!")
        if thermal['gpu_temp'] > gpu_thresh:
            warnings.append(f"⚠️  GPU temperature is HIGH ({thermal['gpu_temp']:.1f}°C > {gpu_thresh:.0f}°C)!")
        if thermal['nvme_temp'] > nvme_thresh:
            warnings.append(f"⚠️  NVMe temperature is HIGH ({thermal['nvme_temp']:.1f}°C > {nvme_thresh:.0f}°C)!")

        if warnings:
            self.warning_label.set_markup(
                f"<span color='{STATUS_HIGH}'>" + " ".join(warnings) + "</span>")
        else:
            self.warning_label.set_markup("")

        return False

    def get_temp_color(self, temp: float, hot_threshold: float = 70) -> str:
        """Colourblind-safe temperature tier colour (blue / amber / purple)."""
        if temp <= 0:
            return '#999999'
        if temp < hot_threshold:
            return STATUS_OK
        elif temp < 80:
            return STATUS_WARN
        else:
            return STATUS_HIGH

    def get_temp_tier(self, temp: float, hot_threshold: float = 70) -> str:
        """Explicit non-colour badge for the temperature tier."""
        if temp <= 0:
            return ""
        if temp < hot_threshold:
            return "[OK] "
        elif temp < 80:
            return "[WARN] "
        else:
            return "[HIGH] "

    def refresh_services_once(self):
        """Run a delayed refresh once; GLib removes the timeout on False."""
        self.refresh_services()
        return False

    def refresh_services(self):
        """Collect service status off the GTK thread."""
        if self._service_refresh_in_flight:
            return True
        self._refresh_login_status()
        self._service_refresh_in_flight = True

        def worker():
            try:
                snapshots = {}
                for name, config in SERVICES.items():
                    if name != "docker":
                        continue  # Privileged service state comes from the control API.
                    status = get_service_status(config['service'])
                    connections = (-1 if status['active'] != 'active' else
                                   get_connection_count(config['port'])) if 'port' in config else -1
                    monitor_active = ('monitor' in config and
                                      get_service_status(config['monitor'])['active'] == 'active')
                    snapshots[name] = (status, connections, monitor_active)
                mcp_instances = get_mcp_instances() if MCP_SUPPORT else {}
                try:
                    local_policy = mcp_policy_status() if MCP_POLICY_SUPPORT else None
                    policy_error = None if MCP_POLICY_SUPPORT else "Local MCP policy is not installed"
                except (PolicyError, ValueError, OSError) as exc:
                    local_policy, policy_error = None, str(exc)
                GLib.idle_add(self._apply_services_snapshot, snapshots, mcp_instances,
                              local_policy, policy_error)
            except Exception as exc:
                GLib.idle_add(self._apply_services_error, str(exc))

        threading.Thread(target=worker, name='monkey-services', daemon=True).start()
        return True

    def _apply_services_error(self, message: str):
        self._service_refresh_in_flight = False
        self.total_memory_label.set_text(f"Service status unavailable: {message[:160]}. Retry services.")
        for row in self.service_rows.values():
            if row.config.get("observe_only"):
                row.show_unavailable()
        self.mcp_policy_message.set_text(f"Local process status unavailable: {message[:160]}")
        self.mcp_policy_message.set_visible(True)
        for row in (*self.mcp_policy_rows.values(), *self.startup_mcp_policy_rows.values()):
            row.update_policy(None, [], busy=True)
        return False

    def _apply_services_snapshot(self, snapshots: dict, mcp_instances: dict,
                                 local_policy, policy_error):
        self._service_refresh_in_flight = False
        total_memory = 0.0
        for name, snapshot in snapshots.items():
            self.service_rows[name].update_status(*snapshot)
            total_memory += snapshot[0]['memory_mb']

        # A process can restart while its server count stays constant.
        current_mcps = {
            name: [(item['pid'], item.get('start_time_ticks')) for item in instances]
            for name, instances in mcp_instances.items()
        }
        old_mcps = {
            name: [(item['pid'], item.get('start_time_ticks')) for item in row.instances]
            for name, row in self.mcp_rows.items()
        }
        if current_mcps != old_mcps:
            self._rebuild_mcp_section(mcp_instances)
        for instances in mcp_instances.values():
            total_memory += sum(item.get('memory_mb', 0) for item in instances)

        if policy_error:
            self.mcp_policy_message.set_text(f"Local MCP policy unavailable: {policy_error[:160]}")
            self.mcp_policy_message.set_visible(True)
        else:
            self.mcp_policy_message.set_visible(False)
        for provider, row in (*self.mcp_policy_rows.items(),
                              *self.startup_mcp_policy_rows.items()):
            policy_row = local_policy.get(provider) if isinstance(local_policy, dict) else None
            instances = mcp_instances.get(f"{provider}-mcp", [])
            row.update_policy(policy_row, instances, busy=self._mcp_action_busy)
        if self._mcp_receipt_pending and not policy_error:
            self._set_mcp_action(
                self.mcp_action_label.get_text().replace(
                    "Checking live readback…", "Current readback shown below.").replace(
                    "checking live readback…", "current readback shown below."))
            self._mcp_receipt_pending = False

        if total_memory < 100:
            color = STATUS_OK
            tier = "[OK]"
        elif total_memory < 500:
            color = STATUS_WARN
            tier = "[WARN]"
        else:
            color = STATUS_HIGH
            tier = "[HIGH]"

        self.total_memory_label.set_markup(
            f"<b>Reported Docker + MCP memory: <span color='{color}'>{tier} {total_memory:.1f} MB</span> "
            "(not unique RAM)</b>"
        )
        return False

    def show_logs(self, service_name: str):
        """Switch to logs view for a service"""
        # Find index of service
        service_names = list(SERVICES.keys())
        if service_name in service_names:
            index = service_names.index(service_name)
            self.logs_view.service_combo.set_selected(index)
            self.stack.set_visible_child_name("logs")

    def on_theme_toggle(self, button):
        """Toggle between light and dark mode"""
        self.dark_mode = not self.dark_mode

        # Get the style manager and apply color scheme
        style_manager = Adw.StyleManager.get_default()

        # Get window widget
        window = self.get_root()

        if self.dark_mode:
            # Dark mode
            style_manager.set_color_scheme(Adw.ColorScheme.FORCE_DARK)
            window.remove_css_class("light")
            self.theme_button.set_icon_name("weather-clear-night-symbolic")
            self.theme_button.set_tooltip_text("Switch to Light Mode")
            self.app_title.set_markup(_heading_markup("MONKEY MONITOR", dark=True))
            self.pc_page.set_heading_theme(dark=True)
            print("🌙 Switched to Dark Mode")
        else:
            # Light mode
            style_manager.set_color_scheme(Adw.ColorScheme.FORCE_LIGHT)
            window.add_css_class("light")
            self.theme_button.set_icon_name("weather-clear-symbolic")
            self.theme_button.set_tooltip_text("Switch to Dark Mode")
            self.app_title.set_markup(_heading_markup("MONKEY MONITOR", dark=False))
            self.pc_page.set_heading_theme(dark=False)
            print("☀️  Switched to Light Mode")


class MonkeyMonitorApplication(Adw.Application):
    """Monkey Monitor Application with D2C Theme"""

    def __init__(self):
        super().__init__(application_id='com.monkeymonitor.ServiceMonitor')
        self.connect('activate', self.on_activate)
        self.load_theme()

    def load_theme(self):
        """Load D2C Neon Electric theme CSS"""
        css_provider = Gtk.CssProvider()

        # Try to load from installed location first
        theme_paths = [
            '/usr/local/share/monkey-monitor/monkey-monitor-theme.css',
            os.path.join(os.path.dirname(__file__), 'monkey-monitor-theme.css'),
        ]

        for theme_path in theme_paths:
            if os.path.exists(theme_path):
                try:
                    css_provider.load_from_path(theme_path)
                    Gtk.StyleContext.add_provider_for_display(
                        Gdk.Display.get_default(),
                        css_provider,
                        Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
                    )
                    print(f"🎨 D2C Theme loaded from: {theme_path}")
                    return
                except Exception as e:
                    print(f"Warning: Could not load theme from {theme_path}: {e}")

        print("Warning: D2C theme CSS not found, using default styling")

    def on_activate(self, app):
        """Application activation"""
        windows = app.get_windows()
        win = windows[0] if windows else DevMonWindow(application=app)
        win.present()


def main():
    """Main entry point"""
    app = MonkeyMonitorApplication()
    return app.run(sys.argv)


if __name__ == '__main__':
    sys.exit(main())
