#!/usr/bin/env python3
"""
eve_mtop.py (`mtop`) — Live Muse 2 EEG & Electrode Seating Monitor (Terminal TUI + Localhost Web HUD)
=====================================================================================================
- Default (`mtop` / `eve top`):
    Live 4 Hz (250ms) ANSI terminal monitor displaying TP9/AF7/AF8/TP10 contact status,
    1-40 Hz bandpower (µV), Alpha 8-13 Hz (µV), 60 Hz line noise, ADC rail %, Reference/DRL
    lock, battery %, PPG, and live 16-column Unicode waveform sparklines (`▁▂▃▄▅▆▇█`).
    Press `w` inside `mtop` to open the graphical Web Canvas HUD in your browser, or `q` to quit.
- Graphical Web HUD (`mtop --web` / `mtop --gui` / `eve gui`):
    Starts a local-only (`127.0.0.1:8765`) read-only HTTP server and opens a 60fps dark-mode
    HTML5 Canvas 4-channel oscilloscope + interactive Muse 2 forehead/ear seating diagram.
- Static Snapshot (`mtop --once`):
    Prints one snapshot and exits.

Security Invariant: Reads strictly from `~/.eve/live_eeg.json` and binds only to `127.0.0.1`.
Zero external dependencies, zero network egress, zero file modifications.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import re
import select
import shutil
import signal
import sys
import threading
import time
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional

SDK_VERSION = "2.5.4"
EVE_HOME = Path(os.environ.get("EVE_HOME", os.path.expanduser("~/.eve")))
LIVE_EEG_PATH = Path(os.environ.get("EVE_LIVE_EEG_PATH", str(EVE_HOME / "live_eeg.json")))

RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RED = "\033[31m"
CYAN = "\033[36m"
MAGENTA = "\033[35m"

SPARK_CHARS = "▁▂▃▄▅▆▇█"
CH_NAMES = ("TP9", "AF7", "AF8", "TP10")
LOC_MAP = {
    "TP9": "L-Ear/Mast",
    "AF7": "L-Forehead",
    "AF8": "R-Forehead",
    "TP10": "R-Ear/Mast",
}

ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
ANSI_ON = sys.stdout.isatty() and "NO_COLOR" not in os.environ
if not ANSI_ON:
    RESET = BOLD = DIM = GREEN = YELLOW = RED = CYAN = MAGENTA = ""

_resized = False


def _on_winch(signum, frame):
    global _resized
    _resized = True


def term_width(default: int = 100) -> int:
    try:
        return max(40, shutil.get_terminal_size((default, 30)).columns)
    except Exception:
        return default


def fit(s: str, width: int) -> str:
    if width <= 0 or len(ANSI_RE.sub("", s)) <= width:
        return s
    out: List[str] = []
    vis = 0
    i = 0
    while i < len(s):
        m = ANSI_RE.match(s, i)
        if m:
            out.append(m.group(0))
            i = m.end()
            continue
        if vis >= width - 1:
            return "".join(out) + "…" + RESET
        out.append(s[i])
        vis += 1
        i += 1
    return "".join(out)


def make_bar(val: float, max_val: float, width: int = 10, color: str = GREEN) -> str:
    ratio = max(0.0, min(1.0, val / max(max_val, 1e-6)))
    filled = int(round(ratio * width))
    return f"{color}{'█' * filled}{DIM}{'░' * (width - filled)}{RESET}"


def _goertzel_band_rms(vals: List[float], fs: float, f_lo: float, f_hi: float, step_hz: float = 2.0) -> float:
    n = len(vals)
    if n < 16:
        return 0.0
    mu = sum(vals) / n
    centered = [x - mu for x in vals]
    power_sum = 0.0
    f = f_lo
    while f <= f_hi + 1e-6:
        k = int(0.5 + (n * f) / fs)
        w = (2.0 * math.pi * k) / n
        cosine = math.cos(w)
        coeff = 2.0 * cosine
        q0 = q1 = q2 = 0.0
        for x in centered:
            q0 = coeff * q1 - q2 + x
            q2 = q1
            q1 = q0
        mag2 = q1 * q1 + q2 * q2 - q1 * q2 * coeff
        power_sum += max(0.0, mag2) / (n * n)
        f += step_hz
    return math.sqrt(power_sum * 2.0)


def _sparkline(vals: List[float], width: int = 16) -> str:
    if len(vals) < 4:
        return "·" * width
    step = max(1, len(vals) // width)
    sub = [vals[i] for i in range(0, len(vals), step)][-width:]
    lo, hi = min(sub), max(sub)
    span = max(hi - lo, 1.0)
    return "".join(SPARK_CHARS[min(7, max(0, int((v - lo) / span * 7.99)))] for v in sub)


def analyze_live_state() -> Dict[str, Any]:
    if not LIVE_EEG_PATH.exists():
        return {
            "exists": False,
            "fresh": False,
            "age_s": 999.0,
            "status": "not_running",
            "message": f"{LIVE_EEG_PATH} not found. Start daemon via: ~/.eve/sdk/eve daemon --background",
            "channels": {},
            "samples_tail": [],
        }
    try:
        raw = json.loads(LIVE_EEG_PATH.read_text(encoding="utf-8"))
    except Exception as exc:
        return {
            "exists": True,
            "fresh": False,
            "age_s": 999.0,
            "status": "read_error",
            "message": f"Error reading {LIVE_EEG_PATH}: {exc}",
            "channels": {},
            "samples_tail": [],
        }

    now = time.time()
    updated = float(raw.get("updated_at") or raw.get("updated_unix") or LIVE_EEG_PATH.stat().st_mtime)
    age_s = max(0.0, now - updated)
    samples = raw.get("samples") or []
    fs = float(raw.get("fs") or 256.0)
    fresh = bool(age_s <= 10.0 and len(samples) >= 16)

    seat = raw.get("seating_telemetry") or {}
    cq = seat.get("contact_quality") or raw.get("electrodes") or {}
    ref_pair = raw.get("ref_drl_raw12")
    if isinstance(ref_pair, list) and len(ref_pair) >= 2:
        ref_locked = (1400.0 <= float(ref_pair[0]) <= 2700.0) and (1400.0 <= float(ref_pair[1]) <= 2700.0)
    else:
        ref_locked = bool(seat.get("ref_locked", fresh))

    win = samples[-min(len(samples), 256):]
    ch_out: Dict[str, Dict[str, Any]] = {}
    k_ok = 0

    for c_idx, ch in enumerate(CH_NAMES):
        c_vals = [float(row[c_idx]) for row in win if isinstance(row, (list, tuple)) and len(row) > c_idx]
        info = cq.get(ch) if isinstance(cq, dict) else {}
        if not isinstance(info, dict):
            info = {}

        if c_vals:
            s_vals = sorted(c_vals)
            med = s_vals[len(s_vals) // 2]
            centered = [v - med for v in c_vals]
            rms_uv = math.sqrt(sum(v * v for v in centered) / len(centered))
            pinned_cnt = 0
            for i in range(1, len(c_vals)):
                v = c_vals[i]
                dv = abs(v - c_vals[i - 1])
                if abs(v) >= 920.0 or abs(v - med) >= 880.0 or (abs(v) >= 448.5 and dv < 0.8):
                    pinned_cnt += 1
            calc_rail_pct = (pinned_cnt / max(1, len(c_vals) - 1)) * 100.0
            if calc_rail_pct < 1.5:
                calc_rail_pct = 0.0
            rail_pct = float(info.get("rail_pct")) if info.get("rail_pct") is not None else calc_rail_pct
            bp_1_40 = float(info.get("bp_1_40_uv") or rms_uv)
            alpha_uv = float(info.get("alpha_8_13_uv") or _goertzel_band_rms(c_vals[-128:], fs, 8.0, 13.0, 2.5))
            l60_uv = float(info.get("line_60hz_uv") or _goertzel_band_rms(c_vals[-128:], fs, 59.0, 61.0, 2.0))
        else:
            rms_uv = float(info.get("rms_uv") or info.get("bp_1_40_uv") or 0.0)
            bp_1_40 = float(info.get("bp_1_40_uv") or rms_uv)
            alpha_uv = float(info.get("alpha_8_13_uv") or 0.0)
            l60_uv = float(info.get("line_60hz_uv") or 0.0)
            rail_pct = float(info.get("rail_pct") or 0.0)

        tier = str(info.get("quality_tier") or "").upper()
        st_raw = str(info.get("status") or "").lower()
        if st_raw == "railed" and rail_pct < 10.0 and ref_locked:
            st_raw = "settling"
            if tier == "RED":
                tier = "YELLOW"

        if not st_raw:
            if not c_vals:
                st_raw = "no_signal"
                tier = "RED"
            elif not ref_locked or rail_pct >= 15.0:
                st_raw = "railed"
                tier = "RED"
                if rail_pct < 15.0:
                    rail_pct = 100.0 if not ref_locked else 15.0
            elif rms_uv < 0.6:
                st_raw = "flat"
                tier = "RED"
            elif bp_1_40 > 240.0 or rail_pct >= 5.0:
                st_raw = "motion" if bp_1_40 > 240.0 else "settling"
                tier = "YELLOW"
            elif l60_uv > 40.0:
                st_raw = "ok_60hz"
                tier = "YELLOW"
            else:
                st_raw = "ok"
                tier = "GREEN"
        elif not tier:
            if st_raw in ("railed", "flat", "no_signal"):
                tier = "RED"
            elif st_raw in ("settling", "motion", "motion_artifact", "ok_60hz"):
                tier = "YELLOW"
            else:
                tier = "GREEN"

        is_ok = (tier != "RED") and ref_locked
        if is_ok:
            k_ok += 1

        ch_out[ch] = {
            "name": ch,
            "loc": LOC_MAP[ch],
            "status": st_raw,
            "quality_tier": tier,
            "contact_ok": is_ok,
            "rms_uv": round(rms_uv, 1),
            "bp_1_40_uv": round(bp_1_40, 1),
            "alpha_8_13_uv": round(alpha_uv, 1),
            "line_60hz_uv": round(l60_uv, 1),
            "rail_pct": round(rail_pct, 1),
            "spark": _sparkline(c_vals[-128:], width=16) if c_vals else ("·" * 16),
        }

    is_seated = bool(seat.get("is_seated", (k_ok >= 2 and ref_locked and fresh)))
    warning = raw.get("warning") or seat.get("warning")
    if not warning and not is_seated:
        if not fresh:
            warning = raw.get("message") or "Waiting for Muse 2 BLE stream (turn headband on)..."
        elif not ref_locked:
            warning = "Center forehead Reference/DRL sensor unlocked — press headband flush against bare forehead skin."
        else:
            bad = [c for c in CH_NAMES if not ch_out[c]["contact_ok"]]
            warning = f"Adjust sensor contact on {', '.join(bad)} (tuck hair behind ears & press forehead flush)."

    return {
        "exists": True,
        "fresh": fresh,
        "age_s": round(age_s, 2),
        "sdk_version": raw.get("sdk_version", SDK_VERSION),
        "status": raw.get("status", "unknown"),
        "session_id": raw.get("session_id") or "none",
        "transport": raw.get("session_transport") or "local_ble",
        "server_samples": int(raw.get("session_server_samples") or 0),
        "device_name": raw.get("device_name") or raw.get("device_id") or "Muse-2",
        "device_mac": raw.get("device_mac") or "",
        "battery_pct": raw.get("battery_pct"),
        "ppg_ir": raw.get("ppg_ir"),
        "ref_drl_raw12": ref_pair,
        "ref_locked": ref_locked,
        "is_seated": is_seated,
        "k_active": k_ok,
        "warning": warning,
        "update_available": raw.get("update_available"),
        "channels": ch_out,
        "samples_tail": [row[:4] for row in samples[-192:] if isinstance(row, (list, tuple)) and len(row) >= 4],
    }


def render_snapshot(width: Optional[int] = None, web_url: Optional[str] = None) -> str:
    width = width or term_width()
    st = analyze_live_state()
    if not st["exists"]:
        return (
            f"{RED}{BOLD}mtop:{RESET} {st['message']}\n"
            f"{DIM}Run `~/.eve/sdk/eve daemon --background` and turn on your Muse 2 headband.{RESET}"
        )

    fresh = st["fresh"]
    age_s = st["age_s"]
    k_active = st["k_active"]
    batt = st["battery_pct"]
    ppg = st["ppg_ir"]
    ref_locked = st["ref_locked"]

    fresh_badge = f"{GREEN}{BOLD}● LIVE ({age_s:.1f}s){RESET}" if fresh else f"{YELLOW}{BOLD}◌ {st['status'].upper()} ({age_s:.0f}s){RESET}"
    ch_col = GREEN if k_active == 4 else (YELLOW if k_active >= 2 else RED)
    drl_badge = f"{GREEN}{BOLD}LOCKED{RESET}" if ref_locked else f"{RED}{BOLD}UNLOCKED{RESET}"
    batt_str = f"{GREEN if (batt or 0) >= 25 else RED}{batt:.0f}%{RESET}" if batt is not None else "n/a"
    ppg_str = f"{CYAN}{ppg:.0f}{RESET}" if ppg else "n/a"

    lines: List[str] = []
    lines.append(
        f"{BOLD}MTOP{RESET} {fresh_badge}  {BOLD}{st['device_name']}{RESET}  "
        f"ch={ch_col}{BOLD}{k_active}/4{RESET}  "
        f"DRL={drl_badge}  "
        f"batt={batt_str}  ppg_ir={ppg_str}  "
        f"sess={CYAN}{st['session_id']}{RESET}"
    )

    if st["is_seated"]:
        lines.append(
            f"{BOLD}SEAT{RESET} {GREEN}{BOLD}● HEADBAND SEATED OK{RESET}  "
            f"{DIM}transport={st['transport']}  srv_samples={st['server_samples']}  sdk=v{st['sdk_version']}{RESET}"
        )
    else:
        lines.append(
            f"{BOLD}SEAT{RESET} {RED}{BOLD}⚠ {st['warning'] or 'Seat headband on bare forehead & behind ears'}{RESET}"
        )

    if st.get("update_available") and isinstance(st["update_available"], dict):
        u = st["update_available"]
        lines.append(f"{YELLOW}Notice: SDK v{u.get('latest_version')} available (run `eve update` for info){RESET}")

    if web_url:
        lines.append(f"{CYAN}{BOLD}GUI {RESET} Live Web Oscilloscope active at: {BOLD}{web_url}{RESET}")

    lines.append(f"{DIM}{'─' * max(20, width)}{RESET}")
    lines.append(
        f"{BOLD}{'CH':<5} {'LOC':<10} {'STATUS':<12} {'1-40Hz (µV)':<20} {'ALPHA 8-13Hz':<14} {'60Hz':<8} {'RAIL':<6} {'TRACE'}{RESET}"
    )

    for ch in CH_NAMES:
        c = st["channels"].get(ch, {})
        st_raw = str(c.get("status", "no_signal")).lower()
        tier = str(c.get("quality_tier", "")).upper()
        bp = float(c.get("bp_1_40_uv", 0.0))
        alpha = float(c.get("alpha_8_13_uv", 0.0))
        l60 = float(c.get("line_60hz_uv", 0.0))
        rail = float(c.get("rail_pct", 0.0))
        spark = str(c.get("spark", "·" * 16))

        if tier == "RED" or st_raw in ("flat", "no_signal") or (st_raw == "railed" and rail >= 10.0):
            st_col = RED
            st_lbl = "RAILED" if "rail" in st_raw else ("FLAT" if "flat" in st_raw else st_raw.upper()[:10])
        elif tier == "YELLOW" or st_raw in ("ok_60hz", "motion", "motion_artifact", "settling", "railed"):
            st_col = YELLOW
            if st_raw == "ok_60hz":
                st_lbl = "OK (60Hz)"
            elif "motion" in st_raw:
                st_lbl = "MOTION"
            else:
                st_lbl = "SETTLING"
        else:
            st_col, st_lbl = GREEN, "OK"

        bp_col = GREEN if (c.get("contact_ok") and bp < 120.0) else (YELLOW if c.get("contact_ok") else RED)
        bp_bar = make_bar(bp, 150.0, 8, bp_col)
        lines.append(
            f"{BOLD}{ch:<5}{RESET} {DIM}{LOC_MAP[ch]:<10}{RESET} "
            f"{st_col}{BOLD}{st_lbl:<12}{RESET} "
            f"{bp:>6.1f} µV {bp_bar}  "
            f"{CYAN}{alpha:>5.1f} µV{RESET}      "
            f"{l60:>5.1f}   "
            f"{rail:>4.1f}%  "
            f"{st_col}{spark}{RESET}"
        )

    return "\n".join(fit(line, width) for line in lines)


WEB_HUD_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mtop — Eve Muse 2 Live EEG & Seating Monitor</title>
<style>
  :root {
    --bg: #0b0f17;
    --panel: #131a27;
    --border: #233047;
    --text: #e6edf7;
    --dim: #7f91b0;
    --ok: #22c55e;
    --warn: #eab308;
    --bad: #ef4444;
    --cyan: #38bdf8;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    background: var(--bg);
    color: var(--text);
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
    padding: 18px;
  }
  .header {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 14px;
  }
  .title { font-size: 16px; font-weight: 700; display: flex; align-items: center; gap: 10px; }
  .badge {
    padding: 4px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
  }
  .badge-ok { background: rgba(34,197,94,0.18); color: var(--ok); border: 1px solid rgba(34,197,94,0.4); }
  .badge-warn { background: rgba(234,179,8,0.18); color: var(--warn); border: 1px solid rgba(234,179,8,0.4); }
  .badge-bad { background: rgba(239,68,68,0.18); color: var(--bad); border: 1px solid rgba(239,68,68,0.4); }
  .meta { font-size: 13px; color: var(--dim); display: flex; gap: 16px; flex-wrap: wrap; }
  .meta b { color: var(--text); }
  .banner {
    padding: 10px 14px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    margin-bottom: 14px;
  }
  .grid {
    display: grid;
    grid-template-columns: 320px 1fr;
    gap: 14px;
  }
  @media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
  .card {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 14px;
  }
  .card h3 {
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--dim);
    margin-bottom: 12px;
  }
  .ch-row {
    display: grid;
    grid-template-columns: 56px 95px 80px 1fr;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255,255,255,0.05);
    font-size: 12px;
  }
  .ch-row:last-child { border-bottom: none; }
  canvas {
    width: 100%;
    height: 360px;
    display: block;
    background: #080b11;
    border-radius: 8px;
    border: 1px solid var(--border);
  }
</style>
</head>
<body>
  <div class="header">
    <div class="title">
      <span>MTOP // EVE MUSE 2 MONITOR</span>
      <span id="liveBadge" class="badge badge-warn">CONNECTING</span>
      <span id="drlBadge" class="badge badge-warn">DRL: --</span>
    </div>
    <div class="meta">
      <span>Device: <b id="devName">Muse-2</b></span>
      <span>Seated: <b id="chCount">0/4</b></span>
      <span>Battery: <b id="battPct">--</b></span>
      <span>PPG IR: <b id="ppgIr">--</b></span>
      <span>Session: <b id="sessId">--</b></span>
    </div>
  </div>

  <div id="seatBanner" class="banner badge-warn">Waiting for local ~/.eve/live_eeg.json stream...</div>

  <div class="grid">
    <div class="card">
      <h3>Headband Sensor Seating Map</h3>
      <svg viewBox="0 0 280 210" width="100%" height="200">
        <!-- Head outline -->
        <ellipse cx="140" cy="110" rx="82" ry="88" fill="#0d131f" stroke="#2c3d5b" stroke-width="2"/>
        <!-- Nose indicator -->
        <polygon points="140,14 132,26 148,26" fill="#2c3d5b"/>
        <!-- Forehead band arc -->
        <path d="M 62 85 Q 140 35 218 85" fill="none" stroke="#38bdf8" stroke-width="2" stroke-dasharray="4,3"/>
        <!-- TP9 Left Ear -->
        <circle id="node_TP9" cx="46" cy="118" r="16" fill="#ef4444" stroke="#0b0f17" stroke-width="3"/>
        <text x="46" y="122" text-anchor="middle" fill="#fff" font-size="10" font-weight="bold">TP9</text>
        <text id="uv_TP9" x="46" y="148" text-anchor="middle" fill="#7f91b0" font-size="10">-- µV</text>
        <!-- AF7 Left Forehead -->
        <circle id="node_AF7" cx="98" cy="54" r="16" fill="#ef4444" stroke="#0b0f17" stroke-width="3"/>
        <text x="98" y="58" text-anchor="middle" fill="#fff" font-size="10" font-weight="bold">AF7</text>
        <text id="uv_AF7" x="98" y="83" text-anchor="middle" fill="#7f91b0" font-size="10">-- µV</text>
        <!-- REF/DRL Center Forehead -->
        <rect id="node_DRL" x="128" y="34" width="24" height="16" rx="4" fill="#ef4444" stroke="#0b0f17" stroke-width="2"/>
        <text x="140" y="45" text-anchor="middle" fill="#fff" font-size="8" font-weight="bold">DRL</text>
        <!-- AF8 Right Forehead -->
        <circle id="node_AF8" cx="182" cy="54" r="16" fill="#ef4444" stroke="#0b0f17" stroke-width="3"/>
        <text x="182" y="58" text-anchor="middle" fill="#fff" font-size="10" font-weight="bold">AF8</text>
        <text id="uv_AF8" x="182" y="83" text-anchor="middle" fill="#7f91b0" font-size="10">-- µV</text>
        <!-- TP10 Right Ear -->
        <circle id="node_TP10" cx="234" cy="118" r="16" fill="#ef4444" stroke="#0b0f17" stroke-width="3"/>
        <text x="234" y="122" text-anchor="middle" fill="#fff" font-size="10" font-weight="bold">TP10</text>
        <text id="uv_TP10" x="234" y="148" text-anchor="middle" fill="#7f91b0" font-size="10">-- µV</text>
      </svg>
      <div id="chTable"></div>
    </div>

    <div class="card">
      <h3>256 Hz Real-Time 4-Channel EEG Oscilloscope (TP9 · AF7 · AF8 · TP10)</h3>
      <canvas id="scope" width="900" height="360"></canvas>
    </div>
  </div>

<script>
const CHANNELS = ["TP9", "AF7", "AF8", "TP10"];
const COLORS = { ok: "#22c55e", ok_60hz: "#eab308", settling: "#eab308", motion: "#eab308", motion_artifact: "#eab308", flat: "#ef4444", railed: "#ef4444", no_signal: "#ef4444" };
const TIER_COLORS = { GREEN: "#22c55e", YELLOW: "#eab308", RED: "#ef4444" };

function drawScope(st) {
  const canvas = document.getElementById("scope");
  const ctx = canvas.getContext("2d");
  const W = canvas.width, H = canvas.height;
  ctx.clearRect(0, 0, W, H);

  const samples = st.samples_tail || [];
  const laneH = H / 4;

  for (let c = 0; c < 4; c++) {
    const ch = CHANNELS[c];
    const info = (st.channels && st.channels[ch]) || {};
    const yMid = laneH * c + laneH * 0.5;

    ctx.strokeStyle = "#1c2638";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(0, yMid);
    ctx.lineTo(W, yMid);
    ctx.stroke();

    const col = TIER_COLORS[info.quality_tier] || COLORS[info.status] || "#38bdf8";
    ctx.fillStyle = col;
    ctx.font = "bold 12px monospace";
    ctx.fillText(ch + " (" + (info.loc || "") + ")", 10, laneH * c + 18);
    ctx.fillStyle = "#7f91b0";
    ctx.font = "11px monospace";
    ctx.fillText(
      "status=" + (info.status || "--").toUpperCase() +
      "  1-40Hz=" + (info.bp_1_40_uv ?? 0).toFixed(1) + "µV" +
      "  alpha=" + (info.alpha_8_13_uv ?? 0).toFixed(1) + "µV" +
      "  rail=" + (info.rail_pct ?? 0).toFixed(1) + "%",
      155, laneH * c + 18
    );

    if (samples.length >= 8) {
      let vals = samples.slice(-160).map(r => r[c] || 0);
      let mean = vals.reduce((a, b) => a + b, 0) / vals.length;
      const nBins = 44;
      const step = Math.max(1, vals.length / nBins);
      const bins = [];
      for (let b = 0; b < nBins; b++) {
        const i0 = Math.floor(b * step);
        const i1 = Math.max(i0 + 1, Math.min(vals.length, Math.floor((b + 1) * step)));
        let s = 0;
        for (let i = i0; i < i1; i++) s += (vals[i] - mean);
        bins.push(s / (i1 - i0));
      }
      const alpha = 0.30;
      const fwd = new Array(bins.length);
      fwd[0] = bins[0];
      for (let i = 1; i < bins.length; i++) fwd[i] = alpha * bins[i] + (1 - alpha) * fwd[i - 1];
      const smooth = new Array(bins.length);
      smooth[bins.length - 1] = fwd[bins.length - 1];
      for (let i = bins.length - 2; i >= 0; i--) smooth[i] = alpha * fwd[i] + (1 - alpha) * smooth[i + 1];

      const pts = [];
      for (let i = 0; i < smooth.length; i++) {
        const x = (i / (smooth.length - 1)) * W;
        const norm = Math.tanh(smooth[i] / 36.0);
        const y = yMid - norm * (laneH * 0.27);
        pts.push([x, y]);
      }

      ctx.save();
      ctx.strokeStyle = col;
      ctx.globalAlpha = 0.62;
      ctx.lineWidth = 1.35;
      ctx.lineJoin = "round";
      ctx.lineCap = "round";
      ctx.beginPath();
      ctx.moveTo(pts[0][0], pts[0][1]);
      for (let i = 1; i < pts.length - 1; i++) {
        const xc = 0.5 * (pts[i][0] + pts[i + 1][0]);
        const yc = 0.5 * (pts[i][1] + pts[i + 1][1]);
        ctx.quadraticCurveTo(pts[i][0], pts[i][1], xc, yc);
      }
      ctx.lineTo(pts[pts.length - 1][0], pts[pts.length - 1][1]);
      ctx.stroke();
      ctx.restore();
    }
  }
}

async function poll() {
  try {
    const res = await fetch("/live.json", { cache: "no-store" });
    const st = await res.json();

    const liveBadge = document.getElementById("liveBadge");
    if (st.fresh) {
      liveBadge.className = "badge badge-ok";
      liveBadge.textContent = "● LIVE (" + st.age_s.toFixed(1) + "s)";
    } else {
      liveBadge.className = "badge badge-bad";
      liveBadge.textContent = "◌ " + (st.status || "STALE").toUpperCase();
    }

    const drlBadge = document.getElementById("drlBadge");
    drlBadge.className = "badge " + (st.ref_locked ? "badge-ok" : "badge-bad");
    drlBadge.textContent = "DRL: " + (st.ref_locked ? "LOCKED" : "UNLOCKED");
    document.getElementById("node_DRL").setAttribute("fill", st.ref_locked ? "#22c55e" : "#ef4444");

    document.getElementById("devName").textContent = st.device_name || "Muse-2";
    document.getElementById("chCount").textContent = (st.k_active || 0) + "/4";
    document.getElementById("battPct").textContent = st.battery_pct != null ? st.battery_pct.toFixed(0) + "%" : "n/a";
    document.getElementById("ppgIr").textContent = st.ppg_ir != null ? st.ppg_ir.toFixed(0) : "n/a";
    document.getElementById("sessId").textContent = st.session_id || "none";

    const banner = document.getElementById("seatBanner");
    if (st.is_seated) {
      banner.className = "banner badge-ok";
      banner.textContent = "● HEADBAND SEATED OK — All active Muse 2 electrodes locked and streaming at 256 Hz.";
    } else {
      banner.className = "banner badge-bad";
      banner.textContent = "⚠ " + (st.warning || "Seat Muse 2 headband firmly against bare forehead skin and behind both ears.");
    }

    let rowsHtml = "";
    for (const ch of CHANNELS) {
      const c = (st.channels && st.channels[ch]) || {};
      const col = TIER_COLORS[c.quality_tier] || COLORS[c.status] || "#ef4444";
      const node = document.getElementById("node_" + ch);
      if (node) node.setAttribute("fill", col);
      const uv = document.getElementById("uv_" + ch);
      if (uv) uv.textContent = (c.bp_1_40_uv ?? 0).toFixed(1) + " µV";

      rowsHtml += `<div class="ch-row">
        <b style="color:${col}">${ch}</b>
        <span style="color:#7f91b0">${c.loc || ""}</span>
        <b style="color:${col}">${(c.status || "--").toUpperCase()}</b>
        <span>${(c.bp_1_40_uv ?? 0).toFixed(1)} µV · α ${(c.alpha_8_13_uv ?? 0).toFixed(1)} µV</span>
      </div>`;
    }
    document.getElementById("chTable").innerHTML = rowsHtml;
    drawScope(st);
  } catch (e) {}
}
setInterval(poll, 250);
poll();
</script>
</body>
</html>
"""


