#!/usr/bin/env python3
# summary: Turn Game mode on or off.
"""starchaser game: Game mode. One switch that gets the computer out of a game's way, and puts everything back after.

    starchaser game on [--auto]      turn it on (--auto: a game started; a game ending turns off only an --auto on)
    starchaser game off [--auto]     put everything back the way it was
    starchaser game toggle
    starchaser game status           JSON: on, auto, what it changed, what this computer can do
    starchaser game set <key> <value>   a choice (keys below), saved in ~/.config/starchaser/game.json
    starchaser game game-started | game-ended   internal: the cockpit saw a game window open / the last one close
    starchaser game session-start   internal: a new desktop session (hyprland.lua) ends a Game mode left from the last

What it does while on (each one can be switched off in Settings > Game mode):
    performance  power mode Performance
    dnd          Do not disturb: no notification popups (critical ones still show)
    awake        the screens stay on: no screensaver, screen-off, lock or sleep timer (the cockpit's idle inhibitor)
    effects      no blur, shadows or animations
    vrr          variable refresh rate for full-screen windows (Hyprland misc:vrr = 2)
    scheduler    give games priority when sharing processor time, when this computer supports it;
                 switching it needs no password
    hdr          not a Game mode switch: each screen chooses in Settings > Displays (Off / On / Only in Game mode,
                 kept in ~/.config/starchaser/displays.json). Game mode turns HDR (10-bit, cm = "hdr") on for the
                 "Only in Game mode" screens and back off after; each keeps its mode/position/scale/turn
    stream       make sure Sunshine is running, so Moonlight on another device can pick the game up (off by default)
    auto         turn on by itself when a game starts (a Steam game's window, gamescope, or GameMode), off when it ends

The tools for power modes and game performance come from the official repos (software sources).
What was in place before is saved and restored on off. A log out ends Game mode: the effects, VRR, HDR and Keep
awake end with the session, and the next session's start (session-start) puts back what outlives it (power mode, Do
not disturb, the scheduler) and clears the record, so nothing says "on" for a Game mode that is half gone. (A
restart of the computer clears the record too, but the power mode and Do not disturb remain.)
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path

CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
PREFS = CONFIG / "starchaser/game.json"
NOTIFS = CONFIG / "starchaser/notifications.json"
RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
STATE = RUNTIME / "starchaser-game.json"
DEFAULTS = {"performance": True, "dnd": True, "awake": True, "effects": True, "vrr": True, "scheduler": True,
            "stream": False, "auto": True}
DISPLAYS = CONFIG / "starchaser/displays.json"
COCKPIT = ["qs", "-p", str(Path.home() / ".config/quickshell/cockpit"), "ipc", "call", "cockpit"]
EFFECTS = {"decoration:blur:enabled": "decoration = { blur = { enabled = %s } }",
           "decoration:shadow:enabled": "decoration = { shadow = { enabled = %s } }",
           "animations:enabled": "animations = { enabled = %s }"}


def run(*cmd, env=None) -> str:
    if not shutil.which(cmd[0]):
        return ""
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=15, env=env).stdout.strip()
    except subprocess.TimeoutExpired:
        return ""


def scx(*args: str) -> tuple[int, str]:
    """Run scxctl. A switch that hangs or a missing binary is an answer too (code -1 and why), never an exception:
    one escaping turn_on left Game mode's other changes made with nothing recorded to undo them."""
    try:
        r = subprocess.run(["scxctl", *args], capture_output=True, text=True, timeout=20)
    except subprocess.TimeoutExpired:
        return -1, "the processor scheduler didn't answer in time"
    except OSError:
        return -1, "the processor scheduler isn't available"
    return r.returncode, (r.stderr or r.stdout).strip()


def hypr_env() -> dict:
    env = dict(os.environ)
    if not env.get("HYPRLAND_INSTANCE_SIGNATURE"):
        live = sorted((RUNTIME / "hypr").glob("*/.socket.sock"), key=lambda p: p.stat().st_mtime) if (RUNTIME / "hypr").is_dir() else []
        if live:
            env["HYPRLAND_INSTANCE_SIGNATURE"] = live[-1].parent.name
    return env


