#!/usr/bin/env python3
"""
proxstrip.py v2 - Proxmox traffic + health display for a WS2812 strip
wired directly to a Raspberry Pi's GPIO.

  * Traffic: polls the Proxmox uplink over SNMP once per second. Inbound
    particles travel router -> server, outbound travel server -> router.
    Each particle's speed comes from real data: average packet size (bulk
    transfers = fast and long, chatty small packets = slow and short) blended
    with current throughput, plus a little jitter, so many speeds coexist.
  * Service tags: particles from guests listed in SERVICES (read from their
    container's network counters) and from qBittorrent (read from its Web API)
    keep the normal blue / green trail but get a solid head LED in the
    service's color, so the strip stays calm while you can still pick them out.
  * Health: polls the Proxmox API (read-only token):
        OK   -> blue / green particles
        WARN -> amber particles over a slow amber glow
        CRIT -> red particles over a faster red pulse
        DOWN -> host unreachable: whole strip pulses red
  * Rainbows (rare events):
        - "all clear" sweep when the host recovers from WARN/CRIT/DOWN
        - comet every RAINBOW_EVERY_GB received (router -> server) or sent
          (server -> router), counted on the host's own counters
        - "shiny": a 1-in-SHINY_ODDS chance each minute of comets from
          both ends meeting over a rainbow sweep
        - HTTP trigger: http://<pi>:8765/rainbow?type=in|out|sweep|shiny
  * Control page: open http://<pi>:8765/ in a browser for a live mirror of
    the strip, current state and throughput, and buttons for every rainbow.

Put your own settings in proxstrip_local.py next to this file. Anything set
there overrides the defaults below, so future versions of this script can be
dropped in without re-entering your config.

Usage:
    sudo ./venv/bin/python proxstrip.py              # real strip, real data
    sudo ./venv/bin/python proxstrip.py --demo       # real strip, fake data + all effects
    python3 proxstrip.py --simulate --demo           # terminal preview, no hardware needed
"""

import argparse
import colorsys
import json
import math
import random
import signal
import subprocess
import sys
import threading
import time
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

# =============================================================================
# DEFAULT CONFIG - override any of these in proxstrip_local.py
# =============================================================================
LED_COUNT = 150
LED_PIN = 18
LED_BRIGHTNESS = 128
LED_ORDER = "GRB"
FPS = 60
SERVER_AT_END = True       # True: LED 0 is at the router, last LED at the server

PVE_HOST = "PROXMOX_IP_ADDRESS"
PVE_NODE = "pve"
PVE_TOKEN_ID = "ledstrip@pve!strip"
PVE_TOKEN_SECRET = "00000000-0000-0000-0000-000000000000"
PVE_VERIFY_TLS = False

SNMP_COMMUNITY = "changeme"
SNMP_INTERFACE = "eno1"       # physical uplink NIC; see `ip -br link` on the host
SWAP_RX_TX = False
SNMP_POLL_SECONDS = 1.0

HEALTH_POLL_SECONDS = 15
WATCH_VMIDS = []
CPU_WARN, CPU_CRIT = 0.85, 0.97
MEM_WARN, MEM_CRIT = 0.90, 0.97
STORAGE_WARN, STORAGE_CRIT = 0.85, 0.95
STORAGE_OVERRIDES = {}     # per-storage (warn, crit), e.g. {"storage_name": (0.99, 1.00)}
UNREACHABLE_AFTER = 3

SCALE_MBPS = 1000
IDLE_MBPS = 0.02

# --- Service colors (optional) ---
SERVICES = []              # [(name, guest interface, head color)], e.g. [("Jellyfin", "veth101i0", (200, 0, 255))]
QBIT_URL = ""              # e.g. "http://QBIT_IP_ADDRESS:8081" (needs auth bypass for the Pi's subnet)
QBIT_COLOR = (255, 255, 255)   # head color for qBittorrent particles
QBIT_GAIN = 1.0            # qBittorrent head brightness relative to the others
OTHER_NAME = "Everything else"

# --- Color ---
RX_COLOR = (0, 40, 255)    # inbound: deep blue
TX_COLOR = (0, 255, 20)    # outbound: pure green
WARN_COLOR = (255, 80, 0)
CRIT_COLOR = (255, 0, 0)
HEAD_WHITENESS = 0.12      # 0 = head same color as trail, 1 = white head
SATURATION = 1.4           # 1.0 = off; higher pushes every pixel away from white
GAMMA = 2.2                # LED gamma correction; 1.0 = off (the old, paler look)

# --- Particle motion ---
SPEED_MIN, SPEED_MAX = 7.0, 48.0   # LEDs per second
SPEED_SIZE_WEIGHT = 0.65   # 0 = speed from throughput only, 1 = from packet size only
SPEED_JITTER = 0.15        # random +/- per particle
MAX_SPAWN_PER_SEC = 3.0
BASE_TRAIL = 9
MAX_PARTICLES_PER_DIR = 40

# --- Rainbows ---
RAINBOW_ON_RECOVERY = True
RAINBOW_EVERY_GB = 100     # 0 disables data milestones
SHINY_ODDS = 4096          # 1-in-N per minute (~once every 2.8 days); 0 disables
TRIGGER_PORT = 8765        # 0 disables the HTTP trigger
RAINBOW_LENGTH = 30        # comet length in LEDs
RAINBOW_SPEED = 40.0       # comet speed, LEDs per second
SWEEP_SECONDS = 6.0
# =============================================================================

try:
    from proxstrip_local import *   # noqa: F401,F403  (your settings)
except ImportError:
    pass

OID_IFNAME = "1.3.6.1.2.1.31.1.1.1.1"
OID_HC_IN = "1.3.6.1.2.1.31.1.1.1.6"
OID_HC_IN_PKTS = "1.3.6.1.2.1.31.1.1.1.7"
OID_HC_OUT = "1.3.6.1.2.1.31.1.1.1.10"
OID_HC_OUT_PKTS = "1.3.6.1.2.1.31.1.1.1.11"

OK, WARN, CRIT, DOWN = "OK", "WARN", "CRIT", "DOWN"
RAINBOW_KINDS = ("in", "out", "sweep", "shiny")


