main
Colby Knox 0.2.99: dashboard picks a Windows machine only on a click, Works here section with a Linux Altium 365 bridge (#33) 687f09e
"""Which Windows machine the Altium dashboard drives (altium-bridge#33).

Altium Designer runs only on Windows. The dashboard used to drive the first machine Adom Bridge listed, and from a
Linux computer that started Altium on someone else's laptop without a click. The rule now:

- a machine the user picked (by clicking it on the dashboard) is remembered and used;
- otherwise the computer the dashboard runs on, when it is a Windows PC (the user is sitting at it);
- otherwise nothing: the dashboard shows a picker and calls no Altium verb anywhere until the user clicks one.

Nothing here ever picks a machine on the user's behalf.
"""
import json
import os
import subprocess
import time
from pathlib import Path

ADD_WINDOWS_URL = "https://wiki.adom.inc/adom/adom-bridge"
PICKER_TEXT = "Altium Designer runs on Windows. Run it on one of your Windows machines:"
NO_WINDOWS_TEXT = "Altium Designer needs a Windows computer with Adom Bridge. Here's how to add one."

_cache = {"t": 0.0, "rows": None, "local": None}


def _state_dir() -> Path:
    base = os.environ.get("XDG_STATE_HOME") or os.path.join(os.path.expanduser("~"), ".local", "state")
    return Path(base) / "altium-dashboard"


def pick_file() -> Path:
    return _state_dir() / "machine.json"


def _run_json(args, timeout=30):
    try:
        p = subprocess.run(["adom-bridge", *args], capture_output=True, text=True, timeout=timeout)
        return json.loads(p.stdout or "{}")
    except Exception:
        return {}


def rows_from_targets(d) -> list:
    """`adom-bridge targets` rows as {name, hostname, os, reachable}. Pure."""
    out = []
    for t in (d.get("targets") or []):
        if not t.get("name"):
            continue
        out.append({"name": t["name"], "hostname": t.get("hostname") or t["name"], "os": t.get("os"),
                    "reachable": bool(t.get("reachable"))})
    return out


def machines(max_age=10.0):
    """Every machine on the account, and the hostname of the computer this dashboard talks to (its local ab)."""
    if _cache["rows"] is not None and time.time() - _cache["t"] < max_age:
        return _cache["rows"], _cache["local"]
    rows = rows_from_targets(_run_json(["targets"]))
    local = _run_json(["status"], timeout=15).get("hostname") or None
    _cache.update(t=time.time(), rows=rows, local=local)
    return rows, local


def local_os(rows, local_host):
    """The OS of the computer the dashboard runs beside. ADOM_ALTIUM_DASHBOARD_LOCAL_OS overrides it, so the Linux
    behaviour can be tested from a Windows PC. Pure apart from that variable."""
    forced = os.environ.get("ADOM_ALTIUM_DASHBOARD_LOCAL_OS")
    if forced:
        return forced.strip().lower()
    if not local_host:
        return None
    for r in rows:
        if r["hostname"].lower() == local_host.lower() or r["name"].lower() == local_host.lower():
            return (r.get("os") or "").lower() or None
    return None


def windows_machines(rows):
    return [r for r in rows if (r.get("os") or "").lower() == "windows" and r.get("reachable")]


def picked():
    try:
        return json.loads(pick_file().read_text(encoding="utf-8")).get("name") or None
    except Exception:
        return None


def remember(name):
    """Only ever called for a machine the user clicked."""
    d = _state_dir()
    d.mkdir(parents=True, exist_ok=True)
    pick_file().write_text(json.dumps({"name": name, "pickedAt": time.strftime("%Y-%m-%dT%H:%M:%S")}), encoding="utf-8")


def choose(requested, rows, local_host, remembered):
    """(machine or None, why). Pure: the whole rule lives here.

    requested  a machine named explicitly (a pill the user clicked, or `--target` from the CLI)
    remembered the machine the user last clicked on the dashboard
    """
    wins = {r["name"].lower(): r["name"] for r in windows_machines(rows)}
    listed = {r["name"].lower(): r["name"] for r in rows}
    if requested and requested != "-":
        name = listed.get(requested.lower())
        return (name, "named") if name else (None, "not_listed")
    if remembered and remembered.lower() in wins:
        return wins[remembered.lower()], "picked"
    if local_os(rows, local_host) == "windows":
        for r in rows:
            if local_host and (r["hostname"].lower() == local_host.lower() or r["name"].lower() == local_host.lower()):
                return r["name"], "this_computer"
    return None, "no_machine_picked"


def resolve(requested=None):
    rows, local = machines()
    return choose(requested, rows, local, picked())


def picker_payload(rows, local_host):
    """What the dashboard shows when no machine is chosen. Pure."""
    wins = windows_machines(rows)
    return {
        "needsMachine": True,
        "localOs": local_os(rows, local_host),
        "message": PICKER_TEXT if wins else NO_WINDOWS_TEXT,
        "windowsMachines": [{"name": r["name"], "label": f"Launch on {r['name']}"} for r in wins],
        "noWindowsMachine": not wins,
        "addWindowsUrl": ADD_WINDOWS_URL,
        "_hint": ("Nothing runs until the user clicks a machine: POST /api/pick {name, launch:true}. "
                  "Never pick one for them." if wins else
                  "No Windows machine with Adom Bridge is on this account. Point the user at addWindowsUrl; "
                  "do not call altium_* verbs, they cannot succeed."),
    }