#!/usr/bin/env -S python3 -X utf8
# summary: Open, hide, or choose the Music key's app.
"""starchaser music: the Music key opens your music app. Change it in Settings > Software > Default apps > Music key.

    starchaser music [open]         show your music app on its own desktop over the one you're on, or hide it again
                                    (started there the first time)
                                    Leaving out open does the same thing.
    starchaser music list [--json]  the choices, which one is picked (marked *), and which are installed
    starchaser music set <id>       pick one: spotify, strawberry, apple-music, spotify-web, youtube-music, or
                                    desktop:<app id> for another music app installed here (see list)
    starchaser music ask            the first-press question again (which app should the Music key open?)
    starchaser music hide           hide the Music space if it is showing
    starchaser music playpause      play or pause; if no player is open, show how to open your music app
Your choice is saved in ~/.config/starchaser/music.json
"""
# Notes (not shown to people): nothing is picked until you pick (decided 2026-10-11: "ask on first press"). The first
# press asks, with a card offering Spotify, Apple Music and More choices, remembers the answer and opens it. Spotify
# comes installed (spotify-launcher, from Arch's own repos; decided 2026-10-11: "include spotify in the install"): it is
# by far the most installed music app on Linux (Flathub, October 2026: about 6.4 million installs). For music files
# you own, the most installed player is Strawberry (Flathub: about 9,200 installs in the last month). A choice that
# isn't installed yet offers to install it (Settings > Software's own offer; never the community AUR in one step).
# The web choices open through starchaser webapp in a separate, saved browser profile without a keyring prompt.
# Installed site app IDs are only used to recognize windows already running, so the Music key still toggles them.
import fcntl
import json
import os
import re
import select
import shutil
import stat
import subprocess
import sys
import time
from contextlib import contextmanager
from pathlib import Path
from uuid import uuid4

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams
safe_streams()

HOME = Path.home()
CONF = HOME / ".config/starchaser/music.json"
GUARD = HOME / ".local/state/starchaser/music-guard"
PENDING = HOME / ".local/state/starchaser/music-pending"
PENDING_SECONDS = 15 * 60
DEFAULT = ""          # nothing picked: the first press asks
QUESTION = Path(os.environ.get("XDG_RUNTIME_DIR", f"/tmp/starchaser-music-{os.getuid()}")) / "starchaser-music-question.json"
NO_PLAYER = QUESTION.parent / "starchaser-music-no-player.stamp"



def music_key() -> str:
    """The Music key's key in use now (profile and your own changes count), or "" when it has none."""
    try:
        return subprocess.run(["starchaser", "shortcuts", "key", "Apps: Music"], capture_output=True, text=True,
                              timeout=5).stdout.strip()
    except (OSError, subprocess.TimeoutExpired):
        return ""


def why(label: str) -> str:
    """Why an install is being offered: names the key the person pressed (looked up, never written in here, so a
    profile or a changed key reads right), or says "the Music key" when it can't be told."""
    k = music_key()
    return (f"{label} is selected for {k or 'the Music key'} but isn't installed yet. Get it in Settings to start listening, "
            "or pick another music app in Settings > Software > Default apps > Music key.")

# id: label, line (what it is, for Settings), how to find it, how to start it
CHOICES = {
    "spotify": {"label": "Spotify", "kind": "app", "short": "Streaming music and podcasts", "line": "Stream music and podcasts (free with ads, or Premium). The most used music app on Linux.",
                "cmds": ["spotify-launcher", "spotify"], "flatpak": "com.spotify.Client", "catalog": "spotify",
                "classes": ["spotify", "com.spotify.client"]},
    "strawberry": {"label": "Strawberry", "kind": "app", "short": "Plays your own music files", "line": "Plays and organizes the music files you own.",
                   "cmds": ["strawberry"], "flatpak": "org.strawberrymusicplayer.strawberry", "catalog": "strawberry",
                   "classes": ["strawberry", "org.strawberrymusicplayer.strawberry"]},
    "apple-music": {"label": "Apple Music", "kind": "web", "short": "Needs an Apple Music subscription", "line": "music.apple.com in its own window (needs an Apple Music subscription).",
                    "url": "https://music.apple.com", "classes": ["music.apple.com"]},
    "spotify-web": {"label": "Spotify on the web", "kind": "web", "short": "No app needed", "line": "open.spotify.com in its own window: nothing to install.",
                    "url": "https://open.spotify.com", "name": "Spotify", "classes": ["open.spotify.com"]},
    "youtube-music": {"label": "YouTube Music", "kind": "web", "short": "Music videos and playlists", "line": "music.youtube.com in its own window.",
                      "url": "https://music.youtube.com", "classes": ["music.youtube.com"]},
}
ORDER = ["spotify", "strawberry", "apple-music", "spotify-web", "youtube-music"]


BROKEN_KEPT = ""


def keep_broken() -> None:
    """A settings file that can't be read is kept beside the new one (music.json.broken), so nothing is lost."""
    global BROKEN_KEPT
    dest = CONF.with_name(CONF.name + ".broken")
    try:
        dest.write_bytes(CONF.read_bytes())
    except OSError:
        return
    BROKEN_KEPT = dest.name


def conf() -> dict:
    global BROKEN_KEPT
    try:
        c = json.loads(CONF.read_text())
        if isinstance(c, dict):
            return c
    except (OSError, ValueError, RecursionError):
        pass
    if CONF.exists() and not BROKEN_KEPT:
        keep_broken()
        if BROKEN_KEPT:
            print(f"starchaser music: the settings in music.json couldn't be read and were kept as "
                  f"{BROKEN_KEPT}; the settings below start from their defaults.", file=sys.stderr)
    return {}