def log(msg):
    print(time.strftime("%Y-%m-%d %H:%M:%S"), msg, flush=True)


def clamp01(x):
    return max(0.0, min(1.0, x))


class Shared:
    """State shared between poller threads and the render loop."""
    def __init__(self):
        self.lock = threading.Lock()
        # Mbps / packets-per-second, all from the server's point of view (rx = into the server)
        self.up = {"rx_mbps": 0.0, "tx_mbps": 0.0, "rx_pps": 0.0, "tx_pps": 0.0, "t": 0.0}
        self.svc = {}               # service name -> same keys as up (minus t)
        self.qb = {"rx_mbps": 0.0, "tx_mbps": 0.0, "t": 0.0}
        self.state = OK
        self.reasons = []
        self.events = []
        self.history = deque(maxlen=12)
        self.frame = []

    def fire(self, kind, why):
        with self.lock:
            self.events.append(kind)
            self.history.appendleft({"time": time.strftime("%H:%M:%S"), "kind": kind, "why": why})
        log(f"rainbow: {kind} ({why})")


def mbps_to_activity(mbps):
    if mbps < IDLE_MBPS:
        return 0.0
    return clamp01(math.log10(1 + mbps) / math.log10(1 + SCALE_MBPS))


def size_factor(nbytes, npkts):
    if npkts <= 0:
        return 0.0
    return clamp01((nbytes / npkts - 100) / 1300)   # ~100 B chatter .. ~1400 B bulk


def size_from_rate(mbps, pps):
    return size_factor(mbps * 1e6 / 8, pps)


def compute_sources(shared):
    """Split uplink traffic into colored sources. Each entry: name, colors, gain,
    and per-direction Mbps and packet-size factor."""
    now = time.monotonic()
    with shared.lock:
        up = dict(shared.up)
        svc = {k: dict(v) for k, v in shared.svc.items()}
        qb = dict(shared.qb)
    if now - up["t"] > 5:
        up = {"rx_mbps": 0.0, "tx_mbps": 0.0, "rx_pps": 0.0, "tx_pps": 0.0}
        svc = {}
    sources = []
    rem = {"rx_mbps": up["rx_mbps"], "tx_mbps": up["tx_mbps"],
           "rx_pps": up["rx_pps"], "tx_pps": up["tx_pps"]}

    for name, _iface, color, *rest in SERVICES:
        d = svc.get(name, {"rx_mbps": 0.0, "tx_mbps": 0.0, "rx_pps": 0.0, "tx_pps": 0.0})
        src = {"name": name, "rx_color": RX_COLOR, "tx_color": TX_COLOR, "head": color,
               "gain": rest[0] if rest else 1.0}
        for k in ("rx", "tx"):
            src[k + "_mbps"] = d[k + "_mbps"]
            src[k + "_size"] = size_from_rate(d[k + "_mbps"], d[k + "_pps"])
            rem[k + "_mbps"] -= d[k + "_mbps"]
            rem[k + "_pps"] -= d[k + "_pps"]
        sources.append(src)

    if QBIT_URL:
        fresh = now - qb["t"] <= 5
        src = {"name": "qBittorrent", "rx_color": RX_COLOR, "tx_color": TX_COLOR, "head": QBIT_COLOR,
               "gain": QBIT_GAIN}
        for k in ("rx", "tx"):
            mbps = qb[k + "_mbps"] if fresh else 0.0
            src[k + "_mbps"] = mbps
            # qBittorrent reports payload only; assume torrent data rides in near-full-size packets
            src[k + "_size"] = size_from_rate(up[k + "_mbps"], up[k + "_pps"]) if mbps else 0.0
            rem[k + "_mbps"] -= mbps
            rem[k + "_pps"] -= mbps * 1e6 / 8 / 1400
        sources.append(src)

    other = {"name": OTHER_NAME, "rx_color": RX_COLOR, "tx_color": TX_COLOR, "head": None, "gain": 1.0}
    for k in ("rx", "tx"):
        mbps = max(0.0, rem[k + "_mbps"])
        other[k + "_mbps"] = mbps
        other[k + "_size"] = size_from_rate(mbps, max(1.0, rem[k + "_pps"])) if mbps else 0.0
    sources.append(other)
    return sources


# ----------------------------------------------------------------------------
# Traffic via SNMP
# ----------------------------------------------------------------------------
def snmp(cmd, *oids):
    out = subprocess.run(
        [cmd, "-v2c", "-c", SNMP_COMMUNITY, "-Oqn", "-t", "3", "-r", "1", PVE_HOST, *oids],
        capture_output=True, text=True, timeout=15,
    )
    if out.returncode != 0:
        raise RuntimeError(out.stderr.strip() or "snmp failed")
    return out.stdout.strip().splitlines()


def if_index_map():
    names = {}
    for line in snmp("snmpwalk", OID_IFNAME):
        oid, _, name = line.partition(" ")
        names[name.strip().strip('"')] = oid.rsplit(".", 1)[-1]
    return names


def snmp_values(lines):
    vals = []
    for line in lines:
        parts = line.split(None, 1)
        try:
            vals.append(int(parts[1]))
        except (IndexError, ValueError):
            vals.append(None)          # e.g. a stopped container's interface
    return vals


