"""Pure-logic tests for the launcher registry (no processes spawned)."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import launchers as L


def test_registry_keys():
    assert {l["key"] for l in L.LAUNCHERS} == {"pulsar", "ardour", "qjackctl", "midimon"}
    assert {w["key"] for w in L.WEB} == {"foundry", "armada"}
    assert set(L.BY_KEY) >= {"pulsar", "ardour", "qjackctl", "midimon", "foundry", "armada"}


def test_which_first():
    assert L.which_first(["definitely-not-a-binary-xyz"]) is None
    assert L.which_first(["definitely-not-xyz", "python3"]).endswith("python3")


def test_snapshot_shape():
    s = L.snapshot()
    assert set(s) == {"web", "apps"}
    for it in s["apps"]:
        assert {"key", "name", "blurb", "kind", "available", "running", "terminal"} <= set(it)
        assert it["kind"] == "app"
    for it in s["web"]:
        assert it["kind"] == "web" and it["url"].startswith("http")


def test_launch_unknown():
    r = L.launch("nope")
    assert r["ok"] is False and r["status"] == "unknown"


def test_port_open_false_on_dead_port():
    assert L._port_open(59999) is False  # nothing should be listening here


def test_web_launch_already_running_opens(monkeypatch):
    # pretend the port is up → must NOT spawn, just report the url to open
    monkeypatch.setattr(L, "_port_open", lambda *a, **k: True)
    r = L.launch("foundry")
    assert r["ok"] is True and r["status"] == "already-running"
    assert r["url"].endswith(":8765/")