def current() -> str:
    a = conf().get("app")
    if isinstance(a, str) and a.startswith("desktop:"):
        a = a.removesuffix(".desktop")
    return a if isinstance(a, str) and (a in CHOICES or a.startswith("desktop:")) else DEFAULT


def choice_label(app: str) -> str:
    label = CHOICES.get(app, {}).get("label") or next((o.get("label") for o in other_apps() if o["id"] == app), None)
    if not label and app == current():
        label = conf().get("label")
    return label if isinstance(label, str) and label.strip() else "Your previous music app"


def close_question() -> None:
    """Close the open "Choose a music app" card: its "Right now: ..." line is wrong once the choice changed
    elsewhere. Its waiter sees the missing state, exits quietly and ends its own notify-send."""
    try:
        with QUESTION.with_suffix(".lock").open("a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            old = question_state()
            if not old:
                return
            try:
                args = Path(f"/proc/{int(old['pid'])}/cmdline").read_bytes().split(b"\0")
                live = f"string:x-starchaser-music-question:{old['token']}".encode() in args
            except (OSError, ValueError, TypeError, KeyError):
                live = False
            if live and str(old.get("id", "")).isdigit():
                subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.Notifications",
                                "--object-path", "/org/freedesktop/Notifications",
                                "--method", "org.freedesktop.Notifications.CloseNotification", str(int(old["id"]))],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=False)
            QUESTION.unlink(missing_ok=True)
    except (OSError, subprocess.SubprocessError):
        pass


def set_choice(app: str, from_question: bool = False) -> int:
    supplied_app = app
    if app.startswith("desktop:"):
        app = app.removesuffix(".desktop")
        desktop_id = app.removeprefix("desktop:")
        for choice_id, choice in CHOICES.items():
            if choice["kind"] == "app" and desktop_id in (choice_id, *choice["cmds"], choice["flatpak"]) \
                    and desktop_file_exists(desktop_id):
                app = choice_id
                break
    if app not in CHOICES and not any(o["id"] == app for o in other_apps()):
        print(f"starchaser music: unknown music app '{supplied_app}'; pick an app from 'starchaser music list'. "
              "The current choice stays the same.", file=sys.stderr)
        return 2
    with pending_lock():
        CONF.parent.mkdir(parents=True, exist_ok=True)
        c = conf()
        c["app"] = app
        c["label"] = choice_label(app)
        CONF.write_text(json.dumps(c, indent=1) + "\n")
        PENDING.unlink(missing_ok=True)
    try:
        subprocess.run(["qs", "-p", str(HOME / ".config/quickshell/cockpit"), "ipc", "call", "cockpit", "musicChoiceChanged"],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=False)
    except (OSError, subprocess.SubprocessError):
        pass
    if not from_question:  # the question's own waiter holds the question lock and has already cleared it
        close_question()
    guard_music_space(*chosen_classes(app), sweep=True)
    if sys.stdout.isatty() and not from_question:  # scripts (not a terminal) keep getting the bare id
        label = choice_label(app)
        print(f"The Music key now opens {label}.")
        choice = CHOICES.get(app)
        if choice and choice["kind"] == "app" and not app_command(choice):
            print("It isn't installed yet. Get it in Settings > Software.")
        elif choice and choice["kind"] == "web":
            browser = browser_info()
            if not (browser.get("app") or browser.get("id")):
                print("It needs a web browser. Get one in Settings > Software.")
            elif not browser.get("app"):
                print("It needs a browser that opens it in its own window, such as Brave Origin. Get one in Settings > Software.")
    else:
        print(app)
    return 0


def installed_webapp(c: dict) -> dict | None:
    """A web choice the person installed as an app from their browser (Brave or Chrome: "Install Apple Music"): its
    .desktop entry runs the browser with --app-id=<id> and is named like the choice. {file, id}, or None."""
    names = {c["label"].lower(), c.get("name", c["label"]).lower()}
    wa = webapp_module()
    if not wa:
        return None
    for d in wa.app_dirs():
        for f in sorted(d.glob("*.desktop")):
            e = wa.desktop_entry(f)
            m = re.search(r"--app-id=([a-p]{32})\b", e.get("exec", "")) if e else None
            if m and e.get("name", "").strip().lower() in names and e.get("nodisplay", "").lower() != "true":
                return {"file": str(f), "id": m.group(1)}
    return None


def flatpak_has(app: str) -> bool:
    return any((Path(d) / "app" / app).is_dir() for d in (HOME / ".local/share/flatpak", Path("/var/lib/flatpak")))


def app_command(c: dict) -> list:
    for cmd in c.get("cmds", []):
        if shutil.which(cmd):
            return [cmd]
    if c.get("flatpak") and shutil.which("flatpak") and flatpak_has(c["flatpak"]):
        return ["flatpak", "run", c["flatpak"]]
    return []


def webapp_module():
    """starchaser webapp's helpers (where .desktop entries live, reading one), or None."""
    import importlib.machinery
    import importlib.util
    try:
        loader = importlib.machinery.SourceFileLoader("starchaser_webapp", str(Path(__file__).resolve().parent / "starchaser-webapp"))
        spec = importlib.util.spec_from_loader("starchaser_webapp", loader)
        wa = importlib.util.module_from_spec(spec)
        loader.exec_module(wa)
        return wa
    except (OSError, ImportError, SyntaxError):
        return None