def traffic_poller(shared, stop):
    """Polls the uplink plus every SERVICES interface in one SNMP request.
    Guest interface numbers change when a container restarts, so the
    name -> number map is refreshed every minute or whenever a lookup misses."""
    idx_map, last_walk, prev, fails = {}, 0.0, {}, 0
    step = RAINBOW_EVERY_GB * 1e9 if RAINBOW_EVERY_GB else 0
    names = [SNMP_INTERFACE] + [svc[1] for svc in SERVICES]
    while not stop.is_set():
        try:
            now = time.monotonic()
            if SNMP_INTERFACE not in idx_map or now - last_walk > 60:
                had_uplink = SNMP_INTERFACE in idx_map
                idx_map, last_walk = if_index_map(), now
                if SNMP_INTERFACE not in idx_map:
                    raise RuntimeError(f"interface {SNMP_INTERFACE!r} not found via SNMP")
                if not had_uplink:
                    log(f"SNMP: {SNMP_INTERFACE} is ifIndex {idx_map[SNMP_INTERFACE]}")
                    for svc in SERVICES:
                        where = f"ifIndex {idx_map[svc[1]]}" if svc[1] in idx_map else "not found (stopped?)"
                        log(f"SNMP: {svc[0]} ({svc[1]}) {where}")
            present = [n for n in names if n in idx_map]
            oids = []
            for n in present:
                i = idx_map[n]
                oids += [f"{OID_HC_IN}.{i}", f"{OID_HC_OUT}.{i}", f"{OID_HC_IN_PKTS}.{i}", f"{OID_HC_OUT_PKTS}.{i}"]
            vals = snmp_values(snmp("snmpget", *oids))
            now = time.monotonic()
            readings = {n: vals[k * 4:k * 4 + 4] for k, n in enumerate(present)}

            up = readings[SNMP_INTERFACE]
            if None in up:
                idx_map = {}
                raise RuntimeError("uplink counters missing")
            if SWAP_RX_TX:
                up = [up[1], up[0], up[3], up[2]]
            # guest interfaces are seen from the host side: "in" = leaving the container
            for n in present[1:]:
                r = readings[n]
                if None in r:
                    last_walk = 0.0
                    readings.pop(n)
                else:
                    readings[n] = [r[1], r[0], r[3], r[2]]
            readings[SNMP_INTERFACE] = up

            rates = {}
            for n, r in readings.items():
                if n in prev:
                    dt = now - prev[n][0]
                    d = [a - b for a, b in zip(r, prev[n][1])]
                    if dt > 0 and min(d) >= 0:     # skip counter resets / restarts
                        rates[n] = {"rx_mbps": d[0] * 8 / dt / 1e6, "tx_mbps": d[1] * 8 / dt / 1e6,
                                    "rx_pps": d[2] / dt, "tx_pps": d[3] / dt}
            if step and SNMP_INTERFACE in prev:
                old = prev[SNMP_INTERFACE][1]
                if up[0] // step > old[0] // step:
                    shared.fire("in", f"{up[0] // step * RAINBOW_EVERY_GB:.0f} GB received")
                if up[1] // step > old[1] // step:
                    shared.fire("out", f"{up[1] // step * RAINBOW_EVERY_GB:.0f} GB sent")
            prev = {n: (now, r) for n, r in readings.items()}

            with shared.lock:
                if SNMP_INTERFACE in rates:
                    shared.up = dict(rates[SNMP_INTERFACE], t=now)
                for name, iface, *_ in SERVICES:
                    if iface in rates:
                        shared.svc[name] = rates[iface]
                    elif iface not in readings:
                        shared.svc.pop(name, None)
            if fails:
                log(f"SNMP recovered after {fails} failed poll(s)")
            fails = 0
        except Exception as e:
            fails += 1
            if fails == 1:
                log(f"SNMP poll failed: {e}")
            if fails >= 10:
                idx_map = {}
            prev = {}
        stop.wait(SNMP_POLL_SECONDS)


def qbit_poller(shared, stop):
    import requests
    url = QBIT_URL.rstrip("/") + "/api/v2/transfer/info"
    fails = 0
    while not stop.is_set():
        try:
            r = requests.get(url, timeout=3)
            r.raise_for_status()
            d = r.json()
            with shared.lock:
                shared.qb = {"rx_mbps": d.get("dl_info_speed", 0) * 8 / 1e6,
                             "tx_mbps": d.get("up_info_speed", 0) * 8 / 1e6,
                             "t": time.monotonic()}
            if fails:
                log(f"qBittorrent recovered after {fails} failed poll(s)")
            fails = 0
        except Exception as e:
            fails += 1
            if fails == 1:
                log(f"qBittorrent poll failed: {e}")
        stop.wait(1.0)


# ----------------------------------------------------------------------------
# Health via Proxmox API
# ----------------------------------------------------------------------------
def health_poller(shared, stop):
    import requests
    import urllib3
    if not PVE_VERIFY_TLS:
        urllib3.disable_warnings()
    s = requests.Session()
    s.headers["Authorization"] = f"PVEAPIToken={PVE_TOKEN_ID}={PVE_TOKEN_SECRET}"
    s.verify = PVE_VERIFY_TLS
    base = f"https://{PVE_HOST}:8006/api2/json"

    def get(path):
        r = s.get(base + path, timeout=5)
        r.raise_for_status()
        return r.json()["data"]

    def grade(value, w, c, label, warn, crit):
        if value >= c:
            crit.append(label)
        elif value >= w:
            warn.append(label)

    failures = 0
    while not stop.is_set():
        warn, crit = [], []
        try:
            st = get(f"/nodes/{PVE_NODE}/status")
            cpu = st.get("cpu", 0)
            mem = st["memory"]["used"] / max(1, st["memory"]["total"])
            grade(cpu, CPU_WARN, CPU_CRIT, f"CPU {cpu:.0%}", warn, crit)
            grade(mem, MEM_WARN, MEM_CRIT, f"RAM {mem:.0%}", warn, crit)

            for r in get("/cluster/resources"):
                if r.get("node") != PVE_NODE:
                    continue
                if r.get("type") in ("qemu", "lxc") and r.get("vmid") in WATCH_VMIDS:
                    if r.get("status") != "running":
                        crit.append(f"{r.get('name', r['vmid'])} ({r['vmid']}) is {r.get('status')}")
                elif r.get("type") == "storage":
                    name = r.get("storage")
                    if r.get("status") != "available":
                        warn.append(f"storage {name} {r.get('status')}")
                    elif r.get("maxdisk"):
                        u = r.get("disk", 0) / r["maxdisk"]
                        sw, sc = STORAGE_OVERRIDES.get(name, (STORAGE_WARN, STORAGE_CRIT))
                        grade(u, sw, sc, f"storage {name} {u:.0%} full", warn, crit)

            try:
                for pool in get(f"/nodes/{PVE_NODE}/disks/zfs"):
                    if pool.get("health", "ONLINE") != "ONLINE":
                        crit.append(f"ZFS {pool.get('name')} {pool.get('health')}")
            except Exception:
                pass

            failures = 0
            state = CRIT if crit else WARN if warn else OK
            reasons = crit + warn
        except Exception as e:
            failures += 1
            log(f"API poll failed ({failures}/{UNREACHABLE_AFTER}): {e}")
            with shared.lock:
                state = DOWN if failures >= UNREACHABLE_AFTER else shared.state
                reasons = ["Proxmox API unreachable"] if state == DOWN else shared.reasons

        with shared.lock:
            changed = state != shared.state or reasons != shared.reasons
            old = shared.state
            shared.state, shared.reasons = state, reasons
        if changed:
            log(f"state {old} -> {state}" + (f": {'; '.join(reasons)}" if reasons else ""))
        stop.wait(HEALTH_POLL_SECONDS)


