#!/usr/bin/env python3
# summary: Read or change power, idle, and sleep settings.
"""starchaser power: power settings for Settings > Power.

Common commands
    starchaser power toggle-screensaver           enable or disable the saved screensaver
    starchaser power screensaver-state            saved enabled state as JSON (read-only)
    starchaser power get                         current settings + battery/AC state as JSON
    starchaser power set <key> <value>           change one setting (keys below) and apply it
    starchaser power battery                     battery state as JSON (cheap: the cockpit polls it)
    starchaser power button                      the power button (the desktop runs this when it is pressed)
    starchaser power lid close|open              the lid (the desktop runs this when it closes or opens)
                                                 ("Turn off screen" darkens only the built-in screen when another is on)
    starchaser power screensaver preview|stop-preview   a full-screen preview with the saved choices (a key or
                                                        the mouse ends it, as with the real one) / close it

Advanced
    starchaser power export-profiles       saved AC and battery choices only (read-only)
    starchaser power profile-state         available power modes and the current mode (read-only)
    starchaser power apply-profiles --stdin   validate and save both choices together
    starchaser power idle <ac|battery|any> <action>  internal: an idle timer fired (screens-off | lock | sleep)
    starchaser power watch                       internal: battery protection and power-source events
    starchaser power source-changed              plugged in / unplugged: apply that source's power mode
    starchaser power lid resume                  internal: check a closed lid after waking, with a 15-second grace
    starchaser power restart-idle                start the part that notices when you step away again (after updates)
    starchaser power end-session logout|reboot|poweroff  ask apps to close before ending the session
    starchaser power stop-session                internal (logout): stop desktop services before closing the desktop
    starchaser power stop-idle                   internal (logout): stop the screen-off timer before closing the desktop
    starchaser power start-idle                  internal (login): refresh its setup for this version, then start it
    starchaser power screensaver start|resume|back|stop|ended   internal: start it / you're back / you're back after it (cancel kept timers) / stop it / it ended (wake the screens)
    starchaser power screensaver displays        the monitors the screensaver can use, as JSON

Keys (machines with a battery have a battery and a plugged-in profile; others only use "ac"):
    <src>.screens   minutes until the screens turn off, 0 = never      (src: ac | battery)
    <src>.lock      minutes until the screen locks, 0 = never
    <src>.sleep     minutes until the computer sleeps, 0 = never
    <src>.profile   power-saver | balanced | performance | "" (leave alone)
    <src>.lid       sleep | lock | screen-off | nothing                 (what closing the lid does)
    lockWhenAway    yes | no      lock when the screens turn off (on by default on computers with a battery)
    lockOnSleep     yes | no      lock the screen whenever the computer goes to sleep (on until you turn it off);
                                  with the lid on screen-off, closing it locks too unless another screen is connected
    button          menu | ask | sleep | poweroff | nothing  (ask opens Sleep / Shut down / Cancel)
                    (locked: menu and ask both show Sleep / Restart / Shut down / Cancel on the lock screen)
    profile         set the power mode right now
    screensaver.enabled   yes | no    Starchaser Starfield when you step away (before the screens go off)
    screensaver.minutes   minutes until it starts; must be sooner than every screens-off / lock / sleep timer
    screensaver.mode      follow | journey | calm | warp | spores | polar | logic | neonrain | pawprints | petals |
                          tunnel | pendulum | orrery | jellyfish | scope | rivers
    screensaver.speed     0.25 .. 3
    screensaver.stars     100 .. 30000
    screensaver.fps       15 .. 144 (30 saves power)
    screensaver.display   all | a monitor's connector name (DP-1, eDP-1, ...) | sdl:N

"""
# Implementation notes (kept out of --help): the timers live in ~/.config/starchaser/power.json and are written
# into ~/.config/hypr/hypridle.conf; where battery and plugged-in differ, each gets its own listener that only
# acts on its own power source, so plugging in or out needs no restart. The screensaver (package
# starchaser-starfield) is a systemd user service that hypridle starts and stops; it is never enabled at login.
# Its choices become the service's command line through a drop-in,
# ~/.config/systemd/user/starchaser-starfield.service.d/10-starchaser.conf, rewritten whenever it starts (monitor
# numbers can change when screens are plugged in). Turning it off removes the drop-in and its hypridle listener
# and stops it; everything else in hypridle.conf is untouched. It's a visual screensaver, not a lock: it exits on
# any input, and it's stopped before the screens go off, the screen locks, or the computer sleeps.
import contextlib
import fcntl
import hashlib
import json
import math
import os
import re
import select
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path

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

safe_streams()

CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
SETTINGS = CONFIG / "starchaser/power.json"
IDLE = CONFIG / "hypr/hypridle.conf"
IDLE_MARK = CONFIG / "starchaser/hypridle-written.sha256"   # the last hypridle.conf Starchaser wrote (refresh_idle)
SOURCES = ("ac", "battery")
# Idle defaults are preserved on existing installs; setup writes 15-minute locking for new installs.
# Closing the lid sleeps unless docked (decision 2026-11-10 #61).
PROFILE_DEFAULTS = {
    "ac":      {"screens": 30, "lock": 0, "sleep": 0,  "profile": "", "lid": "sleep"},
    "battery": {"screens": 15, "lock": 0, "sleep": 30, "profile": "balanced", "lid": "sleep"},
}
BUTTONS = ("menu", "ask", "sleep", "poweroff", "nothing")
# the "Start after" choices Settings > Displays offers (DisplaysPage.qml saverMinutes)
SAVER_CHOICES = (1, 2, 3, 5, 10, 15, 20, 30, 45, 60)
STATE = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "starchaser"
SAVER_MODES = ("journey", "calm", "warp", "spores", "polar", "logic", "neonrain", "pawprints", "petals",
               "tunnel", "pendulum", "orrery", "jellyfish", "scope", "rivers")
# Settings' style names: a fallback must name the choices the person sees, not the renderer's mode words.
SAVER_LABELS = {"journey": "Star flight", "calm": "Calm stars", "warp": "Warp", "spores": "Alien spores",
                "polar": "Polar sky", "logic": "Logic lights", "neonrain": "Neon rain", "pawprints": "Paw prints",
                "petals": "Falling petals", "tunnel": "Glyph tunnel", "pendulum": "Pendulum wave", "orrery": "Orrery",
                "jellyfish": "Jellyfish", "scope": "Oscilloscope", "rivers": "Rivers"}
SAVER_DEFAULTS = {"enabled": False, "minutes": 10, "mode": "follow", "speed": 1.0, "stars": 9500, "fps": 60, "display": "all"}
# the screensaver package's program, off PATH; an older package (until it updates too) had it in /usr/bin
SAVER_BIN = next((p for p in ("/usr/lib/starchaser/bin/starchaser-starfield", "/usr/bin/starchaser-starfield")
                  if os.path.exists(p)), "/usr/lib/starchaser/bin/starchaser-starfield")
SAVER_UNIT = "starchaser-starfield.service"
SAVER_DROPIN = CONFIG / "systemd/user/starchaser-starfield.service.d/10-starchaser.conf"
SAVER_STOP = "systemctl --user stop starchaser-starfield.service"
LIDS = ("sleep", "lock", "screen-off", "nothing")
# "Lock when the computer goes to sleep" is on unless the person turned it off (decided 2026-11-06 #6: laptops lock
# when they sleep; it was off before). Every save until then wrote the old default (false) into power.json along
# with whatever changed, so a saved value counts only when `set lockOnSleep` wrote it (lockOnSleepChosen). The
# cockpit's Sleep line and the menu's sleep hint read power.json themselves and follow the same rule.
LOCK_ON_SLEEP_DEFAULT = True