def other_apps() -> list:
    """Music apps installed here that aren't among the choices above: [{id, label, file, classes}]. Web apps installed from a
    browser for one of the web choices (Apple Music) are that choice, not another app."""
    wa = webapp_module()
    if not wa:
        return []
    known = re.compile(r"spotify|strawberry|apple music|youtube music", re.I)
    out, seen = [], set()
    for d in wa.app_dirs():
        for f in sorted(d.glob("*.desktop")):
            e = wa.desktop_entry(f)
            cats = set(e.get("categories", "").split(";"))
            if not e or e.get("type", "Application") != "Application" or not e.get("exec", "").strip() \
                    or e.get("hidden", "").lower() == "true" or e.get("nodisplay", "").lower() == "true" \
                    or e.get("terminal", "").lower() == "true" \
                    or "Audio" not in cats or not ({"Player", "Music"} & cats) or "Video" in cats:
                continue
            if e.get("tryexec") and not shutil.which(e["tryexec"]):
                continue
            if known.search(f.name) or known.search(e.get("name", "")) or f.stem in seen:
                continue
            seen.add(f.stem)
            classes = [e.get("startupwmclass", "").strip(), f.stem]
            line = ""
            for field in ("comment", "genericname"):
                description = " ".join(e.get(field, "").split())
                if description and not re.search(r"\b(?:GNOME|KDE|CachyOS|Caelestia)\b", description, re.I):
                    line = description
                    break
            out.append({"id": "desktop:" + f.stem, "label": e.get("name", f.stem), "file": str(f),
                        "classes": [k.lower() for k in classes if k], "line": line})
    return out


def desktop_file_exists(did: str) -> bool:
    dirs = [Path.home() / ".local/share/applications", Path("/usr/share/applications"), Path("/usr/local/share/applications"),
            Path.home() / ".local/share/flatpak/exports/share/applications", Path("/var/lib/flatpak/exports/share/applications")]
    return any((d / f"{did}.desktop").is_file() for d in dirs)


def browser_info() -> dict:
    """App-window support and browser availability (a plain default browser can still open tabs)."""
    try:
        r = subprocess.run([str(Path(__file__).resolve().parent / "starchaser-webapp"), "browser"], capture_output=True,
                           text=True, timeout=10)
        info = json.loads(r.stdout)
        if not isinstance(info, dict):
            info = {}
    except (OSError, ValueError, subprocess.TimeoutExpired):
        info = {}
    if not info.get("app") and not info.get("id"):
        wa = webapp_module()
        if wa:
            did = wa.default_browser()
            if did and desktop_file_exists(did):          # a browser that was removed does not count
                info["id"] = did
    return info


def plain_app_fields() -> dict:
    """The keys every choice carries: a native app needs no browser and no catalog entry."""
    return {"catalog": "", "needsBrowser": False, "needsAppBrowser": False, "windowed": False}


def listing() -> dict:
    choices = []
    browser = browser_info()
    windowed = bool(browser.get("app"))
    for i in ORDER:
        c = CHOICES[i]
        line = c["line"] if c["kind"] != "web" or windowed else c["line"].replace("in its own window", "in your web browser")
        needs_browser = c["kind"] == "web" and not (windowed or browser.get("id"))
        needs_app_browser = c["kind"] == "web" and not windowed and bool(browser.get("id"))
        if needs_app_browser:
            line = "Needs a browser that opens it in its own window, such as Brave Origin."
        short = c["short"]
        if i == "spotify" and app_command(c) == ["spotify-launcher"]:
            line += " Downloads Spotify on first use."
            short += "; downloads on first use"
        if needs_browser or needs_app_browser:        # "No app needed" beside "Needs a browser ..." reads as if nothing is needed
            line = line.replace(": nothing to install", "")
            short = short.replace("No app needed", "Plays in a browser window")
        choices.append({"id": i, "label": c["label"], "kind": c["kind"], "line": line, "short": short,
                        "installed": windowed if c["kind"] == "web" else bool(app_command(c)), "catalog": c.get("catalog", ""),
                        "needsBrowser": needs_browser, "needsAppBrowser": needs_app_browser, "windowed": windowed})
    for o in other_apps():
        line = o.get("line") or "A music player."
        choices.append({"id": o["id"], "label": o["label"], "kind": "app", "line": line,
                        "short": line, "installed": True, **plain_app_fields()})
    cur = current()
    if cur.startswith("desktop:") and not any(c["id"] == cur for c in choices):
        choices.append({"id": cur, "label": choice_label(cur), "kind": "app", "line": "No longer installed.",
                        "short": "Your previously chosen music app", "installed": False, **plain_app_fields()})
    return {"current": cur, "default": DEFAULT, "choices": choices}


# ---------------------------------------------------------------------------------------------- opening
def hypr(*args: str) -> str:
    try:
        return subprocess.run(["hyprctl", *args], capture_output=True, text=True, timeout=5).stdout
    except (OSError, subprocess.TimeoutExpired):
        return ""


# The music app lives on its own hidden desktop, special:music, which the Music key shows over whatever you're doing
# and hides again (decided 2026-10-11: "it was its own little space that always starts your music app"; bringing the
# app's window forward on its desktop took him away from what he was doing). Not running: it's started there.
SPECIAL = "special:music"


def chosen_classes(app: str) -> tuple[list, bool]:
    """Use the same native app, desktop entry and browser app IDs as the Music key."""
    if app.startswith("desktop:"):
        entry = next((o for o in other_apps() if o["id"] == app), None)
        return (entry["classes"] if entry else []), True
    c = CHOICES.get(app, {})
    classes = list(c.get("classes", []))
    pwa = installed_webapp(c) if c.get("kind") == "web" else None
    if pwa:
        classes.append(pwa["id"])
        remember_webapp(app, pwa["id"])
    elif c.get("kind") == "web":
        # The browser rewrites its app shortcut now and then; a moment when the file can't be read must not drop
        # the installed app from Music (it was pushed out to a regular desktop). Keep the last one seen.
        known = conf().get("webapps", {}).get(app)
        if isinstance(known, str) and re.fullmatch(r"[a-p]{32}", known):
            classes.append(known)
    return classes, c.get("kind") != "web"