class _MtopWebHandler(BaseHTTPRequestHandler):
    def log_message(self, format: str, *args: Any) -> None:
        return  # Keep terminal clean

    def do_GET(self) -> None:
        if self.path.startswith("/live.json"):
            payload = json.dumps(analyze_live_state()).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
            return
        body = WEB_HUD_HTML.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


def start_web_hud_background(port: int = 8765, open_browser: bool = True) -> str:
    srv = HTTPServer(("127.0.0.1", port), _MtopWebHandler)
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    url = f"http://127.0.0.1:{port}"
    if open_browser:
        try:
            webbrowser.open(url)
        except Exception:
            pass
    return url


def main() -> None:
    parser = argparse.ArgumentParser(description="mtop — Live Muse 2 EEG & Electrode Seating Monitor (Terminal TUI + Localhost Web HUD)")
    parser.add_argument("--once", action="store_true", help="Print one static snapshot and exit")
    parser.add_argument("-w", "--watch", action="store_true", help="(default) continuous live terminal refresh")
    parser.add_argument("--web", "--gui", action="store_true", dest="web", help="Launch localhost (127.0.0.1:8765) Web Canvas Oscilloscope GUI")
    parser.add_argument("--port", type=int, default=8765, help="Localhost port for --web (default 8765)")
    parser.add_argument("--no-browser", action="store_true", help="Do not auto-open browser tab when starting --web")
    parser.add_argument("-i", "--interval", type=float, default=0.25, help="Refresh interval in seconds (default 0.25s)")
    args = parser.parse_args()
    interval = max(0.05, args.interval)

    if args.once:
        print(render_snapshot(200))
        return

    web_url: Optional[str] = None
    if args.web:
        try:
            web_url = start_web_hud_background(port=args.port, open_browser=not args.no_browser)
        except OSError:
            web_url = f"http://127.0.0.1:{args.port}"

    if not sys.stdout.isatty():
        if web_url:
            print(json.dumps({"status": "web_hud_running", "url": web_url, "bind": "127.0.0.1"}))
            try:
                while True:
                    time.sleep(1.0)
            except KeyboardInterrupt:
                return
        print(render_snapshot(200, web_url=web_url))
        return

    try:
        signal.signal(signal.SIGWINCH, _on_winch)
    except (AttributeError, ValueError):
        pass

    stdin_tty = sys.stdin.isatty()
    saved_term = None
    if stdin_tty:
        try:
            import termios
            import tty as tty_mod
            fd = sys.stdin.fileno()
            saved_term = termios.tcgetattr(fd)
            tty_mod.setcbreak(fd)
        except Exception:
            saved_term = None

    global _resized
    try:
        sys.stdout.write("\033[?25l")
        while True:
            width = term_width()
            out = render_snapshot(width, web_url=web_url)
            footer = (
                f"{DIM}[q: exit · w: open Web GUI (127.0.0.1:{args.port}) · "
                f"{interval:.2f}s · {width} cols]{RESET}"
            )
            sys.stdout.write("\033[2J\033[H" + out + "\n" + fit(footer, width) + "\n")
            sys.stdout.flush()
            _resized = False

            deadline = time.monotonic() + interval
            while True:
                remaining = deadline - time.monotonic()
                if remaining <= 0 or _resized:
                    break
                if stdin_tty:
                    r, _, _ = select.select([sys.stdin], [], [], remaining)
                    if r:
                        key = sys.stdin.read(1)
                        if key in ("q", "Q"):
                            raise KeyboardInterrupt
                        if key in ("w", "W"):
                            if not web_url:
                                try:
                                    web_url = start_web_hud_background(port=args.port, open_browser=True)
                                except OSError:
                                    web_url = f"http://127.0.0.1:{args.port}"
                                    try:
                                        webbrowser.open(web_url)
                                    except Exception:
                                        pass
                            else:
                                try:
                                    webbrowser.open(web_url)
                                except Exception:
                                    pass
                            break
                else:
                    time.sleep(remaining)
    except KeyboardInterrupt:
        pass
    finally:
        if sys.stdout.isatty():
            sys.stdout.write("\033[?25h\n")
            sys.stdout.flush()
        if saved_term is not None:
            try:
                import termios
                termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, saved_term)
            except Exception:
                pass


if __name__ == "__main__":
    main()