def power_supplies(status: list | None = None) -> tuple:
    """Use the same combined system-battery estimate as the system safety service."""
    for lib in (Path(__file__).resolve().parents[1] / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
        if (lib / "device_care.py").is_file():
            sys.path.insert(0, str(lib))
            break
    from device_care import power_supply_state
    return power_supply_state(Path("/sys/class/power_supply"), status)


def battery_estimate(base=Path("/sys/class/power_supply")) -> str:
    """Aggregate system battery energy / drain. Never invent a time when the driver has no rate."""
    energy, watts = 0, 0
    try:
        for bat in base.iterdir():
            if (bat / "type").read_text().strip() != "Battery":
                continue
            if (bat / "scope").exists() and (bat / "scope").read_text().strip() == "Device":
                continue
            if (bat / "status").read_text().strip() != "Discharging":
                return ""
            if (bat / "energy_now").exists() and (bat / "power_now").exists():
                energy += max(0, int((bat / "energy_now").read_text()))
                watts += max(0, int((bat / "power_now").read_text()))
            elif all((bat / k).exists() for k in ("charge_now", "current_now", "voltage_now")):
                voltage = int((bat / "voltage_now").read_text()) / 1e6
                energy += max(0, int((bat / "charge_now").read_text()) * voltage)
                watts += max(0, int((bat / "current_now").read_text()) * voltage)
            else:
                return ""
    except (OSError, ValueError):
        return ""
    if not watts or not energy:
        return ""
    minutes = max(1, round(energy / watts * 60))
    if minutes > 7 * 24 * 60:
        return ""
    h, m = divmod(minutes, 60)
    parts = ([f"{h} hour" + ("s" if h != 1 else "")] if h else [])
    if m:
        parts.append(f"{m} minute" + ("s" if m != 1 else ""))
    return "About " + " ".join(parts) + " left"


def away_lock() -> None:
    if load()["lockWhenAway"]:
        act("lock")


def as_int(v, dflt: int) -> int:
    """A hand-edited timer that is not a whole number of minutes falls back to the default: a broken power.json
    must never crash a read."""
    try:
        n = int(float(v))
    except (TypeError, ValueError, OverflowError):
        return dflt
    return n


def as_float(v, dflt: float) -> float:
    """as_int for the screensaver's speed: Infinity and NaN fall back like anything that isn't a number."""
    try:
        f = float(v)
    except (TypeError, ValueError, OverflowError):
        return dflt
    return f if math.isfinite(f) else dflt


BROKEN_KEPT = ""            # the set-aside file's name when power.json couldn't be read (named by `get`)


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


def load() -> dict:
    """power.json, with defaults for anything missing. A file that can't be read, or that isn't the shape of the
    settings, is kept aside as power.json.broken and the defaults answer; a hand-edited member of the wrong type
    falls back to its default — never a traceback."""
    global BROKEN_KEPT
    try:
        raw = json.loads(SETTINGS.read_text())
    except FileNotFoundError:
        raw = {}
    except (OSError, ValueError, RecursionError):
        raw = None
    if raw is not None and not isinstance(raw, dict):
        raw = None
    if raw is not None and any(k in raw and not isinstance(raw[k], dict) for k in (*SOURCES, "screensaver")):
        raw = None
    if raw is None:
        raw = {}
        if not BROKEN_KEPT:
            keep_broken()
            if BROKEN_KEPT:
                print(f"starchaser power: the settings in power.json couldn't be read and were kept as "
                      f"{BROKEN_KEPT}; the power settings below start from their defaults.", file=sys.stderr)
    chosen = raw.get("lockOnSleepChosen") is True and isinstance(raw.get("lockOnSleep"), bool)
    s = {"button": raw.get("button") if raw.get("button") in BUTTONS else "ask",
         "lockOnSleep": raw["lockOnSleep"] if chosen else LOCK_ON_SLEEP_DEFAULT, "lockOnSleepChosen": chosen}
    s["lockWhenAway"] = raw["lockWhenAway"] if isinstance(raw.get("lockWhenAway"), bool) else power_supplies()[0]
    for src in SOURCES:
        prof = dict(PROFILE_DEFAULTS[src])
        if src == "ac":                                        # v1 settings were flat: they become plugged-in's
            prof.update({k: raw[k] for k in ("screens", "lock", "sleep") if k in raw})
        part = raw.get(src)
        prof.update(part if isinstance(part, dict) else {})
        # a hand-edited value keeps its place only when it has the shape of the default it replaces
        for k, dflt in PROFILE_DEFAULTS[src].items():
            if k in ("screens", "lock", "sleep"):
                prof[k] = as_int(prof[k], dflt)
            elif not isinstance(prof[k], str):
                prof[k] = dflt
        s[src] = prof
    saver = raw.get("screensaver")
    s["screensaver"] = {**SAVER_DEFAULTS, **(saver if isinstance(saver, dict) else {})}
    sv = s["screensaver"]
    for k, dflt in SAVER_DEFAULTS.items():
        if k in ("minutes", "stars", "fps"):
            sv[k] = as_int(sv[k], dflt)
        elif k == "speed":
            sv[k] = as_float(sv[k], dflt)
        elif k == "enabled":
            sv[k] = sv[k] if isinstance(sv[k], bool) else dflt
        elif not isinstance(sv[k], str):
            sv[k] = dflt
    if s["screensaver"]["display"] == "":           # old unnamed choices meant all displays in Settings
        s["screensaver"]["display"] = "all"
    return s


_LOADED: dict = {}       # the settings as main() read them: save() writes only what changed since


def save(s: dict) -> None:
    """Write power.json. Under a lock, the file is read again and only the values this command changed are put in:
    a slow command (the screensaver asking for its displays) must not put back a value another one just saved
    ("Lock when the computer goes to sleep" turned on meanwhile). A failure says why in words, never a traceback."""
    import copy
    import fcntl
    try:
        SETTINGS.parent.mkdir(parents=True, exist_ok=True)
        with open(SETTINGS.parent / ".power.lock", "w") as lk:
            fcntl.flock(lk, fcntl.LOCK_EX)
            fresh = load()
            for k, v in s.items():
                was = _LOADED.get(k)
                if isinstance(v, dict) and isinstance(was, dict) and isinstance(fresh.get(k), dict):
                    for f, fv in v.items():
                        if f not in was or was[f] != fv:
                            fresh[k][f] = fv
                elif was != v:
                    fresh[k] = copy.deepcopy(v)
            tmp = SETTINGS.with_suffix(".json.tmp")
            tmp.write_text(json.dumps(fresh, indent=2) + "\n")
            tmp.replace(SETTINGS)
    except OSError as e:
        sys.exit(f"Couldn't save the power settings: {e.strerror or e}. "
                 f"Check that you can write to {SETTINGS.parent}.".replace(str(Path.home()), "~"))
    _LOADED.clear()
    _LOADED.update(copy.deepcopy(fresh))
    s.clear()
    s.update(fresh)


def yes_no(key: str, val: str) -> bool:
    """A switch value: yes/true/1/on or no/false/0/off. Anything else ("ture") is refused, not read as off."""
    v = val.lower()
    if v in ("yes", "true", "1", "on"):
        return True
    if v in ("no", "false", "0", "off"):
        return False
    bad_value(key, f"yes or no (on or off works too), not {val}")


def profiles() -> tuple:
    if not shutil.which("powerprofilesctl"):
        return "", []
    cur = subprocess.run(["powerprofilesctl", "get"], capture_output=True, text=True, timeout=10).stdout.strip()
    out = subprocess.run(["powerprofilesctl", "list"], capture_output=True, text=True, timeout=10).stdout
    names = [l.strip().lstrip("* ").rstrip(":") for l in out.splitlines() if l.strip().endswith(":") and not l.startswith(" " * 4)]
    return cur, names


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


# In a virtual machine's display (virtio-gpu) screens are never turned off: after one sleep and wake, turning the
# screen off and on again froze the whole display there (the kernel's virtio-gpu driver waits forever for the host,
# and Hyprland with it). A virtual screen saves no power, so nothing is lost. The login screen does the same
# (greeter/hyprland.lua virtual_gpu). The screensaver, lock and sleep are unchanged.
VIRTUAL_GPU = Path("/sys/module/virtio_gpu").is_dir()


def dpms(on: bool, mon: str | None = None) -> None:
    """Screens on or off. `mon` limits it to one screen; it must be a screen Hyprland has right now (an unknown
    name turns every screen off). Turning all screens on keeps a closed lid's built-in screen dark (lid_reapply)."""
    if VIRTUAL_GPU:
        return
    target = f', monitor = "{mon}"' if mon else ""
    subprocess.run(["hyprctl", "dispatch", f'hl.dsp.dpms({{ action = "{"enable" if on else "disable"}"{target} }})'],
                   capture_output=True, env=hypr_env())
    if on and not mon and LID_OFF.exists():
        lid_reapply()


# The built-in screens that "When the lid is closed: Turn off screen" turned off while another screen stayed on.
# Anything that wakes all the screens (coming back, waking from sleep) turns these off again while the lid is shut.
LID_OFF = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-lid-off"
LID_STATE_DIR = Path("/proc/acpi/button/lid")
LID_RESLEEP = LID_OFF.with_name("starchaser-lid-resleep")
LID_OPENED = LID_OFF.with_name("starchaser-lid-opened")
BUILTIN = re.compile(r"^(eDP|LVDS|DSI)-")


def monitors() -> list:
    try:
        return json.loads(subprocess.run(["hyprctl", "monitors", "-j"], capture_output=True, text=True,
                                         env=hypr_env(), timeout=5).stdout) or []
    except (OSError, subprocess.TimeoutExpired, ValueError):
        return []


def lid_closed() -> bool:
    """The lid's state from ACPI. Unknown (no lid file) counts as open."""
    for f in LID_STATE_DIR.glob("*/state"):
        try:
            return "closed" in f.read_text()
        except OSError:
            pass
    return False


def lid_screen_off() -> None:
    """Lid closed with "Turn off screen": only the built-in screen goes dark. An external monitor stays on, so a
    docked laptop keeps working. With no other screen on, every screen goes off (as before)."""
    names = [m.get("name", "") for m in monitors()]
    inner = [n for n in names if BUILTIN.match(n)]
    if inner and len(inner) < len(names):
        LID_OFF.write_text("\n".join(inner))
        for n in inner:
            dpms(False, n)
        return
    LID_OFF.unlink(missing_ok=True)
    dpms(False)


def docked() -> bool:
    """Another screen is on besides the built-in one (a monitor, or a stream's own screen such as sun-vd's): the
    laptop is docked, and closing its lid only darkens the built-in screen. An unreadable screen list counts as not
    docked, so a closed lid on its own still locks."""
    return any(not BUILTIN.match(m.get("name", "")) for m in monitors())


def lid_reapply() -> None:
    """After every screen was woken: keep the built-in screen dark while the lid is still shut."""
    if not lid_closed():
        LID_OFF.unlink(missing_ok=True)
        return
    try:
        want = set(LID_OFF.read_text().split())
    except OSError:
        return
    for n in [m.get("name", "") for m in monitors()]:
        if n in want:
            dpms(False, n)


def idle_inhibited() -> bool:
    """Respect logind's block inhibitors, Wayland idle inhibitors and the cockpit's Keep awake switch.
    An unavailable answer keeps the desktop awake; a delay inhibitor only waits for locking, not for activity."""
    try:
        env = session_env()
        commands = [
            ["busctl", "--system", "--json=short", "call", "org.freedesktop.login1", "/org/freedesktop/login1",
             "org.freedesktop.login1.Manager", "ListInhibitors"],
            ["qs", "-p", str(CONFIG / "quickshell/cockpit"), "ipc", "call", "cockpit", "idleInhibited"],
        ]
        answers = [subprocess.run(cmd, capture_output=True, text=True, timeout=3, env=env) for cmd in commands]
        if any(r.returncode for r in answers):
            return True
        inhibitors = json.loads(answers[0].stdout)["data"][0]
        if any(mode == "block" and {"idle", "sleep"} & set(what.split(":"))
               for what, _who, _why, mode, _uid, _pid in inhibitors):
            return True
        return answers[1].stdout.strip() != "false"
    except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
        return True


def resume_lid() -> None:
    """One check per resume, outside systemd-sleep's frozen user sessions. Opening during the grace cancels it.
    CLOCK_BOOTTIME includes time asleep: a later wake gets protection, but immediate repeated wakes cannot loop."""
    lock_path = LID_RESLEEP.with_suffix(".lock")
    with lock_path.open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return
        opened = LID_OPENED.stat().st_mtime_ns if LID_OPENED.exists() else None

        def closed() -> bool:
            mark = LID_OPENED.stat().st_mtime_ns if LID_OPENED.exists() else None
            return mark == opened and lid_closed()

        for _ in range(15):
            if not closed():
                return
            time.sleep(1)
        try:
            last = float(LID_RESLEEP.read_text())
        except (OSError, ValueError):
            last = -120.0
        if time.clock_gettime(time.CLOCK_BOOTTIME) - last < 120:
            return

        def ready() -> bool:
            # Locking can take time. Read everything again just before requesting sleep, including saved settings.
            _LOADED.clear()
            if not closed() or load()[current_source()]["lid"] != "sleep" or docked() or idle_inhibited():
                return False
            tmp = LID_RESLEEP.with_name(f".{LID_RESLEEP.name}.{os.getpid()}.tmp")
            try:
                with tmp.open("w") as out:
                    out.write(str(time.clock_gettime(time.CLOCK_BOOTTIME)))
                    out.flush()
                    os.fsync(out.fileno())
                tmp.replace(LID_RESLEEP)
            finally:
                tmp.unlink(missing_ok=True)
            print("starchaser power: lid still closed after resume; going back to sleep", file=sys.stderr, flush=True)
            if os.environ.get("STARCHASER_LID_RESUME_SERVICE") == "1":
                # The system unit can request sleep without a polkit prompt; desktop code and locking run as the user.
                raise SystemExit(75)
            return True

        _LOADED.clear()
        s = load()
        if closed() and s[current_source()]["lid"] == "sleep" and not docked() and not idle_inhibited():
            if saver_on(s):
                subprocess.run(SAVER_STOP.split(), capture_output=True)
            suspend(s, ready=ready)


IDLE_EXPIRED = LID_OFF.with_name("starchaser-idle-expired")


def idle_deadline(source: str, action: str) -> None:
    # One marker per source/action, reset by actual input. Timers that fired on AC still matter after unplugging.
    IDLE_EXPIRED.mkdir(mode=0o700, parents=True, exist_ok=True)
    (IDLE_EXPIRED / (source + "-" + action)).touch()


def reset_idle_deadlines() -> None:
    for path in IDLE_EXPIRED.glob("*"):
        path.unlink(missing_ok=True)


def apply_lid(s: dict) -> None:
    what = s[current_source()]["lid"]
    if what == "sleep" and docked():
        lid_screen_off()
        return
    if what == "screen-off":
        if s["lockOnSleep"] and not docked():
            act("lock")
        lid_screen_off()
    elif what in ("lock", "sleep"):
        act(what)


def source_changed(s: dict) -> str:
    src = current_source()
    prof = s[src].get("profile")
    err = set_profile(prof) if prof else ""
    # Power-mode failure must never skip the lid or an expired sleep deadline.
    closed = lid_closed()
    if closed:
        apply_lid(s)
    # A shut lid can do nothing, darken the screen or lock; none replaces an expired sleep timer.
    # A lid sleep already took the strongest action, so don't issue it twice after waking.
    if not (closed and s[src]["lid"] == "sleep") and any(IDLE_EXPIRED.glob("*")) and not idle_inhibited():
        for key, action in (("sleep", "sleep"), ("lock", "lock"), ("screens", "screens-off")):
            if s[src][key] and any((IDLE_EXPIRED / (source + "-" + action)).exists() for source in (src, "any")):
                act(action)
                break
    if err:
        return f"{src}: power mode {prof} not set. {err}"
    return ""


def battery_notice(percent: int, critical: bool = False) -> None:
    estimate = battery_estimate()
    title = f"{percent}% battery left" + (" · " + estimate.removesuffix(" left").lower() if estimate else "")
    body = ("Plug in now. Your computer is going to sleep to protect your work." if critical else
            "Plug in your charger soon." if percent > 7 else "Plug in now. Your computer will sleep before the battery is empty.")
    # The notification waits in its own process, so neither its actions nor an unanswered card delay protection.
    script = ('token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; '
              'answer=$(starchaser notify --credential-fd=3 -a Starchaser -u critical -i battery-caution '
              '-h string:x-canonical-private-synchronous:starchaser-low-battery '
              '-A sleep="Sleep now" -A power="Open Power" -w "$1" "$2" 3<"$token"); '
              'case "$answer" in sleep) exec starchaser power sleep-now;; power) exec starchaser settings power;; esac')
    subprocess.Popen(["sh", "-c", script, "sh", title, body], env=session_env(),
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def battery_check(state: dict, supply: tuple | None = None) -> None:
    has, on_battery, percent = supply if supply is not None else power_supplies()
    if not has or not on_battery:
        state.clear()
        return
    if percent is None:
        return
    if percent <= 20 and not state.get("lowHook"):
        state["lowHook"] = True
        with contextlib.suppress(OSError):
            subprocess.Popen(["starchaser", "satellite", "hook", "battery-low", "STARCHASER_BATTERY_PERCENT=" + str(percent)],
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    threshold = 3 if percent <= 3 else 7 if percent <= 7 else 15 if percent <= 15 else 0
    if threshold and threshold < state.get("notice", 100):
        battery_notice(percent, critical=threshold == 3)
        state["notice"] = threshold
    if threshold == 3 and not state.get("slept"):
        # Critical battery overrides idle inhibitors, including Keep awake. Sleep still goes through the lock path.
        state["slept"] = suspend(load())


def watch_power() -> None:
    from starchaser_device_io import write_json
    state, previous, published = {}, None, None
    # Kernel power-supply events arrive without the taskbar. A 10-second read also covers drivers that omit events.
    with socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, 15) as events:
        events.bind((os.getpid(), 1))
        while True:
            supply = power_supplies()
            source = "battery" if supply[1] else "ac"
            if source != previous:
                error = source_changed(load())
                if error:
                    print(error, file=sys.stderr, flush=True)
                previous = source
            battery_check(state, supply)
            statuses = []
            power_supplies(statuses)
            value = {"has": supply[0], "onBattery": supply[1], "percent": supply[2], "status": statuses[0] if statuses else "", "timeLeft": battery_estimate()}
            if value != published:
                write_json(Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "starchaser-power-state.json", value)
                published = value
            if select.select([events], [], [], 10)[0]:
                events.recv(65536)


def hypridle_conf(s: dict, has_battery: bool) -> str:
    # waking every screen also turns a closed lid's built-in screen back on: put it back to dark (lid_reapply)
    on = (f'hyprctl dispatch "hl.dsp.dpms({{ action = \\"enable\\" }})"; '
          f'test -e "{LID_OFF}" && starchaser power lid reapply')
    if VIRTUAL_GPU:
        on = "true"     # screens are never turned off on virtio-gpu (see VIRTUAL_GPU), so there is nothing to wake
    saver = saver_on(s)
    stop = SAVER_STOP + "; " if saver else ""      # the screensaver never runs under a lock screen or while asleep
    parts = [
        "# Starchaser Linux idle settings. Written by starchaser power (Settings > Power); edits here are replaced.",
        "# Apps that inhibit idle (video players, games, the cockpit's keep-awake) hold all of this off.",
        "general {",
        f"    lock_cmd = {stop}starchaser lock                            # loginctl lock-session lands here",
        f"    before_sleep_cmd = {stop}" + ("loginctl lock-session          # lock before any sleep" if s["lockOnSleep"] else "true"),
        f"    after_sleep_cmd = {on}",
        "    ignore_dbus_inhibit = false",
    ]
    if s["lockOnSleep"]:
        # hold the sleep (logind's delay inhibitor) until the lock screen really holds the screens, not only until
        # lock-session was sent: a sleep started anywhere (the menu, the cockpit, systemctl) wakes locked
        parts.append("    inhibit_sleep = 3                                    # wait for the lock before sleeping")
    parts.append("}")
    # Replaced desktop libraries need a fresh process. Check only after input stops; the keeper also leaves open
    # panels, password prompts, locks and fullscreen apps alone. No dependency on how the update was installed.
    idle_mark = str(Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-shell-idle")
    parts += ["", "# load replaced desktop libraries when the taskbar and menu are not in use",
              "listener {", "    timeout = 30",
              f'    on-timeout = : > "{idle_mark}"; starchaser shell keeper refresh',   # (a builtin: no touch)
              f'    on-resume = rm -f "{idle_mark}"', "}"]
    parts += ["", "listener {", "    timeout = 5", "    on-timeout = true",
              "    on-resume = starchaser power idle reset", "}"]
    srcs = SOURCES if has_battery else ("ac",)
    if any(int(s[src]["screens"]) for src in srcs):
        # coming back after 5+ seconds away always wakes the screens. The screens-off listener's own wake-up can be
        # used up by fake activity (a window closing makes Hyprland fake a pointer move) before the screens go dark;
        # this one re-arms after every 5 quiet seconds, and does nothing when the screens are already on.
        parts += ["", "# wake the screens whenever you come back (see starchaser power act)",
                  "listener {", "    timeout = 5", "    on-timeout = true", f"    on-resume = {on}", "}"]
    if saver:
        # timers kept after the screensaver (see starchaser power act) are canceled when you come back; the check is
        # a file test, so the helper only runs while some are kept
        kept = str(KEPT)        # spelled out: hyprlang would read $XDG_RUNTIME_DIR as one of its own variables
        parts += ["", "# coming back cancels the screens-off / lock / sleep timers kept after the screensaver",
                  "listener {", "    timeout = 5", "    on-timeout = true",
                  f'    on-resume = test -e "{kept}" && starchaser power screensaver back', "}"]
        parts += ["", "# the screensaver (Settings > Displays > Screensaver); the screens-off / lock / sleep timers stop it",
                  "listener {", f"    timeout = {int(s['screensaver']['minutes']) * 60}",
                  "    on-timeout = starchaser power screensaver start", "    on-resume = starchaser power screensaver resume", "}"]
        # a pointer move ends the screensaver even when the screensaver's own window misses it (a single jump from
        # a tablet or a remote desktop can reach it as no motion at all): the listener above re-arms only after a
        # whole start-time of quiet, and its one wake-up is used by the fake pointer move when the window opens.
        # This one re-arms after 2 quiet seconds; inside the first 3 seconds (RESUME_GRACE) only a pointer that
        # really moved counts (STARTED_POS).
        parts += ["", "# any key or move while the screensaver shows ends it (backup for the screensaver's own exit)",
                  "listener {", "    timeout = 2", "    on-timeout = true",
                  f"    on-resume = systemctl --user is-active -q {SAVER_UNIT} && starchaser power screensaver resume", "}"]
    # (with the screensaver on, these fire late: Hyprland resets the idle clock when its window opens. The on-time
    # actions are scheduled from the screensaver's start instead (saver_cmd "start"); these stay as the backstop)
    for key, action in (("screens", "screens-off"), ("lock", "lock"), ("sleep", "sleep")):
        mins = {src: int(s[src][key]) for src in srcs}
        # one plain listener when every source agrees; else one per source that checks the source first
        groups = [(next(iter(mins.values())), "any")] if len(set(mins.values())) == 1 else [(m, src) for src, m in mins.items()]
        for m, src in groups:
            if not m:
                continue
            parts += ["", "listener {", f"    timeout = {m * 60}", f"    on-timeout = starchaser power idle {src} {action}"]
            if action == "screens-off":
                parts.append(f"    on-resume = {on}")
            parts.append("}")
    return "\n".join(parts) + "\n"


def restart_hypridle() -> None:
    """Restart through Hyprland, so hypridle gets the desktop's environment and login session
    (`loginctl lock-session` locks the caller's session: started from anywhere else it locks the wrong one)."""
    subprocess.run(["pkill", "-x", "hypridle"], capture_output=True)
    env = hypr_env()
    if env.get("HYPRLAND_INSTANCE_SIGNATURE"):
        subprocess.run(["hyprctl", "dispatch", 'hl.dsp.exec_cmd("hypridle")'], capture_output=True, env=env)


def stop_session_process(name: str, label: str, unit: str = "") -> None:
    """Wait for this user's process to exit before its Wayland connection disappears."""
    match = ["-x", "-U", str(os.getuid()), name]
    try:
        if unit:
            subprocess.run(["systemctl", "--user", "stop", unit], capture_output=True, timeout=5)
        stopped = subprocess.run(["pkill", "-TERM", *match], capture_output=True)
        if stopped.returncode not in (0, 1):
            raise RuntimeError("couldn't signal the service")
        gone = subprocess.run(["pidwait", *match], capture_output=True, timeout=3)
        if gone.returncode not in (0, 1):
            raise RuntimeError("couldn't wait for the service")
    except (OSError, RuntimeError, subprocess.TimeoutExpired):
        sys.exit(f"The {label} could not be stopped. Try logging out again.")


def stop_idle() -> None:
    # Stop the optional unit too: Restart=on-failure must not revive it during logout.
    stop_session_process("hypridle", "screen-off timer", "hypridle.service")


def stop_session_units() -> None:
    # Stop the portal front end with its back ends, so it cannot immediately reactivate one.
    # Missing optional units are harmless; a failed stop of an installed service must not end the desktop.
    units = ["xdg-desktop-portal.service", "xdg-desktop-portal-hyprland.service",
             "xdg-desktop-portal-gtk.service", "starchaser-nightlight.service"]
    try:
        present = []
        for unit in units:
            state = subprocess.run(["systemctl", "--user", "show", "-p", "LoadState", "--value", unit],
                                   capture_output=True, text=True, timeout=2)
            if state.stdout.strip() == "not-found":
                continue
            if state.returncode or state.stdout.strip() != "loaded":
                raise RuntimeError("couldn't check the service")
            present.append(unit)
        if present:
            subprocess.run(["systemctl", "--user", "stop", *present], capture_output=True, timeout=5, check=True)
        # The user manager can outlive the compositor. A later D-Bus request must not restart the portal
        # with a dead Wayland socket. Hyprland's startup imports the new session's environment again.
        subprocess.run(["systemctl", "--user", "unset-environment", "WAYLAND_DISPLAY", "HYPRLAND_INSTANCE_SIGNATURE"],
                       capture_output=True, timeout=2, check=True)
    except (OSError, RuntimeError, subprocess.SubprocessError):
        sys.exit("The desktop services could not be stopped. Try logging out again.")


def stop_session() -> None:
    stop_session_units()
    stop_idle()
    stop_session_process("awww-daemon", "wallpaper service")
    stop_session_process("hyprsunset", "night light")


def idle_digest(text: str) -> str:
    return hashlib.sha256(text.encode()).hexdigest()


def idle_mark() -> str:
    """The checksum of the last hypridle.conf Starchaser wrote, or "" (none written since the record was kept)."""
    try:
        return IDLE_MARK.read_text().strip()
    except OSError:
        return ""


def write_idle(text: str) -> None:
    """Write hypridle.conf (a Power setting changed). A copy that isn't the last one Starchaser wrote (edited by hand,
    or from before the record was kept) is backed up first, beside it, so a hand edit is never just gone."""
    IDLE.parent.mkdir(parents=True, exist_ok=True)
    try:
        old = IDLE.read_text()
    except FileNotFoundError:
        old = None
    if old is not None and old != text and idle_digest(old) != idle_mark():
        shutil.copy2(IDLE, IDLE.with_name(IDLE.name + ".bak-starchaser-" + time.strftime("%Y%m%d-%H%M%S")))
    tmp = IDLE.with_suffix(".conf.tmp")
    tmp.write_text(text)
    tmp.replace(IDLE)
    IDLE_MARK.parent.mkdir(parents=True, exist_ok=True)
    IDLE_MARK.write_text(idle_digest(text) + "\n")


def refresh_idle(want: str) -> str:
    """The automatic rewrites (at sign-in, after updates) bring hypridle.conf up to this version, but never over a hand
    edit (QA 20261107-0943 004: every update and sign-in rewrote it, with no backup and no word). "same" | "written" |
    "kept": edited since Starchaser last wrote it, so it stays as it is and this version's copy is saved beside it
    as hypridle.conf.starchaser-new."""
    try:
        old = IDLE.read_text()
    except FileNotFoundError:
        old = None
    mark = idle_mark()
    if old == want:
        if not mark:                                # written before the record was kept: Starchaser's own
            write_idle(want)
        return "same"
    if old is not None and mark and idle_digest(old) != mark:
        IDLE.with_name(IDLE.name + ".starchaser-new").write_text(want)
        return "kept"
    write_idle(want)
    return "written"


def apply_idle(s: dict, refresh: bool = False) -> None:
    """hypridle.conf from the settings, then hypridle restarted. refresh: an automatic start (sign-in, "Start it
    now"), not a Power setting change, so a hand-edited file is kept (refresh_idle)."""
    has_battery, _, _ = power_supplies()
    text = hypridle_conf(s, has_battery)
    if refresh:
        refresh_idle(text)
    else:
        write_idle(text)
    restart_hypridle()


# ---------- screensaver ----------

def saver_on(s: dict) -> bool:
    return bool(s["screensaver"]["enabled"]) and Path(SAVER_BIN).exists()


def saver_displays() -> list | None:
    """[{index, name, bounds, connector, id}] from the renderer (its numbers are SDL's, not Hyprland's). None when the
    renderer couldn't be asked (it hung or failed), which is not the same as "no such monitor": callers must not
    read a failed answer as "the chosen monitor is gone"."""
    if not Path(SAVER_BIN).exists():
        return []
    try:
        # short: Settings waits on this whenever the screensaver is set to one monitor, and a hung renderer must not
        # make Settings look stuck (listing displays takes well under a second when it works)
        r = subprocess.run([SAVER_BIN, "--list-displays-json"], capture_output=True, text=True, env=session_env(), timeout=3)
        legacy = r.returncode == 2           # older installed renderer: no structured enumeration yet
        if legacy:
            r = subprocess.run([SAVER_BIN, "--list-displays"], capture_output=True, text=True, env=session_env(), timeout=3)
    except (OSError, subprocess.TimeoutExpired):
        return None         # a renderer that hangs or won't run must not leave a setting half-applied
    if r.returncode != 0:
        return None
    try:
        if legacy:
            out = []
            for line in r.stdout.splitlines():
                idx, sep, name = line.partition(":")
                if not sep or not idx.isdigit():
                    return None
                out.append({"index": int(idx), "name": name.strip(), "bounds": None})
        else:
            out = json.loads(r.stdout)
        if not isinstance(out, list) or any(not isinstance(d, dict)
                or type(d.get("index")) is not int or d["index"] < 0
                or not isinstance(d.get("name"), str) for d in out):
            return None
        if len({d["index"] for d in out}) != len(out):
            return None
    except ValueError:
        return None

    outputs = monitors()
    names = {m["name"] for m in outputs if m.get("name")}
    geometry = []
    for m in outputs:
        try:
            w, h = m["width"], m["height"]
            if m.get("transform", 0) % 2:
                w, h = h, w
            if m.get("name") and not m.get("disabled", False) and w > 0 and h > 0:
                # SDL versions report either logical or pixel dimensions at the logical output position.
                for scale in (m.get("scale", 1), 1):
                    geometry.append((m["name"], {"x": m["x"], "y": m["y"],
                                                "width": round(w / scale), "height": round(h / scale)}))
        except (KeyError, TypeError, ZeroDivisionError):
            continue
    for d in out:
        name = d["name"].strip()
        suffix = re.search(r"\(([^()]*)\)$", name)
        conn = suffix[1].strip() if suffix else name
        if conn not in names and not re.fullmatch(r"(?:eDP|LVDS|DSI|DP|HDMI(?:-A)?|DVI(?:-[DI])?|VGA|Virtual)-\d+(?:-\d+)*", conn):
            conn = ""
        if not conn:
            matches = {n for n, bounds in geometry if bounds == d.get("bounds")}
            # Mirrored outputs or repeated SDL bounds do not identify one particular screen.
            if len(matches) == 1 and sum(o.get("bounds") == d.get("bounds") for o in out) == 1:
                conn = next(iter(matches))
        d["connector"] = conn
    connectors = [d["connector"] for d in out]
    for d in out:
        if connectors.count(d["connector"]) > 1 or d["connector"] == "all" or d["connector"].startswith("sdl:"):
            d["connector"] = ""
        d["id"] = d["connector"] or f"sdl:{d['index']}"
    return out


def renderer_caps() -> dict:
    """The installed renderer's colors and modes, remembered until its version or binary changes."""
    full = {"colors": True, "modes": list(SAVER_MODES)}
    try:
        stamp = Path(SAVER_BIN).stat().st_mtime_ns
        version = subprocess.run([SAVER_BIN, "--version"], capture_output=True, text=True, timeout=5)
        key = [SAVER_BIN, version.stdout + version.stderr, stamp]
        cache = STATE / "saver-caps.json"
        try:
            saved = json.loads(cache.read_text())
            caps = saved["caps"]
            if saved["key"] == key and isinstance(caps["colors"], bool) and isinstance(caps["modes"], list) \
                    and caps["modes"] and all(isinstance(m, str) for m in caps["modes"]):
                return caps
        except (OSError, ValueError, KeyError, TypeError):
            pass
        help_result = subprocess.run([SAVER_BIN, "--help"], capture_output=True, text=True, timeout=5)
        help_text = help_result.stdout + "\n" + help_result.stderr
        # the styles it knows: each of ours named anywhere in its help as a whole word. Help formats differ by version
        # (1.0.0 says "--mode journey|calm|warp", 1.1.0 lists them over several lines), so no layout is assumed
        modes = [m for m in SAVER_MODES if re.search(rf"(?<![\w-]){re.escape(m)}(?![\w-])", help_text)]
        # Unknown help (or a missing binary) must not silently strip a choice a newer renderer may support.
        caps = {"colors": "--colors" in help_text, "modes": modes} if modes else full
        try:
            STATE.mkdir(parents=True, exist_ok=True)
            cache.write_text(json.dumps({"key": key, "caps": caps}))
        except OSError:
            pass
        return caps
    except (OSError, subprocess.TimeoutExpired):
        return full


def saver_theme_args(s: dict) -> tuple:
    """Resolve the style and valid theme colors once in the same way for the command line and its explanation."""
    try:
        theme = json.loads((STATE / "theme.json").read_text())
    except (OSError, ValueError, RecursionError):
        theme = {}
    if not isinstance(theme, dict):
        theme = {}
    choice = s["screensaver"]["mode"]
    mode = theme.get("screensaver") if choice == "follow" else choice
    mode = mode if mode in SAVER_MODES else "journey"
    colors = theme.get("colors")
    palette = [colors.get(k) for k in ("bg", "accent", "accent2", "accent3")] if isinstance(colors, dict) else []
    color_args = ["--colors", ",".join(palette)] if len(palette) == 4 and all(
        isinstance(v, str) and re.fullmatch(r"#?[0-9a-fA-F]{6}", v) for v in palette) else []
    return mode, color_args


def saver_compat_note(s: dict) -> str:
    mode, color_args = saver_theme_args(s)
    caps = renderer_caps()
    changes = []
    if mode != "journey" and mode not in caps["modes"]:
        changes.append(f"shows Star flight instead of {SAVER_LABELS[mode]}")
    if color_args and not caps["colors"]:
        changes.append("ignores the theme colors")
    return "The installed screensaver is older than Settings, so it " + " and ".join(changes) + "." if changes else ""


def saver_error() -> str:
    try:
        return (STATE / "saver-last-error").read_text().strip()
    except OSError:
        return ""


def saver_args(s: dict, preview: bool = False, displays: list | None = None) -> list:
    """The renderer's command line from the saved choices (each value checked again here). `displays`: the renderer's
    list when the caller already has it (`set screensaver.display` just asked), so the renderer is asked only once."""
    c = s["screensaver"]
    mode, color_args = saver_theme_args(s)
    caps = renderer_caps()
    if mode not in caps["modes"]:
        mode = "journey"
    if not caps["colors"]:
        color_args = []
    speed = min(3.0, max(0.25, float(c["speed"])))
    stars = min(30000, max(100, int(c["stars"])))
    fps = min(144, max(15, int(c["fps"])))
    args = [SAVER_BIN, "--windowed" if preview else "--saver"]
    if not preview:
        idx = None
        if c["display"] != "all":
            known = saver_displays() if displays is None else displays
            if known is None:
                idx = dropin_display()       # couldn't ask: keep the monitor the service already uses
            else:
                idx = next((d["index"] for d in known if d["id"] == c["display"]), None)
        args += ["--all-displays"] if idx is None else ["--display", str(idx)]   # a monitor that's gone: every monitor
    return args + color_args + ["--mode", mode, "--speed", f"{speed:g}", "--stars", str(stars), "--fps", str(fps)]


def dropin_display() -> int | None:
    """The --display number in the service's current command line, if it has one."""
    try:
        m = re.search(r"--display'? '?(\d+)", SAVER_DROPIN.read_text())
    except OSError:
        return None
    return int(m.group(1)) if m else None


def session_env() -> dict:
    env = hypr_env()
    rt = env.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
    env.setdefault("XDG_RUNTIME_DIR", rt)
    if not env.get("WAYLAND_DISPLAY"):
        socks = sorted(p.name for p in Path(rt).glob("wayland-[0-9]") if p.is_socket())
        if socks:
            env["WAYLAND_DISPLAY"] = socks[0]
    return env


def unit_path(path: str) -> str:
    """A path as a unit file line writes it: the home folder as %h."""
    home = str(Path.home())
    return "%h" + path[len(home):] if path.startswith(home + "/") else path


def write_dropin(s: dict, displays: list | None = None) -> bool:
    """The service's command line; True when it changed (then systemd must reload)."""
    import shlex
    # ExecStopPost: whenever it ends, the timers scheduled from its start are canceled (at screen-off that's the
    # one that just ran; when you come back, the ones that haven't)
    text = ("# Written by starchaser power (Settings > Displays > Screensaver); edits here are replaced.\n"
            "[Service]\nExecStart=\nExecStart=" + " ".join(shlex.quote(a) for a in saver_args(s, displays=displays)) + "\n"
            "ExecStopPost=" + unit_path(tool_path("starchaser-power")) + " screensaver ended\n")
    if SAVER_DROPIN.exists() and SAVER_DROPIN.read_text() == text:
        return False
    SAVER_DROPIN.parent.mkdir(parents=True, exist_ok=True)
    SAVER_DROPIN.write_text(text)
    return True


def apply_clamped(s: dict, was_on: bool) -> None:
    """Apply a timer change after clamp_saver: hypridle.conf first, and the screensaver's service only when the
    clamp just turned it off or back on (its command line doesn't depend on the timers, and refreshing it asks the
    renderer for its displays, which must not stand between a new timer and hypridle)."""
    apply_idle(s)
    if was_on != saver_on(s):
        apply_saver(s)


def apply_saver(s: dict, displays: list | None = None) -> None:
    """Turn the screensaver's integration on or off to match the settings, then rewrite hypridle.conf."""
    if saver_on(s):
        if write_dropin(s, displays):
            subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
    else:
        subprocess.run(SAVER_STOP.split(), capture_output=True)
        if SAVER_DROPIN.exists():
            SAVER_DROPIN.unlink()
            try:
                SAVER_DROPIN.parent.rmdir()
            except OSError:
                pass
            subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
    apply_idle(s)


LIMIT_WORDS = {"screens": "your screens turn off", "lock": "the screen locks", "sleep": "the computer sleeps"}


def saver_limit_by(s: dict) -> tuple:
    """The screensaver has to start before anything else happens: the soonest screens-off / lock / sleep, in
    minutes, and what sets it, in words ("your screens turn off", "... on battery" when only the battery time is
    that short). On a tie: screens, then lock, then sleep, plugged in before battery. (0, "") when all are Never."""
    has_battery, _, _ = power_supplies()
    best = (0, "")
    for k in ("screens", "lock", "sleep"):
        if k == "screens" and VIRTUAL_GPU:
            continue        # screens are never turned off here (see VIRTUAL_GPU), so that timer limits nothing
        for src in (SOURCES if has_battery else ("ac",)):
            t = int(s[src][k])
            if t and (not best[0] or t < best[0]):
                best = (t, LIMIT_WORDS[k] + (" on battery" if src == "battery" else ""))
    return best


def saver_limit(s: dict) -> int:
    return saver_limit_by(s)[0]


def dur(m: int) -> str:
    """Minutes the way Settings' dropdowns say them (60 is "1 hour")."""
    h, r = divmod(m, 60)
    mins = f"{r} minute{'' if r == 1 else 's'}"
    if not h:
        return mins
    hours = f"{h} hour{'' if h == 1 else 's'}"
    return hours if not r else f"{hours} {mins}"


def clamp_saver(s: dict) -> str:
    """After a screens-off / lock / sleep time changes, keep the screensaver starting sooner than all of them.
    Starting at the same time as the lock races it, and a screensaver that starts after the lock comes up stays
    on screen after you unlock. Returns a note for Settings when it changed something the person had turned on.

    A screensaver this turned off (nothing fits under a 1-minute timer) is marked autoOff, and turns back on by
    itself once a start time fits again (decided 2026-10-10: B045 b): with the start time the person picked when it
    still fits, else the latest one that does. Only one Starchaser turned off: turning it on or off in Displays
    clears the mark, so a person's own Off is never undone."""
    c, (limit, by) = dict(s["screensaver"]), saver_limit_by(s)
    if not c["enabled"] and c.get("autoOff"):
        fits = [m for m in SAVER_CHOICES if not limit or m < limit]
        if not fits:
            return ""
        if limit and int(c["minutes"]) >= limit:
            c["minutes"] = fits[-1]
        c["enabled"], c["autoOff"] = True, False
        s["screensaver"] = c
        return f"The screensaver is back on (starts after {dur(int(c['minutes']))})."
    # a screensaver that's off keeps the start time the person picked: turning it back on in Displays moves it to
    # the latest one that fits and says so, and `start` won't run one that races the lock anyway
    if not c["enabled"] or not limit or int(c["minutes"]) < limit:
        return ""
    fits = [m for m in SAVER_CHOICES if m < limit]
    if fits:
        m = c["minutes"] = fits[-1]
        note = f"Start after is now {dur(m)}, so the screensaver comes before {by} ({dur(limit)})."
    else:
        c["enabled"] = False         # nothing fits under a 1-minute timer: turn it off rather than race the lock
        c["autoOff"] = True          # ...and back on by itself when the timer is longer again (above)
        # no one-time note: Settings > Power and Displays already show a lasting line naming the 1-minute timer
        # (saverBlockText), and both together read as two stacked messages saying the same thing
        note = ""
    s["screensaver"] = c
    return note


def own_hyprlock() -> bool:
    """This account's hyprlock is running (another person's, at a second login, locks nothing here). Read from /proc,
    as pgrep -x would, without starting it: the lock wait below looks four times a second."""
    uid = os.getuid()
    for proc in Path("/proc").iterdir():
        if not proc.name.isdigit():
            continue
        try:
            if (proc / "comm").read_text().strip() == "hyprlock" and proc.stat().st_uid == uid:
                return True
        except OSError:
            continue
    return False


# Written by the lock screen (its pid) once every screen is covered, removed as it unlocks (lock/shell.qml)
LOCK_SECURE = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-lock.secure"


def lock_is_up() -> bool:
    """Is the lock screen showing? The lock's `locked` call answers true or false on stdout (and exits 0 either
    way, so the exit code alone says nothing). A lock preview window (STARCHASER_LOCK_PREVIEW=1) answers false,
    and `ipc` talks to the oldest copy of the lock config, so with a preview open the real lock is the newest copy:
    ask both, as starchaser lock does."""
    if own_hyprlock():
        return True
    for newest in ([], ["--newest"]):
        try:
            r = subprocess.run(["qs", "ipc", *newest, "-p", str(CONFIG / "quickshell/lock"), "call", "lock", "locked"],
                               capture_output=True, text=True, env=session_env(), timeout=3)
        except (OSError, subprocess.TimeoutExpired):
            continue
        if r.stdout.strip() == "true":
            return True
    return False


def lock_power_choices() -> bool:
    """Ask the lock screen to show its power choices (the power key while locked). Like lock_is_up, both copies are
    asked: a preview answers false and shows nothing; the real lock answers true."""
    for newest in ([], ["--newest"]):
        try:
            r = subprocess.run(["qs", "ipc", *newest, "-p", str(CONFIG / "quickshell/lock"), "call", "lock", "powerKey"],
                               capture_output=True, text=True, env=session_env(), timeout=3)
        except (OSError, subprocess.TimeoutExpired):
            continue
        if r.stdout.strip() == "true":
            return True
    return False


PREVIEW_PID = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-starfield-preview.pid"


def preview_pid() -> int | None:
    """The preview renderer's pid while it really runs, else None. The pid file stays behind when the preview is
    closed with Esc or its window's close (the renderer exits by itself), so the file alone isn't proof: the pid has
    to still be our renderer (the same check stop-preview makes). A stale file is removed."""
    try:
        pid = int(PREVIEW_PID.read_text())
        if Path(f"/proc/{pid}/exe").resolve() == Path(SAVER_BIN):
            st = Path(f"/proc/{pid}/stat").read_text()
            if st[st.rindex(")") + 2:][:1] != "Z":                   # an exited child nobody reaped yet isn't running
                return pid
    except (OSError, ValueError):
        pass
    try:
        PREVIEW_PID.unlink(missing_ok=True)
    except OSError:                # a runtime folder it may not write: no preview, never a traceback
        pass
    return None
STARTED = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-starfield.started"
# Hyprland fakes a pointer movement when the screensaver's window appears under the pointer, and hypridle takes
# that as you coming back: activity this soon after it starts isn't you. (The renderer has the same grace for
# pointer motion; real keys, clicks, touches and moves still end it, because it exits on them by itself.)
RESUME_GRACE = 3.0
# Where the pointer was when the screensaver started. The fake move above leaves the pointer where it is, so activity
# inside the grace with the pointer somewhere else is you: a single jump from a tablet or a remote desktop (QEMU's
# pointer) reaches the screensaver's window as no motion at all, and the backup listener's one wake-up landed in the
# grace and was dropped; the screensaver then stayed until a second move 2 s later (r30 VM test). Read only.
STARTED_POS = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-starfield.started-pos"
# Set when the screens-off or lock timer closes the screensaver itself (you haven't come back): its "ended" then
# keeps the later timers it scheduled. Without this the lock canceled the screens-off timer, and the screens went
# off a whole screens-off interval after the lock (lock 2 + screens off 3 went dark at 5 minutes, not 3).
KEEP_TIMERS = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-after-saver.keep"
# While those kept timers wait: when they were kept. You coming back (any key or move, also at the lock screen while
# you type your password) cancels them through hypridle's "back" listener, so the screens can't go dark and the
# computer can't sleep under your hands. The pointer move Hyprland fakes when the screensaver's window closes comes
# within a second or two of keeping them, so a "back" that soon is ignored.
KEPT = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-after-saver.kept"
BACK_GRACE = 5.0


def keep_timers(why: str) -> None:
    KEEP_TIMERS.write_text(why)
    KEPT.write_text(str(time.time()))


def stop_after_saver() -> None:
    # one at a time: a timer that was never scheduled (lock or sleep set to Never) makes a combined
    # `systemctl stop` fail as a whole, and then the screens-off one fired while you were using the computer
    for action in ("screens-off", "lock", "sleep"):
        subprocess.run(["systemctl", "--user", "stop", f"starchaser-after-saver-{action}.timer"], capture_output=True)
    KEPT.unlink(missing_ok=True)


def screens_dark() -> bool:
    try:
        mons = json.loads(subprocess.run(["hyprctl", "monitors", "-j"], capture_output=True, text=True,
                                         env=hypr_env()).stdout)
    except (OSError, ValueError):
        return False
    return bool(mons) and not any(m.get("dpmsStatus") for m in mons)


def still_away() -> bool:
    """For a timer scheduled when the screensaver started: are you still away? The screensaver is still up, or the
    lock screen or dark screens took over from it. Back at the computer (none of those): the timer does nothing."""
    if subprocess.run(["systemctl", "--user", "is-active", "--quiet", SAVER_UNIT], capture_output=True).returncode == 0:
        return True
    return lock_is_up() or screens_dark()


SAVER_ACTIVE = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-saver-active"


SAVER_CURSOR = SAVER_ACTIVE.with_name("starchaser-saver-cursor.json")


def saver_cursor(active: bool) -> None:
    # A newly mapped Wayland window may never get pointer focus until the mouse moves. SDL cannot hide
    # the previous app's cursor then. Hide it through the compositor's idle timer without moving it.
    env = hypr_env()
    session = env.get("HYPRLAND_INSTANCE_SIGNATURE")
    if not session:
        return
    try:
        with SAVER_CURSOR.with_suffix(".lock").open("a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            try:
                saved = json.loads(SAVER_CURSOR.read_text())
            except (OSError, ValueError, RecursionError):
                saved = {}
            if not isinstance(saved, dict):
                saved = {}
            same_session = saved.get("session") == session
            if active:
                if same_session:
                    return                  # do not save our temporary timeout as the person's own choice
                reply = subprocess.run(["hyprctl", "getoption", "cursor:inactive_timeout", "-j"],
                                       capture_output=True, text=True, env=env, timeout=3)
                answer = json.loads(reply.stdout)
                prior = answer.get("float") if isinstance(answer, dict) else None
                if reply.returncode or type(prior) not in (int, float) or not math.isfinite(prior) or prior < 0:
                    return
                with tempfile.NamedTemporaryFile(mode="w", dir=SAVER_CURSOR.parent, prefix=".saver-cursor-", delete=False) as tmp:
                    json.dump({"session": session, "timeout": prior}, tmp)
                    tmp.flush()
                    os.fsync(tmp.fileno())
                os.replace(tmp.name, SAVER_CURSOR)
                value = 0.1
            else:
                if not same_session:
                    SAVER_CURSOR.unlink(missing_ok=True)
                    return
                value = saved.get("timeout")
                if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
                    return
            result = subprocess.run(["hyprctl", "eval", f"hl.config({{ cursor = {{ inactive_timeout = {value} }} }})"],
                                    capture_output=True, env=env, timeout=3)
            if not active and result.returncode == 0:
                SAVER_CURSOR.unlink(missing_ok=True)
    except (OSError, ValueError, subprocess.TimeoutExpired):
        pass                                # cursor hiding must not stop the screensaver or its cleanup


def saver_popup_state(active: bool) -> None:
    saver_cursor(active)
    # ExecStopPost calls ended even after a crash; keep the flag in the runtime folder.
    try:
        SAVER_ACTIVE.write_text("1\n" if active else "0\n")
    except OSError:
        pass                                  # only hides the pop-up cards; never stop the saver for it


def saver_cmd(s: dict, what: str) -> None:
    if what == "start":
        if not saver_on(s):
            return
        # already showing: hypridle asks again one start-time after the screensaver's window opened (that window
        # resets its idle clock), and starting over would push the screens-off / lock / sleep timers back by a
        # whole start-time (start 1 + screens off 3 went dark at 4 minutes)
        if subprocess.run(["systemctl", "--user", "is-active", "--quiet", SAVER_UNIT], capture_output=True).returncode == 0:
            return
        # never under the lock screen: it gets no input there, so it would still cover the desktop after unlock
        if lock_is_up():
            return
        # a start time at or past the lock's (a power.json from before the clamp) races the lock: sit it out
        limit = saver_limit(s)
        if limit and int(s["screensaver"]["minutes"]) >= limit:
            return
        env = session_env()
        # user services don't see the desktop's variables unless they're handed over
        subprocess.run(["systemctl", "--user", "import-environment", "WAYLAND_DISPLAY", "XDG_CURRENT_DESKTOP",
                        "HYPRLAND_INSTANCE_SIGNATURE", "XDG_RUNTIME_DIR"], capture_output=True, env=env)
        if write_dropin(s):
            subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
        # not while the screens are off: the screensaver's window would count as activity and turn them back on
        try:
            mons = json.loads(subprocess.run(["hyprctl", "monitors", "-j"], capture_output=True, text=True, env=env).stdout)
            if mons and not any(m.get("dpmsStatus") for m in mons):
                return
        except ValueError:
            pass
        # asked again: the steps above take a few seconds, and a lock that came up meanwhile would end up on top
        if lock_is_up():
            return
        STARTED.write_text(str(time.time()))
        pos = cursor_pos()
        if pos is None:
            STARTED_POS.unlink(missing_ok=True)
        else:
            STARTED_POS.write_text(json.dumps(pos))
        # timers kept from an earlier time away (lock, then you unlocked) would still hold their unit names, and the
        # new ones below couldn't be scheduled: clear them first
        stop_after_saver()
        KEEP_TIMERS.unlink(missing_ok=True)
        saver_popup_state(True)
        started = subprocess.run(["systemctl", "--user", "start", SAVER_UNIT], capture_output=True, text=True)
        if started.returncode:
            saver_popup_state(False)
        # Keep the timer path as it was even on failure; Settings can explain it without delaying a good start.
        try:
            error_file = STATE / "saver-last-error"
            if started.returncode:
                reason = started.stderr.strip()
                if not reason:
                    try:
                        reason = subprocess.run(["journalctl", "--user", "-u", SAVER_UNIT, "-n", "1", "--no-pager", "-o", "cat"],
                                                capture_output=True, text=True, timeout=3).stdout.strip()
                    except (OSError, subprocess.TimeoutExpired):
                        pass
                reason = f"The screensaver couldn't start: {reason.splitlines()[-1][:120]}." if reason else \
                         "The screensaver couldn't start. Try Preview to see what went wrong."
                STATE.mkdir(parents=True, exist_ok=True)
                error_file.write_text(reason + "\n")
            else:
                error_file.unlink(missing_ok=True)
        except OSError:
            pass
        # the screensaver's window resets hypridle's idle clock, so its own timers would fire late (screens off at
        # 15 + 30 = 45 minutes): schedule them from now for the time that's left
        src, head = current_source(), int(s["screensaver"]["minutes"])
        for key, action in (("screens", "screens-off"), ("lock", "lock"), ("sleep", "sleep")):
            left = int(s[src][key]) - head
            if int(s[src][key]) and left > 0:
                # AccuracySec: systemd lets a timer fire up to a minute late by default (screens 3 went dark at 3:22)
                subprocess.run(["systemd-run", "--user", "--collect", f"--unit=starchaser-after-saver-{action}",
                                f"--on-active={left * 60}", "--timer-property=AccuracySec=1s", str(Path(__file__).resolve()), "idle", "any", action, "after-saver"],
                               capture_output=True)
        # Watch the pointer long enough for hypridle's backup listener to re-arm (~3 s), then stop when the pointer
        # moves. This only reads where the pointer is; it never moves it.
        if pos is not None:
            until = time.monotonic() + RESUME_GRACE + 2.5
            while time.monotonic() < until:
                time.sleep(0.25)
                now = cursor_pos()
                if now is not None and now != pos:
                    if subprocess.run(["systemctl", "--user", "is-active", "--quiet", SAVER_UNIT], capture_output=True).returncode == 0:
                        subprocess.run(SAVER_STOP.split(), capture_output=True)
                    break
    elif what == "ended":
        saver_popup_state(False)
        # closed by the screens-off or lock timer, not by you: the later timers stay (each checks you're still away
        # when it fires, and you coming back cancels them: "back" below)
        if KEEP_TIMERS.exists():
            KEEP_TIMERS.unlink(missing_ok=True)
            return
        stop_after_saver()
    elif what == "back":
        # hypridle: a key or move after 5 quiet seconds. Kept timers are canceled: you're here (typing your
        # password at the lock screen counts), so the screens stay on and the computer doesn't sleep.
        try:
            if time.time() - float(KEPT.read_text()) < BACK_GRACE:
                return          # the fake pointer move from the screensaver's window closing
        except (OSError, ValueError):
            return              # nothing kept
        stop_after_saver()
    elif what == "resume":
        try:
            if time.time() - float(STARTED.read_text()) < RESUME_GRACE:
                # inside the grace, only a pointer that has really moved counts (see STARTED_POS)
                try:
                    was = tuple(json.loads(STARTED_POS.read_text()))
                except (OSError, ValueError, TypeError):
                    return
                now = cursor_pos()
                if now is None or now == was:
                    return
        except (OSError, ValueError):
            pass
        subprocess.run(SAVER_STOP.split(), capture_output=True)
    elif what == "stop":
        subprocess.run(SAVER_STOP.split(), capture_output=True)
    elif what == "preview":
        # The preview is the real thing (decided 2026-10-10): full screen on the screens it's set to show on, and it
        # ends when the mouse moves or a key is pressed, like the screensaver itself, so it needs no close x. The
        # renderer's own --saver mode ends on keys, clicks, touches and moves; preview-watch below covers a pointer
        # jump its window never sees as motion (a tablet, a remote desktop), as `start` does for the real one.
        saver_cmd(s, "stop-preview")
        if not Path(SAVER_BIN).exists():
            sys.exit("The screensaver (starchaser-starfield) isn't installed.")
        # where the pointer is BEFORE the preview opens (as `start` does): read after it opened, a move in its first
        # moments (which the renderer's own grace ignores) became the starting point and left the preview up
        pos = cursor_pos()
        # Keep the renderer's words: older installed versions can reject a new option before a window appears.
        preview_err = PREVIEW_PID.with_suffix(".stderr")
        try:
            with preview_err.open("w") as err:
                p = subprocess.Popen(saver_args(s), env=session_env(), start_new_session=True,
                                     stdout=subprocess.DEVNULL, stderr=err)
        except OSError:
            # plain words, not the system's error text ("[Errno 13] Permission denied: ...")
            sys.exit("The preview couldn't start: the screensaver program can't be run. Reinstalling it from "
                     "Settings > Software (Starchaser Starfield) usually fixes this.")
        PREVIEW_PID.write_text(str(p.pid))
        if pos is not None:
            subprocess.Popen([str(Path(__file__).resolve()), "screensaver", "preview-watch"], start_new_session=True,
                             env={**os.environ, "STARCHASER_PREVIEW_POS": json.dumps(pos)},
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        until = time.monotonic() + 1.5
        while True:
            if p.poll() is not None:
                PREVIEW_PID.unlink(missing_ok=True)
                if p.returncode == 0:
                    return                      # a key, click or move ended it: that is not a failure
                try:
                    reason = preview_err.read_text(errors="replace").strip()
                except OSError:
                    reason = ""
                sys.exit(f"The preview couldn't start: {reason.splitlines()[-1][:120]}." if reason else
                         "The preview couldn't start (the screensaver program quit right away).")
            if time.monotonic() >= until:
                break
            time.sleep(0.1)
        (STATE / "saver-last-error").unlink(missing_ok=True)       # it opened, so an older start failure no longer holds
    elif what == "preview-watch":
        # while the preview runs: the pointer somewhere else than where it was when the preview opened is you
        # moving it, so the preview ends. This only reads where the pointer is; it never moves it.
        try:
            pos = tuple(json.loads(os.environ.get("STARCHASER_PREVIEW_POS", "")))
        except (ValueError, TypeError):
            pos = None
        time.sleep(0.5)
        while pos is not None and preview_pid():
            time.sleep(0.25)
            now = cursor_pos()
            if now is not None and now != pos:
                saver_cmd(s, "stop-preview")
                break
    elif what == "stop-preview":
        pid = preview_pid()                                                  # only ever our own preview
        if pid:
            try:
                os.kill(pid, 15)
            except OSError:
                pass
        PREVIEW_PID.unlink(missing_ok=True)
    elif what == "preview-wait":
        # blocks until the preview window is gone (closed with Esc, its close, or Stop preview), so Settings can
        # put its buttons back; cheap, unlike `get`, which may repair and re-apply settings
        while preview_pid():
            time.sleep(0.5)
    elif what == "displays":
        print(json.dumps(saver_displays() or []))
    else:
        usage(f"unknown screensaver command: {what}")


def maker_owns_power() -> bool:
    import runpy
    return runpy.run_path(str(Path(__file__).resolve().with_name("starchaser-laptop")))["maker_owns_power"]()


def set_profile(val: str) -> str:
    """Switch the power mode now. "" when it worked, else a plain sentence for Settings (never the raw D-Bus error:
    power-profiles-daemon allows the change only for the person signed in at this computer)."""
    if maker_owns_power():
        return "Power modes are managed by the laptop control center. Open Settings > Hardware to change the owner."
    try:
        r = subprocess.run(["powerprofilesctl", "set", val], capture_output=True, text=True, timeout=15)
    except (OSError, subprocess.TimeoutExpired):
        return "Couldn't change the power mode right now."
    if r.returncode == 0:
        return ""
    if re.search(r"AccessDenied|Not ?Authori[sz]ed|not allowed|PermissionDenied", r.stderr or "", re.I):
        return "Couldn't change the power mode: only the person signed in at this computer can change it."
    return "Couldn't change the power mode right now."


def usage(msg: str) -> None:
    """A wrong command: say what was wrong in one line (not the whole help), and exit 2."""
    print(f"starchaser power: {msg}\nRun 'starchaser power --help' for more help.", file=sys.stderr)
    sys.exit(2)


def bad_value(key: str, msg: str) -> None:
    """A wrong value for a known setting: every key answers the same way (exit 2, nothing saved)."""
    print(f"starchaser power: {key}: {msg} (nothing was changed)", file=sys.stderr)
    sys.exit(2)


def ok_setting(key: str, val: str) -> None:
    """One plain line on a terminal after a change; Settings and scripts read the values back and see no change."""
    if sys.stdout.isatty():
        print(f"{key} is now {val}.")


def current_source() -> str:
    _, on_battery, _ = power_supplies()
    return "battery" if on_battery else "ac"


def cursor_pos() -> tuple | None:
    """Where the pointer is (Hyprland's cursorpos), or None when it can't be read. Read only, never set."""
    try:
        r = subprocess.run(["hyprctl", "cursorpos", "-j"], capture_output=True, text=True, env=hypr_env(), timeout=3)
        c = json.loads(r.stdout)
        return (c["x"], c["y"])
    except (OSError, subprocess.TimeoutExpired, ValueError, KeyError, TypeError):
        return None


def start_lock() -> None:
    """Start the lock screen so it outlives whoever asked. The after-saver timers run this from a short-lived
    systemd-run service, and systemd kills everything left in that service's cgroup when it returns (setsid and
    new sessions don't leave a cgroup), so a plain child process took the lock screen down with it. Hyprland
    starts it the way Super+L does; without Hyprland, a scope of its own keeps it alive."""
    env = session_env()
    if env.get("HYPRLAND_INSTANCE_SIGNATURE"):
        r = subprocess.run(["hyprctl", "dispatch", 'hl.dsp.exec_cmd("starchaser lock")'],
                           capture_output=True, text=True, env=env)
        if r.returncode == 0 and "error" not in (r.stdout + r.stderr).lower():
            return
    if shutil.which("systemd-run") and subprocess.run(
            ["systemd-run", "--user", "--scope", "--collect", "--quiet", "starchaser", "lock"],
            capture_output=True, env=env).returncode == 0:
        return
    subprocess.Popen(["starchaser", "lock"], start_new_session=True, env=env)


def act(action: str) -> None:
    if action == "screens-off":
        away_lock()   # Lock before the VM screen-off guard, too.
        # virtio-gpu never darkens its screens (VIRTUAL_GPU): closing the screensaver there only faked activity and
        # restarted the idle cycle (saver, stop, saver again), and the lock / sleep timers kept after the saver found
        # it gone and did nothing. The screensaver stays until you come back or those timers close it.
        if VIRTUAL_GPU:
            return
        # The screensaver can't stay up behind dark screens (it quits when the displays change; pausing it makes
        # Hyprland show "not responding"), and closing its window makes Hyprland fake a pointer move that hypridle
        # takes for you coming back. So: close it first, let that fake activity pass, then turn the screens off.
        # The "wake" listener (hypridle_conf) re-arms 5 s later, so your real return still wakes them.
        if saver_on(load()) and subprocess.run(["systemctl", "--user", "is-active", "--quiet", SAVER_UNIT], capture_output=True).returncode == 0:
            before = cursor_pos()
            keep_timers("screens-off")
            subprocess.run(SAVER_STOP.split(), capture_output=True)
            time.sleep(2)
            start = cursor_pos()
            # moved in those 2 seconds: you're back, so the screens stay on (hypridle's own timer still counts)
            if before is not None and start is not None and start != before:
                KEEP_TIMERS.unlink(missing_ok=True)
                stop_after_saver()
                return
            dpms(False)
            # Until that listener re-arms, nothing wakes the screens: a mouse move in those seconds left them dark
            # (a second move later worked). Watch the pointer for that long and wake them if it moves. This only
            # reads where the pointer is; it never moves it.
            if start is not None:
                for _ in range(16):
                    time.sleep(0.5)
                    now = cursor_pos()
                    if now is not None and now != start:
                        dpms(True)
                        break
            return
        dpms(False)
        return
    if action == "lock":
        # Lock first, then close the screensaver, so it never ends on an unlocked desktop.
        start_lock()
        # starchaser lock waits up to about 10 s for its lock screen and starts the backup lock itself when it
        # doesn't come up, so wait past that: this fallback is for a starchaser lock that never ran at all.
        # The lock screen is asked (lock_is_up: two programs) at once, then when its mark (LOCK_SECURE) is there, and
        # every 2 s without one (the backup lock leaves none); the mark is a file, looked at four times a second.
        deadline, asked = time.monotonic() + 12, None
        while True:
            if asked is None or LOCK_SECURE.exists() or own_hyprlock() or time.monotonic() - asked >= 2:
                asked = time.monotonic()
                if lock_is_up():
                    deadline = 0
                    break
            if time.monotonic() > deadline:
                break
            time.sleep(0.25)
        if deadline:
            # never leave the desktop open: fall back to hyprlock, and say so
            print("starchaser power: the lock screen didn't come up; using the plain lock screen", file=sys.stderr)
            if shutil.which("hyprlock") and not own_hyprlock():
                env = session_env()
                if env.get("HYPRLAND_INSTANCE_SIGNATURE"):
                    subprocess.run(["hyprctl", "dispatch", 'hl.dsp.exec_cmd("hyprlock")'], capture_output=True, env=env)
                else:
                    subprocess.Popen(["hyprlock"], start_new_session=True, env=env)
            # say it locked only once the plain lock screen is really up (it can fail too, say with its settings gone)
            time.sleep(1)               # one that can't start quits within this, so a pid seen after it is a lock
            for _ in range(8):
                if own_hyprlock():
                    title, body = ("The lock screen didn't start",
                                   "Starchaser used its plain lock screen instead. Unlock it with your password as usual.")
                    break
                time.sleep(0.25)
            else:
                title, body = ("Your computer isn't locked",
                               "The lock screen didn't start. Try locking again, or log out before you leave the computer.")
            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", "-u", "critical", "-i", "dialog-warning", title, body],
                           capture_output=True, env=session_env())
        if saver_on(load()):
            if subprocess.run(["systemctl", "--user", "is-active", "--quiet", SAVER_UNIT], capture_output=True).returncode == 0:
                keep_timers("lock")
            subprocess.run(SAVER_STOP.split(), capture_output=True)
        return
    if saver_on(load()):
        subprocess.run(SAVER_STOP.split(), capture_output=True)
    if action == "sleep":
        suspend(load())


def suspend(s: dict, ready=None) -> bool:
    """Sleep now (the sleep timer, the lid, the power button). With "Lock when the computer goes to sleep" on, the
    lock screen comes up first: act("lock") waits for it and falls back to the plain lock, so the sleeps Starchaser
    starts itself don't depend on hypridle running (its before-sleep lock covers the others)."""
    if s["lockOnSleep"]:
        act("lock")
    if ready is not None and not ready():
        return False
    return subprocess.run(["systemctl", "suspend"]).returncode == 0


def start_idle() -> None:
    """At login (Hyprland's autostart): bring hypridle.conf up to date with this version of Starchaser, then become
    hypridle. An update changes what the file should say (the virtio-gpu guard, for one), but the file was only
    rewritten when a Power setting changed, so an updated computer kept the old one. A file edited by hand is kept
    (refresh_idle). Whatever goes wrong while rewriting, hypridle still starts with the file that is there."""
    try:
        has_battery, _, _ = power_supplies()
        if refresh_idle(hypridle_conf(load(), has_battery)) == "kept":
            print(f"starchaser power: kept your own {IDLE}; this version's copy is {IDLE}.starchaser-new", file=sys.stderr)
    except Exception as e:
        print(f"starchaser power: hypridle.conf not refreshed: {e}", file=sys.stderr)
    os.execvp("hypridle", ["hypridle"])


def profile_data_command(argv: list) -> None:
    """Recurring export never runs the general get command's timer repair or hardware probes."""
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import starchaser_settings_schema as schema

    def read():
        try:
            if SETTINGS.is_symlink():
                raise ValueError("Linked settings file.")
            raw = schema.loads(SETTINGS.read_bytes())
        except FileNotFoundError:
            raw = {}
        schema.require(isinstance(raw, dict))
        for src in SOURCES:
            schema.require(isinstance(raw.get(src, {}), dict))
        return raw

    def portable(raw):
        return schema.payload("power-profiles", {src: raw.get(src, {}).get("profile", PROFILE_DEFAULTS[src]["profile"])
                                                  for src in SOURCES})

    try:
        if argv == ["export-profiles"]:
            print(json.dumps(portable(read()), sort_keys=True))
            return
        if argv == ["profile-state"]:
            current, available = profiles()
            print(json.dumps({"profile": current, "profiles": available}))
            return
        if argv != ["apply-profiles", "--stdin"]:
            usage("Use export-profiles, profile-state, or apply-profiles --stdin.")
        data = schema.payload("power-profiles", schema.loads(sys.stdin.buffer.read(schema.MAX_BYTES + 1)))
        _, available = profiles()
        if any(value and value not in available for value in data.values()):
            raise ValueError("Unavailable power mode.")
        SETTINGS.parent.mkdir(parents=True, exist_ok=True)
        lock_fd = os.open(SETTINGS.parent / ".power.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
        with os.fdopen(lock_fd, "w") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            raw = read()
            portable(raw)  # Refuse broken local choices rather than overwriting them.
            for src, value in data.items():
                raw.setdefault(src, {})["profile"] = value
            fd, tmp = tempfile.mkstemp(dir=SETTINGS.parent, prefix=".power.", suffix=".tmp")
            try:
                with os.fdopen(fd, "w") as out:
                    out.write(json.dumps(raw, sort_keys=True, indent=2) + "\n")
                    out.flush()
                    os.fsync(out.fileno())
                os.replace(tmp, SETTINGS)
                directory = os.open(SETTINGS.parent, os.O_RDONLY | os.O_DIRECTORY)
                try:
                    os.fsync(directory)
                finally:
                    os.close(directory)
            finally:
                if os.path.exists(tmp):
                    os.unlink(tmp)
        value = data[current_source()]
        error = set_profile(value) if value else ""
        print(json.dumps({"ok": True, "note": "Saved, but the power mode can't change right now." if error else ""}))
    except (OSError, ValueError, TypeError, subprocess.SubprocessError):
        print("The saved power modes could not be read or applied. Check which modes are available here.", file=sys.stderr)
        sys.exit(1)


def main(argv: list) -> None:
    if argv[:1] and argv[0] in ("export-profiles", "profile-state", "apply-profiles"):
        profile_data_command(argv)
        return
    if argv[:1] in (["toggle-screensaver"], ["screensaver-state"]):
        if len(argv) != 1:
            sys.exit(takes_nothing_after("starchaser power", argv[0], argv))
        if argv[0] == "toggle-screensaver":
            main(["set", "screensaver.enabled", "no" if load()["screensaver"]["enabled"] else "yes"])
        print(json.dumps({"enabled": load()["screensaver"]["enabled"]}))
        return
    cmd = argv[0] if argv else "get"
    if cmd in ("get", "battery", "start-idle", "stop-idle", "stop-session", "restart-idle", "source-changed", "watch", "sleep-now", "shutdown-now", "button") and len(argv) > 1:
        sys.exit(takes_nothing_after("starchaser power", cmd, argv))
    if cmd == "set" and len(argv) < 3:
        sys.exit(usage_error("starchaser power", "set needs a setting and a value (for example: set ac.sleep 30)",
                             "set <setting> <value>"))
    if cmd == "end-session":
        if len(argv) != 2 or argv[1] not in ("logout", "reboot", "poweroff", "windows"):
            usage("Choose logout, reboot, or poweroff.")
        result = subprocess.run(["qs", "-p", str(Path.home() / ".config/quickshell/cockpit"), "ipc", "call", "cockpit", "endSession", argv[1]], check=False)
        sys.exit(result.returncode)
    if cmd == "stop-session":
        stop_session()
        return
    if cmd == "stop-idle":
        stop_idle()
        return
    if cmd == "start-idle" and len(argv) == 1:
        start_idle()
    s = load()
    import copy
    _LOADED.clear()
    _LOADED.update(copy.deepcopy(s))
    if cmd == "get":
        # a power.json from before the clamp can have the screensaver at or past a timer: fix it when Settings looks
        was_on, before = saver_on(s), dict(s["screensaver"])
        # the note goes out only on the read that made the change (the one that saves): Settings keeps showing it
        # until the next thing you do there, so "Start after" doesn't move without a word
        note = clamp_saver(s)
        if s["screensaver"] != before:
            save(s)
            apply_clamped(s, was_on)
        else:
            note = ""
        cur, names = profiles()
        limit, limit_by = saver_limit_by(s)
        has_battery, on_battery, pct = power_supplies()
        sleep_ready = subprocess.run(["systemctl", "is-enabled", "nvidia-suspend.service"],
                                     capture_output=True, text=True).stdout.strip()
        nvidia = Path("/proc/driver/nvidia").exists()
        lid = Path("/proc/acpi/button/lid")
        # An unreadable cache or error file must not hide all the other power settings.
        try:
            compat = saver_compat_note(s)
        except Exception:
            compat = ""
        try:
            error = saver_error()
        except Exception:
            error = ""
        print(json.dumps({**s, "profile": cur, "profiles": names,
                          "hasBattery": has_battery, "onBattery": on_battery, "batteryPercent": pct,
                          "hasLid": lid.is_dir() and any(lid.iterdir()),
                          "hypridle": subprocess.run(["pidof", "hypridle"], capture_output=True).returncode == 0,
                          "saverInstalled": Path(SAVER_BIN).exists(), "saverLimit": limit, "saverLimitBy": limit_by, "saverNote": note,
                          "saverCompat": compat, "saverError": error,
                          "saverRunning": subprocess.run(["systemctl", "--user", "is-active", "--quiet", SAVER_UNIT], capture_output=True).returncode == 0,
                          "previewRunning": preview_pid() is not None,
                          # screens are never turned off on virtio-gpu (see VIRTUAL_GPU): Settings says so
                          "virtualScreens": VIRTUAL_GPU,
                          # NVIDIA cards need nvidia-suspend/resume enabled or they can wake to a black screen
                          "sleepWarning": nvidia and sleep_ready != "enabled"}))
    elif cmd == "set" and len(argv) == 3:
        key, val = argv[1], argv[2]
        if key == "profile":
            available = profiles()[1]
            if val not in available:
                bad_value(key, "choose one of " + ", ".join(available) if available else "no power modes are available right now")
            err = set_profile(val)
            if err:
                sys.exit(err)
            ok_setting(key, val)
            return
        if key == "button":
            if val not in BUTTONS:
                bad_value(key, f"one of {', '.join(BUTTONS)}")
            s["button"] = val
            save(s)
            ok_setting(key, val)
            return
        if key == "lockWhenAway":
            s[key] = yes_no(key, val)
            save(s)
            apply_idle(s)
            ok_setting(key, val)
            return
        if key == "lockOnSleep":
            s["lockOnSleep"] = yes_no(key, val)
            s["lockOnSleepChosen"] = True         # the person's own choice now: kept over the default (on or off)
            save(s)
            apply_idle(s)
            ok_setting(key, val)
            return
        if key.startswith("screensaver."):
            field, c = key.split(".", 1)[1], dict(s["screensaver"])
            displays = None
            try:
                if field == "enabled":
                    c["enabled"] = yes_no(key, val)
                    c["autoOff"] = False         # the person's own choice now: never turned back on by itself
                elif field == "minutes":
                    c["minutes"] = int(val)
                    if c["minutes"] < 1:
                        raise ValueError
                elif field == "mode":
                    if val not in ("follow", *SAVER_MODES):
                        raise ValueError
                    c["mode"] = val
                elif field == "speed":
                    c["speed"] = float(val)
                    if not 0.25 <= c["speed"] <= 3:
                        raise ValueError
                elif field == "stars":
                    c["stars"] = int(val)
                    if not 100 <= c["stars"] <= 30000:
                        raise ValueError
                elif field == "fps":
                    c["fps"] = int(val)
                    if not 15 <= c["fps"] <= 144:
                        raise ValueError
                elif field == "display":
                    if val != "all":
                        displays = saver_displays()          # asked once: the drop-in below reuses it
                        if displays is None:
                            sys.exit("Couldn't ask the screensaver which monitors it can use. Try again in a moment.")
                        if not val or val not in [d["id"] for d in displays]:
                            raise ValueError
                    c["display"] = val
                else:
                    usage(f"unknown setting: {key}")
            except ValueError:
                bad_value(key, f"not a valid value: {val}")
            limit, by = saver_limit_by(s)
            # a start time is refused as soon as it is picked, whether or not the screensaver is on: the help says
            # it must come sooner than every screens-off / lock / sleep timer
            if (c["enabled"] or field == "minutes") and limit and c["minutes"] >= limit:
                if not any(m < limit for m in SAVER_CHOICES):      # 1 minute: no start time can come before it
                    sys.exit("The screensaver needs a longer wait before the screens turn off, lock or sleep. "
                             "Set those to 2 minutes or more in Settings > Power.")
                sys.exit(f"The screensaver has to start before {by} ({dur(limit)}). "
                         f"Pick a time shorter than {dur(limit)}.")
            was_on = saver_on(s)
            s["screensaver"] = c
            save(s)
            if field == "minutes" and was_on and saver_on(s):
                # the start time is only in hypridle.conf, not the service's command line: skip rebuilding that,
                # which asks the renderer for its displays (slow, or stuck when the renderer hangs)
                apply_idle(s)
            else:
                apply_saver(s, displays)
            ok_setting(key, val)
            return
        if key in ("screens", "lock", "sleep"):            # v1 form: plugged-in
            key = "ac." + key
        src, _, field = key.partition(".")
        if src not in SOURCES or field not in PROFILE_DEFAULTS["ac"]:
            usage(f"unknown setting: {key}")
        if field in ("screens", "lock", "sleep"):
            if not val.isdigit():
                print(f"starchaser power: {key} must be whole minutes, 0 = never, not {val!r} "
                      "(nothing was changed)", file=sys.stderr)
                sys.exit(2)
            s[src][field] = int(val)
            was_on = saver_on(s)
            note = clamp_saver(s)
            save(s)
            apply_clamped(s, was_on)
            ok_setting(key, val)
            if note:
                print(note)
        elif field == "lid":
            if val not in LIDS:
                bad_value(key, f"one of {', '.join(LIDS)}")
            s[src][field] = val
            save(s)
            ok_setting(key, val)
        elif field == "profile":
            if val not in ("", "power-saver", "balanced", "performance"):
                bad_value(key, "choose a saved power mode from the supported choices")
            if val and val not in profiles()[1]:
                sys.exit("That power mode is not available here.")
            s[src][field] = val
            save(s)
            if current_source() == src and val:
                err = set_profile(val)
                if err:          # the choice is saved; it applies the next time the power source changes
                    sys.exit("Saved, but " + err[0].lower() + err[1:])
            ok_setting(key, val)
    elif cmd == "battery":
        st = []
        has, on_battery, pct = power_supplies(st)
        print(json.dumps({"has": has, "percent": pct, "status": st[0] if st else "", "onBattery": on_battery, "timeLeft": battery_estimate()}))
    elif cmd == "screensaver" and len(argv) == 2:
        saver_cmd(s, argv[1])
    elif cmd == "watch":
        watch_power()
    elif cmd == "sleep-now":
        return 0 if suspend(s) else 1
    elif cmd == "shutdown-now":
        # The critical-battery action (3%): a clean shutdown, not a suspend. No lock first; nothing stays in RAM.
        return 0 if subprocess.run(["systemctl", "poweroff"]).returncode == 0 else 1
    elif argv == ["idle", "reset"]:
        reset_idle_deadlines()
    elif cmd == "idle" and len(argv) in (3, 4):
        # "after-saver": scheduled when the screensaver started; you coming back ends the screensaver, so if it's
        # not running any more and neither the lock screen nor dark screens took over from it, you're here: do
        # nothing (in case the timer wasn't canceled)
        if len(argv) == 4 and argv[3] == "after-saver" and not still_away():
            return
        if argv[1] not in (*SOURCES, "any") or argv[2] not in ("screens-off", "lock", "sleep"):
            usage("idle needs ac, battery or any, then screens-off, lock or sleep")
        idle_deadline(argv[1], argv[2])
        if argv[1] in ("any", current_source()):
            act(argv[2])
    elif cmd == "restart-idle":
        # Settings' "Start it now" when the step-away service isn't running, and every sign-in (hyprland.lua): its
        # settings brought up to date (a hand-edited file is kept) and it started
        apply_idle(s, refresh=True)
        time.sleep(1)
        if subprocess.run(["pidof", "hypridle"], capture_output=True).returncode:
            sys.exit("Couldn't start it. Logging out and back in starts it again.")
    elif cmd == "source-changed":
        err = source_changed(s)
        if err:
            sys.exit(err)
        src = current_source()
        print(f"{src}: power mode {s[src].get('profile') or 'unchanged'}")
    elif cmd == "lid" and len(argv) == 2:
        if argv[1] == "close":
            apply_lid(s)
        elif argv[1] == "open":
            LID_OPENED.touch()
            LID_RESLEEP.unlink(missing_ok=True)
            LID_OFF.unlink(missing_ok=True)
            dpms(True)
        elif argv[1] == "resume":
            resume_lid()
        elif argv[1] == "reapply":                 # internal: hypridle woke every screen (see hypridle_conf)
            lid_reapply()
        else:
            usage("lid: close, open, resume or reapply")
    elif cmd == "button":
        b = s["button"]
        if b in ("menu", "ask"):
            # Locked (decided 2026-10-19 #1): the menu can't show over the lock screen, so the lock screen shows
            # Sleep / Restart / Shut down itself (Cancel selected). Nothing it shows unlocks. A lock that can't
            # show them (the backup lock) gets nothing: the menu would only open, unseen, behind it.
            if lock_is_up():
                lock_power_choices()
                return
            page = "power-key" if b == "ask" else "power"
            # The menu's program can't run at all (126/127: missing, or its libraries are, after a bad change): no
            # choices can show, and holding the button would cut the power. Shut down cleanly, as the button does on
            # a computer without a desktop (QA 20261104-1217 005: a short press did nothing). Anything else, a slow
            # or busy menu included, is never a reason to shut down.
            try:
                cant_run = subprocess.run([str(Path.home() / ".config/keybinds/toggle.sh"), page], start_new_session=True,
                                          stdin=subprocess.DEVNULL, timeout=60).returncode in (126, 127)
            except subprocess.TimeoutExpired:
                cant_run = False
            except OSError:
                cant_run = True
            if cant_run:
                subprocess.run(["systemctl", "poweroff"])
        elif b == "sleep":
            suspend(s)
        elif b == "poweroff":
            subprocess.run(["systemctl", "poweroff"])
    else:
        usage("unknown command or wrong number of arguments: " + " ".join(argv))


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]) or any(a in ("-h", "--help") for a in sys.argv[2:]):      # usage on request is not an error
        print(__doc__)
        sys.exit(0)
    try:
        sys.exit(main(sys.argv[1:]))
    except FileNotFoundError as e:
        # a helper program that isn't installed: one plain line, never a Python traceback (Settings reads this too)
        sys.exit(f"starchaser power: {e.filename or 'a needed program'} isn't installed on this computer.")