def remember_webapp(app: str, app_id: str) -> None:
    c = conf()
    seen = c.get("webapps") if isinstance(c.get("webapps"), dict) else {}
    if seen.get(app) == app_id:
        return
    seen[app] = app_id
    c["webapps"] = seen
    try:
        CONF.parent.mkdir(parents=True, exist_ok=True)
        tmp = CONF.with_name(f".{CONF.name}.{os.getpid()}.tmp")
        tmp.write_text(json.dumps(c, indent=1) + "\n")
        tmp.replace(CONF)
    except OSError:
        pass


def guard_music_space(classes: list, exact: bool, sweep: bool = False) -> None:
    """Only the chosen app belongs here, including when another app opens while Music is showing.
    Refresh one pair of event handlers; a changed choice (sweep) also returns the old app to its regular desktop.
    Nothing else sweeps: a window already in Music stays there even when the list comes up short for a moment.
    Browser processes are shared, so only native apps can bring their own process's dialogs."""
    classes = [k.lower() for k in classes if k and "\n" not in k and "\r" not in k]
    tmp = GUARD.with_name(f".{GUARD.name}.{os.getpid()}.tmp")
    try:
        GUARD.parent.mkdir(parents=True, exist_ok=True)
        with tmp.open("w") as f:
            f.write(("exact" if exact else "contains") + "\n" + "".join(k + "\n" for k in classes))
            f.flush()
            os.fsync(f.fileno())
        tmp.replace(GUARD)
    except OSError as e:
        # Persistence is best-effort; the live guard can still protect the current session.
        print(f"starchaser music: couldn't save the Music space guard: {e}", file=sys.stderr)
    finally:
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass
    # Lua uses decimal byte escapes; JSON's Unicode escapes are not Lua strings.
    needles = "{" + ",".join('"' + "".join(chr(b) if 32 <= b < 127 and b not in (34, 92) else f"\\{b:03d}"
                                          for b in k.encode()) + '"' for k in classes) + "}"
    hypr("eval", "StarchaserMusicGuard.configure(" + needles + "," + ("true" if exact else "false") + ","
         + ("true" if sweep else "false") + ")")


def matches_window(c: dict, classes: list, exact: bool) -> bool:
    window_classes = {s.lower() for s in (c.get("class"), c.get("initialClass")) if s}
    return any((k.lower() == cls) if exact else (k.lower() in cls) for k in classes for cls in window_classes)


def system_prompt(c: dict) -> bool:
    return matches_window(c, ["gcr-prompter", "gnome-keyring", "org.gnome.keyring.promptui", "polkit", "pinentry"], False)


def find_windows(classes: list, exact: bool) -> list:
    """The app's windows ({address, workspace name}). An app's class must match exactly; a web app's only has
    to contain the site's address or its app id."""
    if not classes:
        return []
    try:
        clients = json.loads(hypr("clients", "-j") or "[]")
    except ValueError:
        return []
    windows = []
    for c in clients:
        if matches_window(c, classes, exact):
            a = c.get("address", "")
            if re.fullmatch(r"0x[0-9a-fA-F]+", a):
                windows.append({"address": a, "workspace": (c.get("workspace") or {}).get("name", ""),
                                "class": c.get("class"), "initialClass": c.get("initialClass"), "pid": c.get("pid")})
    return windows


def find_window(classes: list, exact: bool) -> dict | None:
    return next(iter(find_windows(classes, exact)), None)


def space_showing() -> bool:
    """Whether the music desktop is showing on the screen in use."""
    try:
        mons = json.loads(hypr("monitors", "-j") or "[]")
    except ValueError:
        return False
    return any(m.get("focused") and (m.get("specialWorkspace") or {}).get("name") == SPECIAL for m in mons)


def toggle_space() -> None:
    hypr("eval", 'hl.dispatch(hl.dsp.workspace.toggle_special("music"))')


def hide_space() -> int:
    if space_showing():
        toggle_space()
    return 0


def hide_for_settings() -> int:
    """The `hide` command: also tells a waiting first-launch watcher not to show Music again over what you opened."""
    try:
        with pending_lock():
            state = pending_state()
            if state:
                state["quiet"] = True
                tmp = PENDING.with_name(f".{PENDING.name}.{os.getpid()}.tmp")
                tmp.write_text(json.dumps(state))
                tmp.replace(PENDING)
    except OSError:
        pass
    return hide_space()


def to_space(w: dict) -> None:
    """Put the window on the music desktop (minimized, or moved off it, it would leave that desktop empty)."""
    if w["workspace"] != SPECIAL:
        hypr("eval", f'hl.dispatch(hl.dsp.window.move({{ workspace = "{SPECIAL}", follow = false, window = "address:{w["address"]}" }}))')


def music_space(classes: list, exact: bool) -> bool:
    """The Music key with the app running: show its desktop over the one in use, or hide it when it's showing.
    False when no window of the app is open (start it, then adopt())."""
    windows = find_windows(classes, exact)
    if not windows:
        return False
    with pending_lock():                # same lock as the watcher's final show: it cannot re-show what this hides
        try:
            PENDING.unlink(missing_ok=True)     # the person is driving now: a first-launch watcher must not toggle again
        except OSError:
            pass
        moved = [w for w in windows if w["workspace"] != SPECIAL]
        for w in windows:
            to_space(w)
        if moved and space_showing():
            w = moved[0]
            hypr("eval", f'hl.dispatch(hl.dsp.focus({{ window = "address:{w["address"]}" }}))')
            return True                 # it just joined the showing music desktop: leave it shown
        toggle_space()
    return True