# ----------------------------------------------------------------------------
# Demo data (no Proxmox needed)
# ----------------------------------------------------------------------------
def demo_poller(shared, stop):
    t0 = time.monotonic()
    states = [(OK, 30), (WARN, 8), (OK, 12), (CRIT, 8), (DOWN, 6)]
    cycle = sum(d for _, d in states)
    rx_base = tx_base = 2.0
    last, shiny_done = None, False
    while not stop.is_set():
        rx_base = max(0.05, rx_base * random.uniform(0.85, 1.18))
        tx_base = max(0.05, tx_base * random.uniform(0.85, 1.18))
        other_rx = rx_base * (40 if random.random() < 0.05 else 1)
        other_tx = tx_base * (40 if random.random() < 0.04 else 1)
        el = (time.monotonic() - t0) % cycle
        if el < 1:
            shiny_done = False
        for st, d in states:
            if el < d:
                break
            el -= d
        phase = (time.monotonic() - t0) % 40
        svc = {}
        up_rx, up_tx = other_rx, other_tx
        up_rx_pps = other_rx * 1e6 / 8 / 400
        up_tx_pps = other_tx * 1e6 / 8 / 400
        for k, (name, *_rest) in enumerate(SERVICES):
            streaming = (phase + k * 13) % 40 < 22          # a stream that comes and goes
            tx = random.uniform(8, 20) if streaming else 0.02
            rx = 0.4 if streaming else 0.01
            svc[name] = {"rx_mbps": rx, "tx_mbps": tx,
                         "rx_pps": rx * 1e6 / 8 / 120, "tx_pps": tx * 1e6 / 8 / 1400}
            up_rx += rx; up_tx += tx
            up_rx_pps += svc[name]["rx_pps"]; up_tx_pps += svc[name]["tx_pps"]
        qb = {"rx_mbps": 0.0, "tx_mbps": 0.0, "t": time.monotonic()}
        if QBIT_URL:
            downloading = 10 < phase < 32
            qb["rx_mbps"] = random.uniform(15, 60) if downloading else 0.0
            qb["tx_mbps"] = random.uniform(0.5, 3)
            up_rx += qb["rx_mbps"] * 1.04; up_tx += qb["tx_mbps"] * 1.04
            up_rx_pps += qb["rx_mbps"] * 1e6 / 8 / 1400; up_tx_pps += qb["tx_mbps"] * 1e6 / 8 / 1400
        with shared.lock:
            shared.up = {"rx_mbps": up_rx, "tx_mbps": up_tx, "rx_pps": up_rx_pps,
                         "tx_pps": up_tx_pps, "t": time.monotonic()}
            shared.svc = svc
            shared.qb = qb
            shared.state = st
        if st != last:
            log(f"demo state -> {st}")
            last = st
        if st == OK and random.random() < 0.06:
            shared.fire(random.choice(("in", "out")), "demo")
        if st == OK and 18 < el < 19 and not shiny_done:
            shared.fire("shiny", "demo")
            shiny_done = True
        stop.wait(1.0)


# ----------------------------------------------------------------------------
# HTTP trigger
# ----------------------------------------------------------------------------
def display_hex(color):
    """Approximate on-screen color of an LED color after saturation + gamma."""
    r, g, b = finalize(color)
    inv = 1 / max(GAMMA, 0.01)
    return "#" + "".join(f"{round(255 * (c / 255) ** inv):02x}" for c in (r, g, b))


def status(shared):
    sources = compute_sources(shared)
    with shared.lock:
        data = {
            "state": shared.state,
            "reasons": list(shared.reasons),
            "history": list(shared.history),
        }
    data["rx_mbps"] = round(sum(s["rx_mbps"] for s in sources), 2)
    data["tx_mbps"] = round(sum(s["tx_mbps"] for s in sources), 2)
    data["sources"] = [{
        "name": s["name"],
        "rx": round(s["rx_mbps"], 2), "tx": round(s["tx_mbps"], 2),
        "rx_color": display_hex(s["rx_color"]), "tx_color": display_hex(s["tx_color"]),
        "head": display_hex(s["head"]) if s.get("head") else None,
    } for s in sources]
    frame = shared.frame
    data.update({
        "pixels": "".join(f"{r:02x}{g:02x}{b:02x}" for r, g, b in frame),
        "gamma": GAMMA,
        "server_at_end": SERVER_AT_END,
        "shiny_odds": SHINY_ODDS,
        "every_gb": RAINBOW_EVERY_GB,
    })
    return data