def hypr_get(opt: str) -> int | None:
    out = run("hyprctl", "getoption", opt, "-j", env=hypr_env())
    try:
        d = json.loads(out)
        return int(d["bool"] if "bool" in d else d["int"])     # true/false options report "bool", numbers "int"
    except (ValueError, KeyError, TypeError):
        return None


def hypr_set(lua: str) -> None:
    run("hyprctl", "eval", f"hl.config({{ {lua} }})", env=hypr_env())


def cm_enabled(on: bool) -> None:
    """Hyprland color management is off unless HDR is in use (config/hypr/hyprland.lua says why: it washes out
    Moonlight streams). Only the HDR steps of Game mode need it on."""
    hypr_set(f"render = {{ cm_enabled = {'true' if on else 'false'} }}")


def load_json(p: Path) -> dict:
    try:
        value = json.loads(p.read_text())
    except (OSError, ValueError, RecursionError):
        return {}
    return value if isinstance(value, dict) else {}


def hdr_map() -> dict:
    """The per-screen HDR map in displays.json: a damaged shape reads as none saved (as in starchaser displays)."""
    h = load_json(DISPLAYS).get("hdr")
    return h if isinstance(h, dict) else {}


def write_json(p: Path, d: dict) -> None:
    # a temporary file of its own in the same folder, then one rename: a fixed "<name>.tmp" was shared by every
    # writer of that file (Settings, the cockpit, the menu), so two at once could swap in each other's half-written
    # copy, and a reader never sees a half-written file either way
    p.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=p.parent, prefix="." + p.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "w") as f:
            f.write(json.dumps(d, indent=2) + "\n")
        mask = os.umask(0)
        os.umask(mask)
        os.chmod(tmp, 0o666 & ~mask)        # mkstemp makes it 0600: keep what a plain write would have given
        os.replace(tmp, p)
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


def prefs() -> dict:
    return {**DEFAULTS, **load_json(PREFS)}


def can_schedule() -> bool:
    return Path("/sys/kernel/sched_ext/state").exists() and bool(shutil.which("scxctl"))


def can_perform() -> bool:
    """power-profiles-daemon offers a Performance profile here. Many computers (VMs, some laptops) only have
    power-saver and balanced: setting "performance" there fails, and saving the old profile would be for nothing."""
    out = run("powerprofilesctl", "list")
    return any(l.strip().lstrip("* ").rstrip(":") == "performance" for l in out.splitlines() if l.strip().endswith(":"))


def scheduler_now() -> str | None:
    """'' when none runs, else '<scheduler> <mode>', e.g. 'lavd gaming' (`scxctl get`: "running Lavd in Gaming mode").
    None when scxctl didn't answer within 5 s: a hanging scheduler service would otherwise hold Game mode for 15 s
    here and 20 s more on the switch that follows (35 s before anything showed)."""
    try:
        out = subprocess.run(["scxctl", "get"], capture_output=True, text=True, timeout=5).stdout
    except subprocess.TimeoutExpired:
        return None
    except OSError:
        return ""
    m = re.match(r"running (\w+) in (\w+) mode", out.strip())
    return f"{m[1].lower()} {m[2].lower()}" if m else ""


def edid_hdr(edid: bytes) -> bool:
    """A CTA-861 extension with an HDR static metadata block (extended tag 6) that lists PQ or HLG."""
    for i in range(128, len(edid), 128):
        b = edid[i:i + 128]
        if len(b) < 4 or b[0] != 0x02:
            continue
        p = 4
        while p < b[2] and p < len(b):
            tag, ln = b[p] >> 5, b[p] & 31
            if tag == 7 and ln >= 2 and p + 2 < len(b) and b[p + 1] == 6:
                return bool(b[p + 2] & 0b1100)
            p += ln + 1
    return False