def adopt_related(w: dict, seen: set, by_pid: bool = False, classes: list | None = None) -> None:
    """Move the app's other windows too (each one once, so a window you minimize or move stays put). Sharing a process
    counts only for a native app: a browser's process also runs your other windows. System prompts have their own process."""
    try:
        clients = json.loads(hypr("clients", "-j") or "[]")
    except ValueError:
        return
    if classes is None:
        classes = [w["class"]] if w.get("class") else []
    for c in clients:
        same_class = matches_window(c, classes, by_pid)
        same_pid = by_pid and w.get("pid", 0) and w["pid"] == c.get("pid")
        a = c.get("address", "")
        if (same_class or same_pid or system_prompt(c)) and a not in seen and re.fullmatch(r"0x[0-9a-fA-F]+", a):
            seen.add(a)
            to_space({"address": a, "workspace": (c.get("workspace") or {}).get("name", "")})


def prompt_addresses() -> set:
    """Addresses of the system prompts (password, keyring) open right now."""
    try:
        return {c.get("address", "") for c in json.loads(hypr("clients", "-j") or "[]") if system_prompt(c)}
    except ValueError:
        return set()


@contextmanager
def opening_notice(label: str):
    """App launches get a temporary card; notification failures must not stop adoption."""
    nid = ""
    if label:
        try:
            result = subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "audio-x-generic",
                                     "-p", "-t", "30000", "-h", "boolean:transient:true",
                                     f"Opening {label}...", "This can take a moment the first time."],
                                    capture_output=True, text=True, timeout=5, check=False)
            if result.returncode == 0 and result.stdout.strip().isdigit():
                nid = result.stdout.strip()
        except (OSError, subprocess.SubprocessError):
            pass
    try:
        yield
    finally:
        if nid:
            try:
                subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.Notifications",
                                "--object-path", "/org/freedesktop/Notifications",
                                "--method", "org.freedesktop.Notifications.CloseNotification", nid],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=False)
            except (OSError, subprocess.SubprocessError):
                pass


def adopt(classes: list, exact: bool, label: str = "") -> bool:
    """Wait up to 30 seconds for the app, then watch five more seconds for its first-run dialogs. A password prompt
    that was already open before Music started belongs to something else and stays where it is."""
    before = prompt_addresses()
    with opening_notice(label):
        for _ in range(120):
            w = find_window(classes, exact)
            if w:
                to_space(w)
                seen = {w["address"]} | before
                adopt_related(w, seen, exact, classes)
                if not space_showing():
                    toggle_space()
                break
            time.sleep(0.25)
        else:
            return False
    for _ in range(20):
        time.sleep(0.25)
        adopt_related(w, seen, exact, classes)
    return True