CONTROL_PAGE = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>proxstrip</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🌈</text></svg>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
  :root {
    color-scheme: dark;
    --bg: #0a0c0f;
    --panel: #11151a;
    --line: #1e252d;
    --ink: #dce4e8;
    --dim: #7f8c96;
    --teal: #00c8a0;
    --amber: #ff8a1f;
    --red: #ff4040;
    --mono: "Space Mono", ui-monospace, Menlo, Consolas, monospace;
    --sans: "DM Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; background: var(--bg); color: var(--ink); }
  body {
    font: 16px/1.55 var(--sans);
    min-height: 100vh;
    padding: max(24px, env(safe-area-inset-top)) 20px max(32px, env(safe-area-inset-bottom));
  }
  body::after {
    content: "";
    position: fixed; inset: 0; pointer-events: none;
    background: repeating-linear-gradient(to bottom, rgba(255,255,255,.022) 0 1px, transparent 1px 3px);
  }
  main { max-width: 900px; margin: 0 auto; }

  header { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
  h1 { font: 700 1.6rem/1.1 var(--mono); margin: 0; letter-spacing: -.02em; }
  h1 small { display: block; font: 400 .8rem/1.4 var(--sans); color: var(--dim); letter-spacing: 0; margin-top: 4px; }

  .state {
    font: 700 .95rem var(--mono);
    padding: 6px 14px; border-radius: 999px;
    border: 1px solid currentColor; color: var(--dim);
    display: inline-flex; align-items: center; gap: 8px;
  }
  .state::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: currentColor; }
  .state[data-s="OK"] { color: var(--teal); }
  .state[data-s="WARN"] { color: var(--amber); }
  .state[data-s="CRIT"], .state[data-s="DOWN"] { color: var(--red); }
  .reasons { color: var(--dim); margin: 10px 0 0; min-height: 1.55em; }

  /* the live strip */
  .strip {
    margin: 26px 0 0;
    background: #000;
    border: 1px solid var(--line);
    border-radius: 14px;
    padding: 22px 16px 14px;
  }
  canvas { display: block; width: 100%; height: 34px; }
  .ends {
    display: flex; justify-content: space-between; align-items: baseline;
    margin-top: 14px; font: 400 .85rem var(--mono); color: var(--dim);
  }
  .ends > span { white-space: nowrap; }
  .ends b { color: var(--ink); font-weight: 700; }
  .rate-in { color: #4d7dff; }
  .rate-out { color: #2bff6a; }

  .legend {
    display: flex; flex-wrap: wrap; gap: 8px 22px;
    margin: 14px 0 0; padding: 12px 2px 0; border-top: 1px solid var(--line);
    font-size: .88rem;
  }
  .src { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 2px 8px; }
  .src .n, .src .r { white-space: nowrap; }
  .sw { display: inline-flex; border-radius: 3px; overflow: hidden; }
  .sw i { display: block; width: 8px; height: 14px; }
  .src .n { color: var(--ink); }
  .src .r { color: var(--dim); font-family: var(--mono); font-size: .8rem; }

  .controls {
    display: grid; gap: 10px; margin-top: 22px;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  button {
    font: inherit; color: var(--ink); text-align: left; cursor: pointer;
    background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
    padding: 16px 16px 14px; display: grid; gap: 2px;
    transition: border-color .15s, transform .08s;
  }
  button:hover { border-color: #33404b; }
  button:active { transform: translateY(1px); }
  button:focus-visible { outline: 2px solid var(--teal); outline-offset: 2px; }
  button .t { font: 700 1rem var(--mono); }
  button .d { color: var(--dim); font-size: .9rem; }
  button[data-sent] { border-color: var(--teal); }
  button[data-sent] .d { color: var(--teal); }
  button[data-failed] { border-color: var(--red); }
  button[data-failed] .d { color: var(--red); }
  button.shiny {
    border: 1px solid transparent;
    background:
      linear-gradient(var(--panel), var(--panel)) padding-box,
      linear-gradient(90deg, #ff3b3b, #ffb21f, #3bff6a, #2bd4ff, #5a5cff, #ff3bd7) border-box;
  }

  section.log { margin-top: 34px; }
  h2 { font: 700 1rem var(--mono); margin: 0 0 10px; }
  ol { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--line); }
  li {
    display: grid; grid-template-columns: 5.5em 6.5em 1fr; gap: 12px;
    padding: 9px 0; border-bottom: 1px solid var(--line); font-size: .92rem;
  }
  li time { font-family: var(--mono); color: var(--dim); }
  li .k { font-family: var(--mono); }
  li .w { color: var(--dim); }
  li.empty { display: block; color: var(--dim); padding: 12px 0; border-bottom: 1px solid var(--line); }
  footer { margin-top: 30px; color: var(--dim); font-size: .85rem; max-width: 62ch; }

  @media (max-width: 520px) {
    .ends { font-size: .72rem; gap: 8px; }
    li { grid-template-columns: 5em 1fr; }
    li .w { grid-column: 1 / -1; padding-left: 0; margin-top: -4px; }
  }
  @media (prefers-reduced-motion: reduce) {
    button { transition: none; }
  }
</style>
</head>
<body>
<main>
  <header>
    <h1>proxstrip<small>Belmont Labs: server traffic, made visible</small></h1>
    <span class="state" id="state" data-s="">Connecting</span>
  </header>
  <p class="reasons" id="reasons"></p>

  <div class="strip" aria-label="Live view of the LED strip">
    <canvas id="strip"></canvas>
    <div class="ends">
      <span><b>Router</b> <span class="rate-in" id="rin">in 0 Mbps →</span></span>
      <span><span class="rate-out" id="rout">← out 0 Mbps</span> <b>Server</b></span>
    </div>
    <div class="legend" id="legend" aria-label="Traffic by service"></div>
  </div>

  <div class="controls">
    <button data-type="in"><span class="t">Inbound comet</span><span class="d">Router to server</span></button>
    <button data-type="out"><span class="t">Outbound comet</span><span class="d">Server to router</span></button>
    <button data-type="sweep"><span class="t">Full sweep</span><span class="d">Rainbow across the whole strip</span></button>
    <button data-type="shiny" class="shiny"><span class="t">Force a shiny</span><span class="d" id="odds">Skip the odds</span></button>
  </div>

  <section class="log">
    <h2>Rainbow log</h2>
    <ol id="log"></ol>
  </section>

  <footer id="note">Researcher's note: the strip cannot tell an earned rainbow from a forced one. The log can.</footer>
</main>

<script>
  const cv = document.getElementById('strip');
  const ctx = cv.getContext('2d');
  const stateEl = document.getElementById('state');
  const reasonsEl = document.getElementById('reasons');
  const logEl = document.getElementById('log');
  const KIND = { in: 'Inbound', out: 'Outbound', sweep: 'Sweep', shiny: 'Shiny' };
  let lastLog = '';

  function fmt(mbps) {
    if (mbps >= 100) return mbps.toFixed(0) + ' Mbps';
    if (mbps >= 1) return mbps.toFixed(1) + ' Mbps';
    return (mbps * 1000).toFixed(0) + ' kbps';
  }

  function draw(hex, gamma, serverAtEnd) {
    const n = hex.length / 6;
    if (!n) return;
    const dpr = window.devicePixelRatio || 1;
    const w = cv.clientWidth, h = cv.clientHeight;
    if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) {
      cv.width = Math.round(w * dpr); cv.height = Math.round(h * dpr);
    }
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, w, h);
    const step = w / n;
    const lw = Math.max(1.5, Math.min(step * 0.72, h * 0.5));
    const lh = Math.max(lw, h * 0.36);
    const inv = 1 / (gamma || 1);
    for (let i = 0; i < n; i++) {
      const j = serverAtEnd ? i : n - 1 - i;
      const o = j * 6;
      let r = parseInt(hex.substr(o, 2), 16), g = parseInt(hex.substr(o + 2, 2), 16), b = parseInt(hex.substr(o + 4, 2), 16);
      r = 255 * Math.pow(r / 255, inv); g = 255 * Math.pow(g / 255, inv); b = 255 * Math.pow(b / 255, inv);
      const x = i * step + step / 2, y = h / 2;
      const lit = Math.max(r, g, b);
      ctx.shadowBlur = lit > 25 ? Math.max(6, lw * 2.2) : 0;
      ctx.shadowColor = `rgb(${r | 0},${g | 0},${b | 0})`;
      ctx.fillStyle = lit > 6 ? `rgb(${r | 0},${g | 0},${b | 0})` : '#14181d';
      ctx.fillRect(x - lw / 2, y - lh / 2, lw, lh);
    }
    ctx.shadowBlur = 0;
  }

  let lastLegend = '';
  function renderLegend(sources) {
    const el = document.getElementById('legend');
    if (!sources || sources.length < 2) { el.hidden = true; return; }
    el.hidden = false;
    const key = sources.map(s => s.name + s.rx_color + s.tx_color + s.head).join('|');
    if (key !== lastLegend) {
      lastLegend = key;
      el.textContent = '';
      for (const s of sources) {
        const item = document.createElement('span'); item.className = 'src';
        const sw = document.createElement('span'); sw.className = 'sw';
        const colors = s.head ? [s.head] : (s.rx_color === s.tx_color ? [s.rx_color] : [s.rx_color, s.tx_color]);
        for (const c of colors) {
          const i = document.createElement('i'); i.style.background = c;
          if (colors.length === 1) i.style.width = '14px';
          sw.appendChild(i);
        }
        const n = document.createElement('span'); n.className = 'n'; n.textContent = s.name;
        const r = document.createElement('span'); r.className = 'r';
        item.append(sw, n, r);
        el.appendChild(item);
      }
    }
    el.querySelectorAll('.r').forEach((r, k) => {
      const s = sources[k];
      r.textContent = 'in ' + fmt(s.rx) + ', out ' + fmt(s.tx);
    });
  }

  function renderLog(history) {
    const key = JSON.stringify(history);
    if (key === lastLog) return;
    lastLog = key;
    logEl.textContent = '';
    if (!history.length) {
      const p = document.createElement('li');
      p.className = 'empty';
      p.textContent = 'No rainbows yet this session. Press a button above to send one.';
      logEl.appendChild(p);
      return;
    }
    for (const e of history) {
      const li = document.createElement('li');
      const t = document.createElement('time'); t.textContent = e.time;
      const k = document.createElement('span'); k.className = 'k'; k.textContent = KIND[e.kind] || e.kind;
      const w = document.createElement('span'); w.className = 'w'; w.textContent = e.why;
      li.append(t, k, w);
      logEl.appendChild(li);
    }
  }

  async function poll() {
    try {
      const r = await fetch('/status', { cache: 'no-store' });
      if (!r.ok) throw new Error(r.status);
      const s = await r.json();
      stateEl.dataset.s = s.state;
      stateEl.textContent = s.state;
      reasonsEl.textContent = s.reasons.length ? s.reasons.join('; ') : 'All systems nominal.';
      document.getElementById('rin').textContent = 'in ' + fmt(s.rx_mbps) + ' →';
      document.getElementById('rout').textContent = '← out ' + fmt(s.tx_mbps);
      const sb = document.querySelector('.shiny');
      if (!('sent' in sb.dataset) && !('failed' in sb.dataset)) {
        document.getElementById('odds').textContent = s.shiny_odds ? `Skip the 1-in-${s.shiny_odds} odds` : 'Shiny odds are off';
      }
      draw(s.pixels, s.gamma, s.server_at_end);
      renderLegend(s.sources);
      renderLog(s.history);
    } catch (e) {
      stateEl.dataset.s = '';
      stateEl.textContent = 'No signal';
      reasonsEl.textContent = 'The page can’t reach proxstrip. Check that the service is running on the Pi.';
    }
    setTimeout(poll, 250);
  }

  document.querySelectorAll('button[data-type]').forEach(btn => {
    const d = btn.querySelector('.d');
    btn.addEventListener('click', async () => {
      const original = d.textContent;
      delete btn.dataset.sent; delete btn.dataset.failed;
      try {
        const r = await fetch('/rainbow?type=' + btn.dataset.type, { method: 'POST' });
        if (!r.ok) throw new Error(r.status);
        btn.dataset.sent = ''; d.textContent = 'Sent';
      } catch (e) {
        btn.dataset.failed = ''; d.textContent = 'Not sent: no answer from the Pi';
      }
      setTimeout(() => { delete btn.dataset.sent; delete btn.dataset.failed; d.textContent = original; }, 1600);
    });
  });

  poll();
</script>
</body>
</html>"""


def trigger_server(shared):
    class Handler(BaseHTTPRequestHandler):
        def _handle(self):
            length = int(self.headers.get("Content-Length") or 0)
            if length:
                self.rfile.read(min(length, 65536))
            url = urlparse(self.path)
            if url.path in ("/", "/index.html"):
                return self._send(200, "text/html; charset=utf-8", CONTROL_PAGE.encode())
            if url.path == "/status":
                return self._send(200, "application/json", json.dumps(status(shared)).encode())
            kind = parse_qs(url.query).get("type", ["sweep"])[0]
            if url.path != "/rainbow" or kind not in RAINBOW_KINDS:
                self.send_response(404)
                self.end_headers()
                self.wfile.write(b"use /rainbow?type=in|out|sweep|shiny\n")
                return
            shared.fire(kind, f"HTTP from {self.client_address[0]}")
            self._send(200, "application/json", b'{"ok": true}\n')

        def _send(self, code, ctype, body):
            self.send_response(code)
            self.send_header("Content-Type", ctype)
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        do_GET = _handle
        do_POST = _handle

        def log_message(self, *args):
            pass

    try:
        srv = ThreadingHTTPServer(("0.0.0.0", TRIGGER_PORT), Handler)
    except OSError as e:
        log(f"HTTP trigger disabled: {e}")
        return
    log(f"HTTP trigger listening on port {TRIGGER_PORT}")
    srv.serve_forever()


# ----------------------------------------------------------------------------
# Rendering
# ----------------------------------------------------------------------------
GAMMA_LUT = [round(255 * (i / 255) ** GAMMA) for i in range(256)]
INBOUND_DIR = +1 if SERVER_AT_END else -1     # direction toward the server


def lerp(a, b, t):
    return tuple(x + (y - x) * t for x, y in zip(a, b))


def hue_rgb(h):
    r, g, b = colorsys.hsv_to_rgb(h % 1.0, 1.0, 1.0)
    return (r * 255, g * 255, b * 255)


def finalize(px):
    r, g, b = px
    m = max(r, g, b)
    if m <= 0.5:
        return (0, 0, 0)
    if m > 255:                       # scale instead of clipping: keeps the hue
        s = 255 / m
        r, g, b, m = r * s, g * s, b * s, 255
    if SATURATION != 1.0:
        r = max(0.0, m - (m - r) * SATURATION)
        g = max(0.0, m - (m - g) * SATURATION)
        b = max(0.0, m - (m - b) * SATURATION)
    return (GAMMA_LUT[int(r)], GAMMA_LUT[int(g)], GAMMA_LUT[int(b)])


class Particle:
    __slots__ = ("pos", "dir", "speed", "trail", "strength", "color", "head", "head_gain")

    def __init__(self, direction, speed, trail, strength, color, head=None, head_gain=1.0):
        self.dir = direction
        self.pos = -1.0 if direction > 0 else float(LED_COUNT)
        self.speed, self.trail, self.strength, self.color = speed, trail, strength, color
        self.head, self.head_gain = head, head_gain


class Comet:
    __slots__ = ("pos", "dir")

    def __init__(self, direction):
        self.dir = direction
        self.pos = -1.0 if direction > 0 else float(LED_COUNT)


class Renderer:
    def __init__(self, shared):
        self.shared = shared
        self.parts = []
        self.eased = {}               # (source name, "rx"/"tx") -> [activity, size]
        self.comets = []
        self.sweeps = []              # [start_time, direction]
        self.t = 0.0
        self.last_state = OK

    # ---- spawning ----
    def _spawn(self, act, size, direction, color, gain, dt, head=None):
        if act <= 0 or len(self.parts) >= MAX_PARTICLES_PER_DIR * 2:
            return
        rate = 0.15 + act * (MAX_SPAWN_PER_SEC - 0.15)
        if random.random() < rate * dt:
            mix = SPEED_SIZE_WEIGHT * size + (1 - SPEED_SIZE_WEIGHT) * act
            speed = (SPEED_MIN + (SPEED_MAX - SPEED_MIN) * mix) * \
                random.uniform(1 - SPEED_JITTER, 1 + SPEED_JITTER)
            trail = BASE_TRAIL * (0.6 + 0.9 * mix) * random.uniform(0.9, 1.1)
            strength = (0.65 + 0.35 * act) * random.uniform(0.9, 1.0)
            if head is None:
                strength *= gain
            self.parts.append(Particle(direction, speed, trail, strength, color, head, gain))

    def _handle_events(self, state):
        with self.shared.lock:
            events, self.shared.events = self.shared.events, []
        if state == DOWN:
            return
        for kind in events:
            if kind == "in":
                self.comets.append(Comet(INBOUND_DIR))
            elif kind == "out":
                self.comets.append(Comet(-INBOUND_DIR))
            elif kind == "sweep":
                self.sweeps.append([self.t, INBOUND_DIR])
            elif kind == "shiny":
                self.comets += [Comet(+1), Comet(-1)]
                self.sweeps.append([self.t + 0.8, -INBOUND_DIR])

    # ---- frame ----
    def frame(self, dt):
        self.t += dt
        with self.shared.lock:
            state = self.shared.state

        if RAINBOW_ON_RECOVERY and state == OK and self.last_state in (WARN, CRIT, DOWN):
            self.shared.fire("sweep", f"recovered from {self.last_state}")
        self.last_state = state
        if SHINY_ODDS and state == OK and random.random() < dt / 60 / SHINY_ODDS:
            self.shared.fire("shiny", "shiny!")
        self._handle_events(state)

        if state == DOWN:
            self.parts.clear(); self.comets.clear(); self.sweeps.clear()
            level = 0.15 + 0.85 * (0.5 + 0.5 * math.sin(self.t * 2.0))
            px = finalize(tuple(c * level for c in CRIT_COLOR))
            return [px] * LED_COUNT

        buf = [[0.0, 0.0, 0.0] for _ in range(LED_COUNT)]
        alert = None
        if state in (WARN, CRIT):
            alert = WARN_COLOR if state == WARN else CRIT_COLOR
            speed, lo, hi = (1.2, 0.08, 0.30) if state == WARN else (3.5, 0.10, 0.40)
            level = lo + (hi - lo) * (0.5 + 0.5 * math.sin(self.t * speed))
            for px in buf:
                px[0], px[1], px[2] = (c * level for c in alert)

        ease = 1 - math.exp(-dt / 0.3)
        for src in compute_sources(self.shared):
            for k, direction in (("rx", INBOUND_DIR), ("tx", -INBOUND_DIR)):
                e = self.eased.setdefault((src["name"], k), [0.0, 0.0])
                e[0] += (mbps_to_activity(src[k + "_mbps"]) - e[0]) * ease
                e[1] += (src[k + "_size"] - e[1]) * ease
                self._spawn(e[0], e[1], direction, src[k + "_color"], src["gain"], dt, src.get("head"))

        white = (255, 255, 255)
        alive = []
        tagged_heads = []
        for p in self.parts:
            base = alert or p.color
            head = lerp(base, white, HEAD_WHITENESS)
            p.pos += p.dir * p.speed * dt
            decay = 3.0 / (max(1.0, p.trail) * max(1.0, GAMMA))
            first = 0
            if p.head is not None and not alert:
                tagged_heads.append(p)
                first = 1                 # the head LED is drawn solid afterwards
            for i in range(first, int(p.trail) + 1):
                x = p.pos - p.dir * i
                k = p.strength * math.exp(-i * decay)
                col = head if i == 0 else base
                lo_i = math.floor(x)
                frac = x - lo_i
                for idx, w in ((lo_i, 1 - frac), (lo_i + 1, frac)):
                    if 0 <= idx < LED_COUNT and w > 0:
                        px = buf[idx]
                        px[0] += col[0] * k * w
                        px[1] += col[1] * k * w
                        px[2] += col[2] * k * w
            tail = p.pos - p.dir * p.trail
            if -p.trail - 2 < tail < LED_COUNT + p.trail + 2:
                alive.append(p)
        self.parts = alive

        # service-tagged heads: one solid LED in the service color, drawn on top
        for p in tagged_heads:
            idx = int(round(p.pos))
            if 0 <= idx < LED_COUNT:
                k = min(1.0, p.head_gain)       # heads always full strength so they read as a tag
                buf[idx] = [c * k for c in p.head]

        # rainbow sweeps (whole strip, flowing in a direction)
        live_sweeps = []
        for sw in self.sweeps:
            age = self.t - sw[0]
            if age < 0:
                live_sweeps.append(sw)
                continue
            if age > SWEEP_SECONDS:
                continue
            live_sweeps.append(sw)
            a = 0.9 * clamp01(min(age / 0.7, (SWEEP_SECONDS - age) / 1.2))
            for idx, px in enumerate(buf):
                c = hue_rgb(1.5 * (idx / LED_COUNT - 0.5 * sw[1] * age))
                px[0] = px[0] * (1 - a) + c[0] * a
                px[1] = px[1] * (1 - a) + c[1] * a
                px[2] = px[2] * (1 - a) + c[2] * a
        self.sweeps = live_sweeps

        # rainbow comets
        live_comets = []
        for c in self.comets:
            c.pos += c.dir * RAINBOW_SPEED * dt
            head = c.pos
            tail = head - c.dir * RAINBOW_LENGTH
            for idx in range(max(0, int(min(head, tail))), min(LED_COUNT, int(max(head, tail)) + 2)):
                d = (head - idx) * c.dir          # distance behind the head
                if 0 <= d < RAINBOW_LENGTH:
                    f = d / RAINBOW_LENGTH
                    a = (1 - f) ** 0.6
                    col = hue_rgb(self.t * 0.6 + f * 0.9)
                    px = buf[idx]
                    px[0] = px[0] * (1 - a) + col[0] * a
                    px[1] = px[1] * (1 - a) + col[1] * a
                    px[2] = px[2] * (1 - a) + col[2] * a
            if -RAINBOW_LENGTH - 2 < tail < LED_COUNT + RAINBOW_LENGTH + 2:
                live_comets.append(c)
        self.comets = live_comets

        return [finalize(px) for px in buf]


# ----------------------------------------------------------------------------
# Outputs
# ----------------------------------------------------------------------------
class StripOutput:
    def __init__(self):
        from rpi_ws281x import PixelStrip, ws
        strip_type = getattr(ws, f"WS2811_STRIP_{LED_ORDER}")
        channel = 1 if LED_PIN in (13, 19, 41, 45, 53) else 0
        self.strip = PixelStrip(LED_COUNT, LED_PIN, 800000, 10, False,
                                LED_BRIGHTNESS, channel, strip_type)
        self.strip.begin()

    def show(self, pixels):
        for i, (r, g, b) in enumerate(pixels):
            self.strip.setPixelColorRGB(i, r, g, b)
        self.strip.show()

    def clear(self):
        self.show([(0, 0, 0)] * LED_COUNT)


class TerminalOutput:
    def __init__(self):
        self.width = min(LED_COUNT, 120)
        sys.stdout.write("\x1b[?25l")

    def show(self, pixels):
        step = LED_COUNT / self.width
        row = []
        for i in range(self.width):
            r, g, b = pixels[int(i * step)]
            row.append(f"\x1b[38;2;{r};{g};{b}m\u2588")
        sys.stdout.write("\r" + "".join(row) + "\x1b[0m")
        sys.stdout.flush()

    def clear(self):
        sys.stdout.write("\x1b[0m\x1b[?25h\n")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--simulate", action="store_true", help="preview in the terminal instead of the strip")
    ap.add_argument("--demo", action="store_true", help="fake traffic; cycles alert states and rainbows")
    args = ap.parse_args()

    shared = Shared()
    stop = threading.Event()
    targets = [demo_poller] if args.demo else [traffic_poller, health_poller]
    if QBIT_URL and not args.demo:
        targets.append(qbit_poller)
    for target in targets:
        threading.Thread(target=target, args=(shared, stop), daemon=True).start()
    if TRIGGER_PORT:
        threading.Thread(target=trigger_server, args=(shared,), daemon=True).start()

    out = TerminalOutput() if args.simulate else StripOutput()
    renderer = Renderer(shared)

    def shutdown(*_):
        stop.set()
    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)

    frame_time = 1.0 / FPS
    last = time.monotonic()
    try:
        while not stop.is_set():
            now = time.monotonic()
            dt = min(0.1, now - last)
            last = now
            pixels = renderer.frame(dt)
            shared.frame = pixels
            out.show(pixels)
            sleep = frame_time - (time.monotonic() - now)
            if sleep > 0:
                time.sleep(sleep)
    finally:
        out.clear()


if __name__ == "__main__":
    main()