def screens() -> list:
    """Hyprland's monitors, each with whether it can do HDR (from its EDID)."""
    try:
        mons = json.loads(run("hyprctl", "monitors", "-j", env=hypr_env()) or "[]")
    except ValueError:
        return []
    for m in mons:
        # sysfs reports a size of 0 for edid even when it holds data: read it
        m["hdrCapable"] = any(edid_hdr(f.read_bytes()) for f in Path("/sys/class/drm").glob(f"card*-{m['name']}/edid"))
    return mons


def bits(m: dict) -> int:
    return 10 if "2101010" in (m.get("currentFormat") or "") else 8


def monitor_rule(m: dict, cm: str, depth: int) -> str:
    """The monitor exactly as it is (mode, position, scale, turn), with a color mode and bit depth."""
    rule = (f'output = "{m["name"]}", mode = "{m["width"]}x{m["height"]}@{m["refreshRate"]:.2f}", '
            f'position = "{m["x"]}x{m["y"]}", scale = {m["scale"]:g}, transform = {int(m.get("transform", 0))}, '
            f'cm = "{cm}", bitdepth = {depth}')
    return f"hl.monitor({{ {rule} }})"


def cockpit(fn: str, *args: str) -> str:
    return run(*COCKPIT, fn, *args, env=hypr_env())