def spawn(cmd: list) -> subprocess.Popen | None:
    from starchaser_app_privacy import mediated_command
    try:
        return subprocess.Popen(mediated_command(cmd), start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except OSError:
        return None


@contextmanager
def pending_lock():
    """Serialize replacement, choice changes and the watcher's final move, never its waiting."""
    PENDING.parent.mkdir(parents=True, exist_ok=True)
    with PENDING.with_suffix(".lock").open("a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        yield


def pending_state() -> dict:
    try:
        state = json.loads(PENDING.read_text())
        return state if isinstance(state, dict) else {}
    except (OSError, ValueError, RecursionError):
        return {}


def pending_active(choice: str) -> bool:
    """A live watcher for this choice (a saved file alone could be left over from a closed session or a reboot)."""
    state = pending_state()
    expires, token = state.get("expires", 0), state.get("token")
    if state.get("choice") != choice or not token or not isinstance(expires, (int, float)) or expires <= time.time():
        return False
    try:
        args = Path(f"/proc/{int(state['pid'])}/cmdline").read_bytes().split(b"\0")
        return token.encode() in args
    except (OSError, ValueError, TypeError, KeyError):
        started = state.get("started", 0)          # just spawned: it has not written its pid yet
        return isinstance(started, (int, float)) and 0 <= time.time() - started < 5


def queue_pending(choice: str, classes: list, exact: bool) -> None:
    """Browser setup can outlast adopt(). Leave one detached watcher for this launch."""
    tmp = PENDING.with_name(f".{PENDING.name}.{os.getpid()}.tmp")
    try:
        with pending_lock():
            if current() != choice or pending_active(choice):
                return
            token = uuid4().hex
            state = {"choice": choice, "token": token, "classes": classes, "exact": exact,
                     "started": time.time(), "expires": time.time() + PENDING_SECONDS}
            with tmp.open("w") as f:
                json.dump(state, f)
                f.flush()
                os.fsync(f.fileno())
            tmp.replace(PENDING)
            if not spawn([str(Path(__file__).resolve()), "--adopt-pending", token]):
                PENDING.unlink(missing_ok=True)
    except OSError:
        pass
    finally:
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass


def adopt_pending(token: str) -> int:
    """Watch only this launch for up to 15 minutes; a newer launch or choice cancels it."""
    deadline = time.monotonic() + PENDING_SECONDS
    try:
        while True:
            with pending_lock():
                state = pending_state()
                if state.get("token") != token:
                    return 0
                if current() != state.get("choice") or state.get("expires", 0) <= time.time() \
                        or time.monotonic() >= deadline:
                    PENDING.unlink(missing_ok=True)
                    return 0
                if state.get("pid") != os.getpid():
                    state["pid"] = os.getpid()
                    tmp = PENDING.with_name(f".{PENDING.name}.{os.getpid()}.tmp")
                    tmp.write_text(json.dumps(state))
                    tmp.replace(PENDING)
                classes, exact = state.get("classes"), state.get("exact")
                if not isinstance(classes, list) or not classes or not all(isinstance(k, str) and k for k in classes) \
                        or not isinstance(exact, bool):
                    PENDING.unlink(missing_ok=True)
                    return 0
                w = find_window(classes, exact)
                if w:
                    # Do not let a choice changed during the compositor query move the old app.
                    if pending_state().get("token") != token or current() != state["choice"]:
                        return 0
                    if w["workspace"] != SPECIAL:
                        to_space(w)
                        # Only this app's own windows come along. A password prompt that opened while we waited
                        # belongs to something else (the first-run prompts of the browser app came and went already).
                        adopt_related(w, {w["address"]} | prompt_addresses(), exact, classes)
                    # Show Music even when the window already opened on its desktop (first launch after the
                    # browser setup used to leave it hidden until a second press), unless Hide said otherwise.
                    if not state.get("quiet") and not space_showing():
                        toggle_space()
                    PENDING.unlink(missing_ok=True)
                    return 0
            time.sleep(0.5)
    except OSError:
        return 0


def notify(title: str, body: str) -> None:
    spawn([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "audio-x-generic", title, body])


def playpause() -> int:
    """The media key never starts an app; repeated presses share one notice every ten seconds."""
    try:
        result = subprocess.run(["playerctl", "play-pause"], capture_output=True, text=True, timeout=5)
    except (OSError, subprocess.TimeoutExpired):
        return 1
    said = result.stdout + result.stderr
    if "No player could handle" in said:
        # newer playerctl says this when no player is open, and also when one is open but can't act: only the list tells
        try:
            listed = subprocess.run(["playerctl", "--list-all"], capture_output=True, text=True, timeout=5).stdout.strip()
        except (OSError, subprocess.TimeoutExpired):
            return result.returncode
        if listed:
            return result.returncode
    elif "No players found" not in said:
        return result.returncode      # a player exists (or playerctl failed another way): no "open an app" notice
    try:
        NO_PLAYER.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
        st = NO_PLAYER.parent.lstat()
        if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid() or st.st_mode & 0o022:
            return 1
        with NO_PLAYER.open("a+") as stamp:
            fcntl.flock(stamp, fcntl.LOCK_EX)
            stamp.seek(0)
            try:
                last = float(stamp.read())
            except ValueError:
                last = None
            now = time.monotonic()
            if last is not None and 0 <= now - last < 10:
                return 0
            key = music_key()
            body = f"Press {key} to open your music app." if key else "Set a Music key in Settings > Shortcuts."
            notify("Open a music app first", body)
            stamp.seek(0)
            stamp.truncate()
            stamp.write(str(now))
        return 0
    except OSError:
        return 1


def tell(msg: str) -> None:
    """One line on the terminal when run from one (the key itself answers on the desktop): says why it didn't open."""
    if sys.stderr.isatty():
        print(f"starchaser music: {msg}", file=sys.stderr)


def no_browser(label: str, app_window: bool = False) -> None:
    """A web choice with no browser installed: say so, with a "Get a browser" button that opens the menu's page
    for choosing one (the same page a browser key opens on a computer without one). Waits for the answer in the
    background, so the key press itself returns at once."""
    title = f"Couldn't open {label}"
    body = f"{label} opens in a web browser, and no web browser is installed yet. Get one, then try again."
    toggle = HOME / ".config/keybinds/toggle.sh"
    command = [str(toggle), "browser"]
    action = 'browser="Get a browser"'
    if app_window:
        body = (f"Your browser opens {label} as a tab. The Music key needs its own window to show or hide. "
                "Get a browser that opens it in its own window, such as Brave Origin, then try again.")
        command = ["starchaser", "settings", "app", "brave-origin"]
        action = 'browser="Get Brave Origin"'
    script = ('a=$(/bin/sh -c \'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi\' starchaser notify -a Starchaser -i audio-x-generic -A ' + action + ' '
              '-h string:x-canonical-private-synchronous:starchaser-music-no-browser '
              '-h string:x-starchaser-transient:1 -w "$1" "$2"); '
              'shift 2; [ "$a" = browser ] && exec "$@"')
    if not spawn(["sh", "-c", script, "sh", title, body, *command]):
        notify(title, body)


def open_music() -> int:
    cur = current()
    guard_music_space(*chosen_classes(cur))
    if cur.startswith("desktop:"):
        app = next((o for o in other_apps() if o["id"] == cur), None)
        if app and music_space(app["classes"], exact=True):
            return 0
        if app and spawn(["gio", "launch", app["file"]]):
            if not adopt(app["classes"], exact=True, label=app.get("label") or "your music app"):
                queue_pending(cur, app["classes"], True)
                notify(f"Still waiting for {app.get('label') or 'your music app'}",
                       "Finish any setup that is open. If no window appears, press the Music key to try again.")
            return 0
        notify("Your music app isn't installed", "Pick another one in Settings > Software > Default apps > Music key.")
        tell("your music app isn't installed. Pick another one in Settings > Software > Default apps > Music key.")
        return 1
    if cur == "":
        return ask()
    c = CHOICES[cur]
    pwa = installed_webapp(c) if c["kind"] == "web" else None
    if pwa:
        remember_webapp(cur, pwa["id"])
    elif c["kind"] == "web":
        known = conf().get("webapps", {}).get(cur)
        if isinstance(known, str) and re.fullmatch(r"[a-p]{32}", known) and music_space([known], False):
            guard_music_space(chosen_classes(cur)[0], False)
            return 0                                   # the installed app is already in Music: just show it
    # an installed web app's window is named after its app id ("brave-<id>-Default", "crx_<id>")
    if pwa:
        if music_space([pwa["id"]], False):
            guard_music_space([pwa["id"]], False)
            return 0
    classes = c.get("classes", [])
    if music_space(classes, c["kind"] == "app"):
        return 0
    if c["kind"] == "web":
        browser = browser_info() if not pwa else {"app": True}
        if browser.get("id") and not browser.get("app"):
            no_browser(c["label"], app_window=True)
            tell(f"{c['label']} needs a browser that opens it in its own window, such as Brave Origin.")
            return 1
        try:
            ok = subprocess.run([str(Path(__file__).resolve().parent / "starchaser-webapp"), c["url"], "--name",
                                 c.get("name", c["label"]), "--private"], timeout=15).returncode == 0
        except (OSError, subprocess.TimeoutExpired):
            ok = False
        if not ok:
            no_browser(c["label"])
            tell(f"couldn't open {c['label']} (no web browser is installed).")
        else:
            if not adopt(classes, False, label=c["label"]):
                queue_pending(cur, classes, False)
                notify(f"Still waiting for {c['label']}",
                       "Finish any browser setup that is open. If no window appears, press the Music key to try again.")
        return 0 if ok else 1
    cmd = app_command(c)
    if cmd:
        process = spawn(cmd)
        if process:
            if adopt(classes, True, label=c["label"]):
                return 0
            # A launcher can hand off successfully and exit 0. A failed launch with no window cannot
            # be waiting for setup: report it instead of leaving a watcher and a misleading notice.
            if process.poll() in (None, 0):
                queue_pending(cur, classes, True)
                notify(f"Still waiting for {c['label']}",
                       "Finish any setup that is open. If no window appears, press the Music key to try again.")
                return 0
        # installed but it wouldn't start: said on the desktop too (this used to fail without a word)
        notify(f"Couldn't start {c['label']}", "Try again, or pick another music app in Settings > Software > Default apps > Music key.")
        tell(f"couldn't start {c['label']}.")
        return 1
    # not installed yet: Software's own "Install …?" (with a plain note instead when it already asked today)
    if not spawn(["starchaser", "software", "offer", "--remind", c["catalog"], why(c["label"])]):
        notify(f"{c['label']} isn't installed yet", "You can install it from Settings > Software.")
    tell(f"{c['label']} isn't installed yet. You can install it from Settings > Software.")
    return 1


def notifications_available() -> bool:
    """Check the service before detaching the question, whose errors cannot reach the caller."""
    try:
        return subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.Notifications",
                               "--object-path", "/org/freedesktop/Notifications",
                               "--method", "org.freedesktop.Notifications.GetServerInformation"],
                              stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5).returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def ask() -> int:
    """The first press, before anything is picked: a card asks which app the Music key should open. The answer is
    remembered and that app opens; More choices opens Settings > Software > Default apps > Music key. Waits for the answer in
    the background, so the key press itself returns at once."""
    if not notifications_available():
        print("starchaser music: couldn't show the music question because notifications are unavailable. "
              "Pick an app in Settings > Software > Default apps > Music key.", file=sys.stderr)
        return 1
    cur = current()
    title = "Choose a music app"
    # profile-independent words: this card can wait in the bell across a profile switch, so it never names the key
    question = "Which music app would you like to open?"
    label = ""
    if cur:
        label = choice_label(cur)
    note = (f"Right now: {label}. Your choice stays until you pick another." if cur
            else "Change it later in Settings > Software > Default apps > Music key.")
    # say what each app needs before it is picked: Spotify may need installing, Apple Music needs a browser and a subscription
    spotify = app_command(CHOICES["spotify"])
    sp = ("; a free account is needed" + (" (downloads on first use)" if spotify == ["spotify-launcher"] else "")
          if spotify else "; needs installing")
    bi = browser_info()
    am = "" if bi.get("app") else " and a browser that opens it in its own window"        # a plain browser can't open it on its own desktop
    # one line per button, in the buttons' order; the note about changing it later closes the card
    body = (f"{question}\nSpotify streams music{sp}.\nApple Music needs a subscription{am}.\n"
            f"More choices opens Settings for streaming or your music files. {note}")
    if not spawn([sys.executable, str(Path(__file__).resolve()), "--question", title, body]):
        notify(title, question + " Pick one in Settings > Software > Default apps > Music key.")
        print("starchaser music: couldn't start the music question. "
              "Pick an app in Settings > Software > Default apps > Music key.", file=sys.stderr)
        return 1
    tell((f"your music app is {label}; it stays until you pick another" if cur else "no music app is picked yet")
         + ": answer the card on your screen, or run 'starchaser music set <id>'.")
    return 0


def question_state() -> dict:
    try:
        state = json.loads(QUESTION.read_text())
        return state if isinstance(state, dict) else {}
    except (OSError, ValueError, RecursionError):
        return {}


def question_wait(title: str, body: str) -> int:
    """Replace the session's question under one lock; only its newest waiter can act on an answer.
    Stale waiters notice the new token and terminate their own notify-send, never somebody else's process."""
    QUESTION.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    # The /tmp fallback is shared: only use a real directory this user owns and nobody else can write to.
    st = QUESTION.parent.lstat()
    if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid() or st.st_mode & 0o022:
        return 1
    token = uuid4().hex
    proc = None
    with QUESTION.with_suffix(".lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX)
            old = question_state()
            cmd = ["stdbuf", "-oL", *['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "audio-x-generic", "-t", "0", "-p", "-w",
                   "-h", f"string:x-starchaser-music-question:{token}", "-h", "string:x-starchaser-transient:1",
                   "-A", "spotify=Spotify",
                   "-A", "apple-music=Apple Music", "-A", "more=More choices"]
            # A crashed waiter must not let a saved id replace an unrelated notification later.
            try:
                args = Path(f"/proc/{int(old['pid'])}/cmdline").read_bytes().split(b"\0")
                live = f"string:x-starchaser-music-question:{old['token']}".encode() in args
            except (OSError, ValueError, TypeError, KeyError):
                live = False
            # The earlier question is closed and a new one posted, so it pops up again: replacing it in place (-r)
            # with the same words changed nothing, and once it had folded into the bell a second press showed
            # nothing at all (QA r64). Transient: closed by us, it leaves the bell's list too (cockpit/Notifs.qml).
            if live and str(old.get("id", "")).isdigit():
                subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.Notifications",
                                "--object-path", "/org/freedesktop/Notifications",
                                "--method", "org.freedesktop.Notifications.CloseNotification", str(int(old["id"]))],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=False)
            proc = subprocess.Popen(cmd + [title, body], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
            if not select.select([proc.stdout], [], [], 5)[0]:
                return 1
            nid = proc.stdout.readline().strip()
            if not nid.isdigit():
                return 1
            QUESTION.write_text(json.dumps({"id": int(nid), "pid": proc.pid, "token": token}))
            fcntl.flock(lock, fcntl.LOCK_UN)
            while True:
                try:
                    proc.wait(timeout=0.2)
                    finished = True
                except subprocess.TimeoutExpired:
                    finished = False
                fcntl.flock(lock, fcntl.LOCK_EX)
                if question_state().get("token") != token:
                    return 0
                if finished:
                    answer = proc.stdout.read().strip()
                    QUESTION.unlink(missing_ok=True)
                    # Keep the lock through saving/opening, so an older answer cannot follow a newer question.
                    if answer in ("spotify", "apple-music") and set_choice(answer, from_question=True) == 0:
                        return open_music()
                    if answer == "more":
                        hide_space()
                        spawn(["starchaser", "settings", "music"])
                    return 0
                fcntl.flock(lock, fcntl.LOCK_UN)
        except OSError:
            notify(title, "Pick one in Settings > Software > Default apps > Music key.")
            return 1
        finally:
            if proc:
                if proc.poll() is None:
                    proc.terminate()
                    try:
                        proc.wait(timeout=2)
                    except subprocess.TimeoutExpired:
                        proc.kill()
                        proc.wait()
                proc.stdout.close()


def main(a: list) -> int:
    cmd = a[0] if a else "open"
    if cmd in ("list", "set") and any(x in ("-h", "--help") for x in a[1:]):   # help after a command word (r172);
        print(__doc__.strip())                            # open/ask/hide/playpause take nothing and say so (choice test)
        return 0
    if not a or a == ["open"]:
        return open_music()
    elif a == ["ask"]:
        return ask()
    elif a == ["playpause"]:
        return playpause()
    elif a == ["hide"]:
        return hide_for_settings()
    elif cmd == "--adopt-pending" and len(a) == 2:
        return adopt_pending(a[1])
    elif cmd == "--question" and len(a) == 3:
        return question_wait(a[1], a[2])
    elif a in (["list"], ["list", "--json"]):
        d = listing()
        if "--json" in a:
            print(json.dumps(d))
        else:
            id_width = max(16, max((len(c["id"]) for c in d["choices"]), default=0))
            for c in d["choices"]:
                mark = "*" if c["id"] == d["current"] else " "
                # the short description says "downloads on first use" only for the launcher-installed app (listing),
                # so the row can be honest about it the way Settings already is
                downloads = "downloads on first use" in c.get("short", "")
                print(f"{mark} {c['id']:<{id_width}} {c['label']}"
                      + ("  (needs a browser)" if c.get("needsBrowser") else "  (downloads on first use)" if downloads
                         else "" if c["installed"] else "  (not installed)"))
            if any(c.get("needsBrowser") for c in d["choices"]):
                print("\nChoices marked (needs a browser) need one first: get one in Settings > Software.")
            if d["current"]:
                print("\n* = the one the Music key opens")
            else:
                print("\nNo app is picked yet. The Music key asks which one to use the first time it is pressed.")
    elif cmd == "set" and len(a) == 2 and a[1] in ("-h", "--help"):   # help after set is help, never a music app id
        print(__doc__.strip())
    elif cmd == "set" and len(a) == 2:
        return set_choice(a[1])
    elif len(a) == 1 and cmd in ("-h", "--help", "help"):
        print(__doc__.strip())
    else:
        # a known command with the wrong words after it says what it needs, not "unknown"
        if cmd == "set":
            print("starchaser music: set needs exactly one choice, for example: starchaser music set spotify "
                  "(starchaser music list shows them)", file=sys.stderr)
        elif cmd == "list":
            print(f"starchaser music: list takes only --json, not '{' '.join(a[1:])}'", file=sys.stderr)
        elif cmd in ("open", "ask", "hide", "playpause"):
            print(f"starchaser music: {cmd} takes nothing after it; use 'starchaser music --help' for help", file=sys.stderr)
        elif cmd in ("-h", "--help", "help"):
            print(f"starchaser music: {cmd} takes nothing after it", file=sys.stderr)
        else:
            print(f"starchaser music: unknown option or command '{' '.join(a)}'", file=sys.stderr)
        print("Usage: starchaser music [open | ask | hide | playpause | list [--json] | set <id> | --help]", file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except PermissionError as error:       # a settings folder it may not write: say so, not a traceback
        sys.exit(f"starchaser music: couldn't save your settings ({error.strerror}). "
                 "Check that you can write to ~/.config.")