def notify(title: str, body: str, choose_power: bool = False) -> None:
    # Identify Game mode feedback so it can appear beside Quick settings when Do not disturb is off.
    cmd = [*['/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", "input-gaming", "-h", "string:x-starchaser-game:1",
           "-t", "10000" if choose_power else "3000"]
    if choose_power:
        # Wait for the button separately so turning Game mode on never waits for an answer.
        subprocess.Popen(["sh", "-c", '[ "$("$@")" = power ] && exec starchaser settings power',
                          "starchaser-game-notice", *cmd, "-A", "power=Choose power mode", title, body],
                         start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    else:
        run(*cmd, title, body)


LAUNCHERS = ("lutris", "heroic", "bottles", "itch")
LAUNCHER_FLATPAKS = ("net.lutris.Lutris", "com.heroicgameslauncher.hgl", "com.usebottles.bottles", "io.itch.itch")


def other_launcher() -> bool:
    """Another game launcher is installed: whoever plays through it doesn't need to be offered Steam."""
    if any(shutil.which(x) for x in LAUNCHERS):
        return True
    have = run("flatpak", "list", "--app", "--columns=application")
    return any(f in have.split() for f in LAUNCHER_FLATPAKS)


def turn_on(auto: bool) -> None:
    st = load_json(STATE)
    if st.get("on"):
        if not auto and st.get("auto"):           # you turned it on yourself while a game had: now it's yours
            st["auto"] = False
            write_json(STATE, st)
        return
    p, saved, changed = prefs(), {}, {}
    # on at once, before the steps (the scheduler alone can take 20 s): Settings > Game mode asks for the status every
    # 4 s, and a status read meanwhile said off, so its switch flipped back to Off while Game mode was coming on.
    # "busy" marks a record whose steps are still running (filled in below).
    write_json(STATE, {"on": True, "auto": auto, "saved": {}, "busy": "on"})
    # What was changed is recorded even if a step fails or throws partway, so off can always put it back
    try:
        if p["performance"] and can_perform():
            saved["profile"] = run("powerprofilesctl", "get")
            run("powerprofilesctl", "set", "performance")
            changed["profile"] = bool(saved["profile"]) and saved["profile"] != "performance" and run("powerprofilesctl", "get") == "performance"
        if p["dnd"]:
            n = load_json(NOTIFS)
            saved["dnd"] = bool(n.get("dnd"))
            if not n.get("dnd"):
                write_json(NOTIFS, {**n, "dnd": True})
                changed["dnd"] = True
        if p["awake"]:
            saved["awake"] = cockpit("keepAwake") == "true"
            if not saved["awake"]:
                cockpit("toggleKeepAwake")
                changed["awake"] = cockpit("keepAwake") == "true"
        if p["effects"]:
            saved["effects"] = {}
            for opt, lua in EFFECTS.items():
                v = hypr_get(opt)
                if v is not None:
                    saved["effects"][opt] = v
                    hypr_set(lua % "false")
        if p["vrr"]:
            v = hypr_get("misc:vrr")
            if v is not None:
                saved["vrr"] = v
                hypr_set("misc = { vrr = 2 }")
        if p["scheduler"] and can_schedule():
            now_running = scheduler_now()
            if now_running is None:                 # it didn't answer: a switch would only hang as well
                saved["schedulerError"] = "the processor scheduler didn't answer in time"
            else:
                saved["scheduler"] = now_running
                verb = "switch" if now_running else "start"
                rc, out = scx(verb, "--sched", "lavd", "--mode", "gaming")
                if rc != 0:
                    saved.pop("scheduler")
                    # never scxctl's raw error dump in the status JSON (GamePage says this plainly and scripts
                    # read this field): scx's own answers (a hang, a missing program) are already sentences
                    saved["schedulerError"] = out if rc < 0 else "the processor scheduler didn't switch"
        game_hdr = {d for d, v in hdr_map().items() if v == "game"}
        if game_hdr:
            saved["hdr"] = {}
            cm_enabled(True)
            for m in screens():
                if m["hdrCapable"] and m.get("description") in game_hdr and m.get("colorManagementPreset") != "hdr":
                    saved["hdr"][m["name"]] = {"cm": m.get("colorManagementPreset") or "srgb", "bits": bits(m)}
                    run("hyprctl", "eval", monitor_rule(m, "hdr", 10), env=hypr_env())
        if p["stream"]:
            if not run("pgrep", "-x", "sunshine"):
                saved["startedSunshine"] = True
                run("hyprctl", "dispatch", 'hl.dsp.exec_cmd("sunshine")', env=hypr_env())
            notify("Ready to stream", f"Open Moonlight on another device and pick {os.uname().nodename}.")
    finally:
        write_json(STATE, {"on": True, "auto": auto, "saved": saved, "changed": changed})
    cockpit("game", "true")
    # Briefly summarize confirmed changes; the Quick settings tiles keep their attribution hints.
    # Keep warnings actionable without listing every enabled option.
    profile = run("powerprofilesctl", "get")
    changes = [text for key, text in (("dnd", "notifications paused"), ("awake", "screens kept on"),
                                     ("profile", "power mode set to Performance")) if changed.get(key)]
    body = "; ".join(changes)
    body = body[0].upper() + body[1:] + "." if body else "Choose what it changes in Settings > Game mode."
    if auto:
        body = "A game started. " + body
    if saved.get("schedulerError"):
        body += " Games couldn't be given priority on the processor. Check Settings > Game mode."
    if profile == "power-saver":
        body += " Power saver is still on and can limit game performance. Choose a power mode in Settings > Power."
    notify("Game mode on", body, choose_power=profile == "power-saver")
    # Keep the Steam offer after the confirmation; starchaser software limits it to once a day.
    if not auto and not shutil.which("steam") and not other_launcher() and not run("flatpak", "info", "com.valvesoftware.Steam"):
        subprocess.Popen(["starchaser", "software", "offer", "steam", "Game mode works without Steam. Optional: get games with Steam."],
                         start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def turn_off(auto: bool, new_session: bool = False) -> None:
    """new_session: called at the start of a new desktop session for a Game mode left on from the last one. Only
    what outlives a session is put back (the effects, VRR and HDR are already the new session's own), quietly."""
    st = load_json(STATE)
    if not st.get("on"):
        return
    if auto and not st.get("auto"):               # you turned it on yourself: a game ending doesn't turn it off
        return
    saved = st.get("saved", {})
    if not new_session:
        # going off: status says off from now on, while the settings are put back (see turn_on's "busy")
        write_json(STATE, {**st, "busy": "off"})
    if new_session:
        # claim the old record at once: the taskbar starts alongside this, and a Game mode switched on there while the
        # scheduler is still being put back writes a new record that must not be deleted below
        STATE.unlink(missing_ok=True)
    # whatever happens while putting things back, Game mode ends: a state file left saying "on" made the next off
    # try the same restore again and Settings kept showing it on. Each step is tried on its own, so one that fails
    # (a full disk, a tool that's gone) doesn't skip the ones after it or leave the cockpit showing Game mode on.
    failed = []

    def step(fn) -> None:
        try:
            fn()
        except Exception as e:
            failed.append(fn.__name__)
            print(f"starchaser game: couldn't put back {fn.__name__}: {e}", file=sys.stderr)

    def profile() -> None:
        if "profile" in saved and saved["profile"]:
            run("powerprofilesctl", "set", saved["profile"])

    def dnd() -> None:
        if "dnd" in saved and not saved["dnd"]:
            write_json(NOTIFS, {**load_json(NOTIFS), "dnd": False})

    def awake() -> None:
        if "awake" in saved and not saved["awake"] and cockpit("keepAwake") == "true":
            cockpit("toggleKeepAwake")

    def effects() -> None:
        for opt, v in saved.get("effects", {}).items():
            hypr_set(EFFECTS[opt] % ("true" if v else "false"))

    def vrr() -> None:
        if "vrr" in saved:
            hypr_set(f"misc = {{ vrr = {int(saved['vrr'])} }}")

    def scheduler() -> None:
        if "scheduler" in saved:
            before = saved["scheduler"]
            if not before:
                scx("stop")
            else:                                  # put the one that ran before back, e.g. "lavd Auto"
                name, _, mode = before.partition(" ")
                scx("switch", "--sched", name, "--mode", mode or "auto")

    def hdr() -> None:
        # HDR back off on the "Only in Game mode" screens: the ones switched on above, and any set to that while
        # Game mode was on (Settings switched it live); a screen changed to "On" meanwhile stays on
        choice = hdr_map()
        for m in screens():
            mode = choice.get(m.get("description"), "off")
            if mode == "on":
                continue
            if m["name"] in saved.get("hdr", {}):
                was = saved["hdr"][m["name"]]
                run("hyprctl", "eval", monitor_rule(m, was["cm"], was["bits"]), env=hypr_env())
            elif mode == "game" and m.get("colorManagementPreset") == "hdr":
                run("hyprctl", "eval", monitor_rule(m, "srgb", 8), env=hypr_env())
        if not any(v in ("on", "game") for v in choice.values()):      # no screen uses HDR any more: color management off again
            cm_enabled(False)

    for fn in ((profile, dnd, scheduler) if new_session else (profile, dnd, awake, effects, vrr, scheduler, hdr)):
        step(fn)
    if new_session:
        # the taskbar may already have read the record and turned Keep awake back on (Theme.qml); it may also not be
        # up yet, in which case it finds no record and starts with Game mode off. Wait up to 5 s for it to answer.
        # A Game mode switched on again meanwhile is the new one: leave the taskbar showing it.
        for _ in range(10):
            if load_json(STATE).get("on"):
                return
            ans = cockpit("keepAwake")
            if ans in ("true", "false"):
                if ans == "true" and "awake" in saved and not saved["awake"]:
                    cockpit("toggleKeepAwake")
                cockpit("game", "false")
                break
            time.sleep(0.5)
        return
    STATE.unlink(missing_ok=True)
    # Sunshine stays running even if Game mode started it: remote desktop is always on (fleet standard)
    cockpit("game", "false")
    # an "Install Steam?" offer still on screen no longer applies: close it and end its waiting notify-send (the
    # cockpit also drops it from the bell when Game mode goes off, Notifs.withdrawSteamOffer)
    try:
        subprocess.run(["starchaser", "software", "withdraw", "steam"], capture_output=True, timeout=15)
    except (OSError, subprocess.TimeoutExpired):
        pass
    notify("Game mode off", "Everything is back the way it was." if not failed else
           "Some settings couldn't be put back the way they were. Check Quick settings and Settings > Displays.")


def status() -> dict:
    st = load_json(STATE)
    return {"on": bool(st.get("on")) and st.get("busy") != "off", "auto": bool(st.get("auto")), "saved": st.get("saved", {}), "prefs": prefs(),
            "canSchedule": can_schedule(), "scheduler": (scheduler_now() or "") if can_schedule() else "",
            "hdrScreens": [m["name"] for m in screens() if m["hdrCapable"]
                           and hdr_map().get(m.get("description")) == "game"],
            "hasProfiles": bool(shutil.which("powerprofilesctl")), "profile": run("powerprofilesctl", "get")}


USAGE = "\n".join(l.strip() for l in __doc__.split("\n")[2:9] if l.strip())   # the command lines of the doc


def usage_error(msg: str) -> None:
    """A short line saying what was wrong, then the commands (not the whole help)."""
    print(f"starchaser game: {msg}", file=sys.stderr)
    print("Usage:\n  " + USAGE.replace("\n", "\n  "), file=sys.stderr)
    print("Run 'starchaser game --help' for more help.", file=sys.stderr)
    sys.exit(2)


def unknown(msg: str) -> None:
    """One line for a command or option that doesn't exist, like the other starchaser helpers."""
    print(f"starchaser game: {msg}. Run 'starchaser game --help' for more help.", file=sys.stderr)
    sys.exit(2)


def main(argv: list) -> None:
    cmd = argv[0] if argv else "status"
    auto = "--auto" in argv
    if cmd in ("on", "off") and any(a != "--auto" for a in argv[1:]):
        usage_error(f"unexpected argument '{next(a for a in argv[1:] if a != '--auto')}'")
    if cmd in ("toggle", "status", "game-started", "game-ended", "session-start") and len(argv) > 1:
        usage_error(f"unexpected argument '{argv[1]}'")
    if cmd == "on":
        turn_on(auto)
        if sys.stdout.isatty():   # one line for a person at a terminal; the desktop's own paths below stay silent
            print("Game mode is on.")
    elif cmd == "off":
        turn_off(auto)
        if sys.stdout.isatty():
            print("Game mode is off.")
    elif cmd == "toggle":
        turn_off(False) if load_json(STATE).get("on") else turn_on(False)
    elif cmd == "status":
        print(json.dumps(status()))
    elif cmd == "game-started":
        if prefs()["auto"]:
            turn_on(True)
    elif cmd == "session-start":
        turn_off(False, new_session=True)
    elif cmd == "game-ended":
        turn_off(True)
    elif cmd == "set" and len(argv) == 3:
        key, val = argv[1], argv[2]
        if key not in DEFAULTS or val not in ("yes", "no", "true", "false", "on", "off"):
            usage_error(f"set: '{key}' = '{val}' is not allowed; the keys are {', '.join(DEFAULTS)}, each set to yes or no, e.g. starchaser game set dnd no")
        write_json(PREFS, {**load_json(PREFS), key: val in ("yes", "true", "on")})
        if sys.stdout.isatty():   # one line for a person at a terminal; Settings reads the value back and sees none
            print(f"{key} is now {val}.")
    elif cmd == "set":
        usage_error("set takes a key and a value, e.g. starchaser game set dnd no")
    elif cmd.startswith("-"):
        unknown(f"unknown option '{cmd}'")
    else:
        unknown(f"unknown command '{cmd}'")


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]) \
            or any(a in ("-h", "--help") for a in sys.argv[2:]):      # help after a command word too (r172)
        print(__doc__)
        sys.exit(0)
    try:
        main(sys.argv[1:])
    except PermissionError as error:       # a settings folder it may not write: say so, not a traceback
        sys.exit(f"starchaser game: couldn't save your settings ({error.strerror}). Check that you can write to ~/.config.")
