#!/usr/bin/env python3
# summary: Read or change screen layouts and display settings.
"""starchaser displays: read and change the screen layout (where each screen's picture sits).

    starchaser displays get                 monitors as JSON (for Settings > Displays)
    starchaser displays init [--force]      write monitors.lua from the current live layout; --force
                                            replaces one already there
    starchaser displays apply <file|-> [--timeout N]
                                            write a new layout (JSON list, see below), keep the old one, reload;
                                            with --timeout, revert by itself after N seconds unless confirmed
                                            (survives Settings closing or the screen going dark)
    starchaser displays confirm             keep the new layout (drops the backup)
    starchaser displays revert              go back to the layout before the last apply, reload
    starchaser displays watch               recover the remaining screen when a screen is unplugged
    starchaser displays sync                tell the taskbar and older apps which screen is the main one (at sign-in)
    starchaser displays migrate             bring monitors.lua (and its backup) up to date; every other command does
                                            this first too (starchaser user refresh runs it, also at sign-in)
    starchaser displays hdr <output> off|on|game
                                            HDR for one screen (one whose screen says it can show it): on = always,
                                            game = only while Game mode is on (starchaser game reads it), off = never.
                                            Kept by the screen's description.

Layout JSON: [{"desc": "...", "mode": "3440x1440@239.99", "x": 400, "y": 1080, "scale": 1,
               "transform": 0, "enabled": true, "primary": false}, ...]

Every screen has a taskbar. The main screen (at most one) gets the background-app status icons, volume control,
keyboard-layout indicator and optional CPU/GPU temperature readouts, the pointer at sign-in (only then: plugging
a screen in or picking a main screen never moves it), workspace 1, and the screen that games and older apps treat
as the main one.
With none marked, those taskbar features appear on the largest screen and the rest stay as they are.
Screens are matched by description (make, model, serial), so the layout survives a screen moving to another port.
"""
# Implementation note (kept out of --help): the desktop loads the saved layout (monitors.lua) from hyprland.lua
# after its generic monitor rule:
#     local mon_ok, mon_err = pcall(dofile, os.getenv("HOME") .. "/.config/hypr/monitors.lua")
#     if not mon_ok then print("monitors.lua not applied: " .. tostring(mon_err)) end
import fcntl
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import time
import uuid
from pathlib import Path

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

safe_streams()

HOME = Path.home()
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", HOME / ".config"))
LAYOUT = CONFIG / "hypr/monitors.lua"
BACKUP = CONFIG / "hypr/monitors.lua.prev"
PENDING = CONFIG / "hypr/monitors.lua.pending"   # {"id", "deadline", "before"} of the unconfirmed apply
COCKPIT = CONFIG / "starchaser/cockpit.json"
DISPLAYS = CONFIG / "starchaser/displays.json"      # {"hdr": {description: "off" | "on" | "game"}}
HDR_MODES = ("off", "on", "game")


def write_atomic(path: Path, text: str) -> None:
    """Write a whole file or nothing: temp file, flush, fsync, then rename over the original."""
    path.parent.mkdir(parents=True, exist_ok=True)         # monitors.lua on a desktop that has no ~/.config/hypr yet
    tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    with open(tmp, "w") as f:
        f.write(text)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)


BROKEN_KEPT = ""            # the set-aside file's name, named once on stderr (settings() reads per monitor)


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


def settings() -> dict:
    """The saved display choices. A file that can't be read, or isn't the shape of one, is kept aside as
    displays.json.broken and the live monitor data answers on its own (never a traceback)."""
    global BROKEN_KEPT
    try:
        raw = json.loads(DISPLAYS.read_text())
    except FileNotFoundError:
        return {}
    except (OSError, ValueError, RecursionError):
        raw = None
    if raw is not None and isinstance(raw, dict):
        return raw
    if not BROKEN_KEPT:
        keep_broken(DISPLAYS)
        if BROKEN_KEPT:
            print(f"starchaser displays: the settings in displays.json couldn't be read and were kept as "
                  f"{BROKEN_KEPT}; the displays are shown without them.", file=sys.stderr)
    return {}


def hdr_settings(st: dict) -> dict:
    """The per-screen HDR map in the saved settings: a damaged shape reads as none saved."""
    h = st.get("hdr")
    return h if isinstance(h, dict) else {}


def hdr_capable(name: str) -> bool:
    """The screen's EDID has an HDR static metadata block (CTA extension, extended tag 6) listing PQ or HLG.
    (sysfs reports edid with size 0 even when it holds data: read it.)"""
    for f in Path("/sys/class/drm").glob(f"card*-{name}/edid"):
        try:
            edid = f.read_bytes()
        except OSError:
            continue
        for i in range(128, len(edid), 128):
            b = edid[i:i + 128]
            if len(b) < 4 or b[0] != 0x02:
                continue
            p = 4
            while p < b[2] and p < len(b):
                tag, ln = b[p] >> 5, b[p] & 31
                if tag == 7 and ln >= 2 and p + 2 < len(b) and b[p + 1] == 6:
                    return bool(b[p + 2] & 0b1100)
                p += ln + 1
    return False
PRIMARY_TAG = "-- primary: "
HEADER = "-- managed by starchaser-displays (Settings > Displays). Monitors matched by description.\n"


def hypr_command(*args) -> subprocess.CompletedProcess:
    env = dict(os.environ)
    if not env.get("HYPRLAND_INSTANCE_SIGNATURE"):     # run from a tty / ssh: find the running instance
        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
    try:
        return subprocess.run(["hyprctl", *args], capture_output=True, text=True, timeout=10, env=env)
    except FileNotFoundError:                          # no hyprctl at all: the same as a desktop that is not answering
        return subprocess.CompletedProcess(["hyprctl", *args], 127, "", "hyprctl is not installed")


def hypr(*args) -> str:
    return hypr_command(*args).stdout


def log_display_failure(raw: str) -> None:
    # Settings displays stderr verbatim, so send diagnostics straight to the journal.
    try:
        subprocess.run(["logger", "-t", "starchaser-displays"], input="(log) " + raw,
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True, timeout=2)
    except (OSError, subprocess.TimeoutExpired):
        pass


def hypr_eval(script: str) -> None:
    """Hyprland can reject Lua in its output while still exiting 0."""
    try:
        result = hypr_command("eval", script)
    except (OSError, subprocess.TimeoutExpired) as e:
        log_display_failure(str(e))
        sys.exit("starchaser displays: The display change wasn't accepted. Nothing was changed.")
    out = (result.stdout + result.stderr).strip()
    if result.returncode != 0 or any(word in out.lower() for word in ("error", "unknown", "invalid")):
        log_display_failure(out)
        sys.exit("starchaser displays: The display change wasn't accepted. Nothing was changed.")


def pending() -> dict:
    try:
        return json.loads(PENDING.read_text())
    except (OSError, ValueError, RecursionError):
        return {}


def last_outcome():
    try:
        return json.loads(PENDING.with_suffix('.outcome').read_text())
    except (OSError, ValueError):
        return {}


def drop_pending(outcome="restored") -> None:
    record = pending()
    if record:
        record.update(outcome=outcome)
        write_atomic(PENDING.with_suffix('.outcome'), json.dumps(record))
    PENDING.unlink(missing_ok=True)


class layout_lock:
    """One lock for everything that touches monitors.lua, its backup and the pending record (apply, the watchdog,
    confirm, revert, settle, hdr): a Keep that lands while the watchdog is half-way through going back must not
    report "kept" over the old layout."""
    def __enter__(self):
        LAYOUT.parent.mkdir(parents=True, exist_ok=True)
        self.f = open(LAYOUT.parent / ".monitors.lock", "w")
        fcntl.flock(self.f, fcntl.LOCK_EX)
        return self

    def __exit__(self, *a):
        self.f.close()


def settle_stale() -> bool:
    """An apply still waiting for Keep whose countdown is long over: its watchdog never ran (the computer was
    restarted, the power went, the session ended during the countdown). Go back to the layout before it, as the
    watchdog would have, so the unconfirmed layout doesn't stay for good and Settings doesn't show a Keep box that
    can't be answered. Run at login (sync) and before every get. True when it went back."""
    with layout_lock():
        p = pending()
        if not (PENDING.exists() and BACKUP.exists()):
            if PENDING.exists() and not BACKUP.exists():
                drop_pending()                  # nothing to go back to: just the leftover record
            return False
        try:
            deadline = float(p.get("deadline", 0))
        except (TypeError, ValueError):
            deadline = 0
        if p.get("deadline") == 0 or deadline > time.time() - 3:   # zero means Apply had no countdown
            return False
        BACKUP.replace(LAYOUT)
        drop_pending()
    reload_hypr()
    return True


def lua_str(v) -> str:
    """A Lua string literal for any text: quotes, backslashes and line breaks escaped, so a monitor description
    (which comes from the screen's EDID, or from a layout file) can't end the string and run as code."""
    out = []
    for ch in str(v):
        o = ord(ch)
        if ch in '"\\':
            out.append("\\" + ch)
        elif o < 32 or o == 127:
            out.append(f"\\{o:03d}")
        else:
            out.append(ch)
    return '"' + "".join(out) + '"'


def lua_comment(v) -> str:
    """Text for a -- comment: on one line (a line break would start real code). Only line-breaking characters become
    spaces; other spacing stays as it is, so the "-- primary:" line still matches a description with two spaces."""
    return "".join(" " if ord(ch) < 32 or ord(ch) == 127 or ch in "\x85  " else ch for ch in str(v))


# A screen with no description (no EDID: a headless output, some KVM switches and cheap adapters) is matched by its
# connector name instead, kept as "name:<connector>" where a description goes, so it can still be laid out and kept.
NAME_ONLY = "name:"


def output_of(m: dict) -> str:
    """The hl.monitor output for a layout entry: its description, or its connector for a screen without one."""
    d = m["desc"]
    return d[len(NAME_ONLY):] if d.startswith(NAME_ONLY) else f"desc:{d}"


def monitors() -> list:
    out = []
    raw = hypr("monitors", "all", "-j")
    try:
        listed = json.loads(raw)             # a missing socket prints its complaint as text, not JSON
    except ValueError:
        listed = None
    if not isinstance(listed, list):
        sys.exit("starchaser displays: Hyprland is not answering (is it running?)")
    by_id = {str(m['id']): m['name'] for m in listed if 'id' in m}
    connectors = {m['name'] for m in listed}
    for m in listed:
        mirror = m.get('mirrorOf')
        mirror = by_id.get(str(mirror), mirror if mirror in connectors else '')
        w, h = m["width"], m["height"]
        lw, lh = w / m["scale"], h / m["scale"]
        if m["transform"] % 2 == 1:
            lw, lh = lh, lw
        # Hyprland lists the display's own preferred mode (its EDID's) first; the set below loses that order
        avail = m.get("availableModes") or []
        preferred = avail[0].replace("Hz", "").split("@")[0] if avail else ""
        desc = (m.get("description") or "").strip() or NAME_ONLY + m["name"]
        out.append({
            "name": m["name"], "desc": desc, "make": m.get("make", ""), "model": m.get("model", ""),
            "mode": f"{w}x{h}@{m['refreshRate']:.2f}", "width": w, "height": h, "refresh": round(m["refreshRate"], 2),
            "x": m["x"], "y": m["y"], "scale": m["scale"], "transform": m["transform"],
            "logicalWidth": round(lw), "logicalHeight": round(lh),
            "mirror": mirror,
            "enabled": not m.get("disabled", False), "focused": m.get("focused", False),
            "hdrCapable": hdr_capable(m["name"]), "hdr": hdr_settings(settings()).get(desc, "off"),
            "colorMode": m.get("colorManagementPreset", ""), "bitDepth": 10 if "2101010" in (m.get("currentFormat") or "") else 8,
            "preferred": preferred,             # "WxH", what Settings labels "(recommended)"
            "modes": sorted({md.replace("Hz", "") for md in avail},
                            key=lambda s: (-int(s.split("x")[0]) * int(s.split("x")[1].split("@")[0]), -float(s.split("@")[1]))),
        })
    return out


def snap_scale(mode: str, scale: float) -> float:
    """The scale Hyprland will really use for this mode. It only takes one that divides the resolution into whole
    pixels and otherwise picks the nearest that does, in steps of 1/120 (1.5 on 1280x800 becomes 1.6). Settings
    offers snapped values already; this keeps a layout from the command line or an old file the same, so positions
    worked out from the scale match the screen."""
    from fractions import Fraction
    try:
        scale = float(scale)
    except (TypeError, ValueError):
        return 1.0              # not a number at all: Hyprland's default rather than a broken monitors.lua
    try:
        w, h = (int(v) for v in mode.split("@")[0].split("x"))
    except (ValueError, AttributeError):
        return scale
    if w <= 0 or h <= 0 or scale <= 0 or ((w / scale).is_integer() and (h / scale).is_integer()):
        return scale
    base = round(scale * 120)
    for i in range(90):
        for n in (base + i, base - i):
            if n > 0 and (Fraction(w * 120, n).denominator == 1 and Fraction(h * 120, n).denominator == 1):
                # full precision: rounded to a few decimals (188/120 as 1.5667) it no longer divides evenly, and
                # Hyprland would refuse it again
                return n / 120
    return scale


def empty_mode(mode) -> bool:
    try:
        w, h = (int(float(v)) for v in str(mode).split("@")[0].split("x"))
        return w <= 0 or h <= 0
    except ValueError:
        return True


def fix_empty_modes(layout: list) -> None:
    """A display that was off at login reports a 0x0 mode (Hyprland starts its size at 0,0). Turned on with that,
    it would get mode = "0x0@..." in monitors.lua: use its own recommended mode at its fastest refresh instead."""
    if not any(m.get("enabled", True) and empty_mode(m.get("mode")) for m in layout):
        return
    live = {x["desc"]: x for x in monitors()}
    for m in layout:
        x = live.get(m.get("desc"))
        if not (m.get("enabled", True) and empty_mode(m.get("mode")) and x and x["modes"]):
            continue
        best = next((md for md in x["modes"] if x["preferred"] and md.startswith(x["preferred"] + "@")), x["modes"][0])
        m["mode"] = best
        m["scale"] = snap_scale(best, m.get("scale") or 1)


# The pointer starts on the main screen at login and is never moved there afterward (Starchaser never moves the
# pointer). Hyprland 0.56 warps it to cursor.default_monitor, forced past cursor.no_warps, the first time that screen
# is ADDED while the option is set: left set, plugging the main screen in (again, after login, or after Settings
# picked it) pulls the pointer over to it. So the option is set only on this Hyprland's first config load (no screens
# are up yet, and the start marker isn't written) and cleared on hyprland.start, which also writes the marker; a
# reload resets every option and skips the block. bin/starchaser-check-pointer accepts default_monitor only in this
# shape.
STARTED_MARKER = "starchaser-started"


def start_on_main_screen(output_lit: str) -> list:
    """The monitors.lua lines that put the pointer on the main screen at login only. output_lit is a Lua string
    literal (lua_str of the output)."""
    return [
        "do",
        '    local started = (os.getenv("XDG_RUNTIME_DIR") or "") .. "/hypr/" .. (os.getenv("HYPRLAND_INSTANCE_SIGNATURE") or "")'
        f' .. "/{STARTED_MARKER}"',
        '    local seen = io.open(started, "r")',
        "    if seen then",
        "        seen:close()",
        "    elseif #hl.get_monitors() == 0 then",
        f"        hl.config({{ cursor = {{ default_monitor = {output_lit} }} }})",
        '        hl.on("hyprland.start", function() hl.config({ cursor = { default_monitor = "" } }); '
        'local f = io.open(started, "w"); if f then f:close() end end)',
        "    end",
        "end",
    ]


# monitors.lua from before the block above: one top-level line (never indented, so the block's own line inside
# `elseif` is not taken for it) that kept cursor.default_monitor set all session
LUA_LIT = r'"(?:[^"\\\n]|\\.)*"'
OLD_DEFAULT_MONITOR = re.compile(r"^hl\.config\(\s*\{\s*cursor\s*=\s*\{\s*default_monitor\s*=\s*(" + LUA_LIT
                                 + r")\s*\}\s*\}\s*\)[ \t;]*$")


def migrate_text(text: str) -> str:
    """text with every old always-on default_monitor line swapped for start_on_main_screen's block (same screen)."""
    out, changed = [], False
    for line in text.split("\n"):
        m = OLD_DEFAULT_MONITOR.match(line)
        if m:
            out.extend(start_on_main_screen(m.group(1)))
            changed = True
        else:
            out.append(line)
    return "\n".join(out) if changed else text


def migrate_layouts() -> list:
    """Rewrite monitors.lua and its backup (revert puts the backup back) when they still have the old line. Run at
    the start of every starchaser displays command and by starchaser user refresh (also at sign-in, before Hyprland
    reads the file). Returns the files rewritten."""
    done = []
    if not (LAYOUT.exists() or BACKUP.exists()):
        return done
    with layout_lock():
        for path in (LAYOUT, BACKUP):
            try:
                text = path.read_text()
            except (OSError, UnicodeDecodeError):
                continue
            new = migrate_text(text)
            if new == text:
                continue
            tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
            with open(tmp, "w") as f:
                f.write(new)
                f.flush()
                os.fsync(f.fileno())
            shutil.copymode(path, tmp)
            tmp.replace(path)
            done.append(path)
    if LAYOUT in done:
        clear_live_default_monitor()
    return done


def clear_live_default_monitor() -> None:
    """The running session read the old line at login, so the option is still set in it: clear it now, not at the
    next sign-in. Best-effort: with no Hyprland running (sign-in, before the desktop starts) there is nothing to clear."""
    try:
        hypr_command("eval", 'hl.config({ cursor = { default_monitor = "" } })')
    except (OSError, subprocess.TimeoutExpired):
        pass


def mode_screens(live):
    """Order screens as the relative This/Other actions see them right now."""
    real = [dict(m) for m in live if m.get("name") != "FALLBACK" and not m.get("name", "").startswith("SunVD")]
    first = next((m for m in real if m.get("focused")), None)
    first = first or next((m for m in real if m["name"].startswith(("eDP", "LVDS"))), real[0] if real else None)
    if first is not None:
        real.remove(first)
        real.insert(0, first)
    return real


def current_mode(live):
    real = mode_screens(live)
    active = [m for m in real if m.get('enabled', True)]
    if len(active) > 1:
        return 'mirror' if any(m.get('mirror') for m in active) else 'extend'
    # Saved choices are relative to the focus at the time they were made. Enabling
    # Only the other screen moves focus there, making it This when the strip reopens.
    if active:
        index = real.index(active[0])
        return 'this' if index == 0 else 'other' if index == 1 else ''
    return ''


def mode_layout(mode: str, live: list) -> list:
    if mode not in ("extend", "mirror", "this", "other"):
        raise ValueError("Choose Extend, Mirror, Only this screen or Only the other screen.")
    real = mode_screens(live)
    if len(real) < 2:
        raise ValueError("Connect another screen first.")
    first = real[0]
    offset = 0
    for i, screen in enumerate(real):
        screen.update(enabled=(i == 0 if mode == "this" else i == 1 if mode == "other" else True),
                      primary=(i == 1 if mode == "other" else i == 0), mirror="", x=offset, y=0)
        if mode == "mirror" and i:
            screen.update(mirror=first["name"], x=0, y=0)
        if screen["enabled"]:
            offset += int(screen.get("logicalWidth", screen.get("width", 1920) / screen.get("scale", 1)))
    return real


def render(layout: list) -> str:
    lines = [HEADER]
    for m in layout:
        lines.append(f"-- {lua_comment(m.get('name', ''))} {lua_comment(m['desc'])}")
        if not m.get("enabled", True):
            lines.append(f'hl.monitor({{ output = {lua_str(output_of(m))}, disabled = true }})\n')
            continue
        lines.append("hl.monitor({")
        lines.append(f'    output    = {lua_str(output_of(m))},')
        lines.append(f'    mode      = {lua_str(m["mode"])},')
        lines.append(f'    position  = "{int(m["x"])}x{int(m["y"])}",')
        lines.append(f'    scale     = {snap_scale(m["mode"], m["scale"])!r},')   # repr: every digit, 1.5 stays 1.5
        if int(m.get("transform", 0)):
            lines.append(f'    transform = {int(m["transform"])},')
        if hdr_settings(settings()).get(m["desc"]) == "on":          # HDR for this screen, always
            lines.append('    cm        = "hdr",')
            lines.append('    bitdepth  = 10,')
        if m.get("mirror"):
            lines.append(f'    mirror    = {lua_str(m["mirror"])},')
        else:
            lines.append('    mirror    = "",')
        lines.append("})\n")
    prim = next((m for m in layout if m.get("primary") and m.get("enabled", True)), None)
    if prim:
        lines.append(f"{PRIMARY_TAG}{lua_comment(prim['desc'])}")
        lines.extend(start_on_main_screen(lua_str(output_of(prim))))
        lines.append(f'hl.workspace_rule({{ workspace = "1", monitor = {lua_str(output_of(prim))}, default = true }})\n')
    return "\n".join(lines)


def backup_text(before: list) -> str:
    """The layout to go back to: the live screens as they are now, plus the saved rules (and main-screen choice) for
    screens that aren't plugged in, which Hyprland doesn't list. Without them a Revert would forget those screens."""
    return with_unplugged(before)


def with_unplugged(layout: list) -> str:
    """render(layout) plus the saved rules (and main-screen choice) for screens the layout doesn't name: Settings
    only sends the screens plugged in now, and saving just those would forget where an unplugged one goes."""
    text = render(layout)
    try:
        saved = LAYOUT.read_text().splitlines()
    except (OSError, UnicodeDecodeError):
        return text
    live_outs = {lua_str(output_of(m)) for m in layout}
    blocks, tail, i = [], [], 0
    while i < len(saved):
        line = saved[i]
        if line.startswith(PRIMARY_TAG):
            tail = saved[i:]
            break
        if line.startswith("hl.monitor({"):
            j = i
            while j < len(saved) - 1 and not saved[j].rstrip().endswith("})"):
                j += 1
            chunk = saved[i:j + 1]
            found = re.search(r"\boutput\s*=\s*(" + LUA_LIT + ")", "\n".join(chunk))
            if found and found.group(1) not in live_outs:
                note = saved[i - 1] if i and saved[i - 1].startswith("-- ") and saved[i - 1] != HEADER.strip() else ""
                blocks.extend(([note] if note else []) + chunk + [""])
            i = j + 1
            continue
        i += 1
    if tail and any(m["desc"] == tail[0][len(PRIMARY_TAG):].strip() or (m.get("primary") and m.get("enabled", True))
                    for m in layout):
        tail = []                               # the main screen is in the layout (or another one is chosen now)
    if not blocks and not tail:
        return text
    extra = "\n".join(blocks)
    at = text.find("\n" + PRIMARY_TAG)
    if at >= 0:
        text = text[:at + 1] + extra + "\n" + text[at + 1:]
    else:
        text = text.rstrip("\n") + "\n\n" + extra
    if tail:
        text = text.rstrip("\n") + "\n\n" + "\n".join(tail)
    return text if text.endswith("\n") else text + "\n"


def primary_desc() -> str:
    try:
        for line in LAYOUT.read_text().splitlines():
            if line.startswith(PRIMARY_TAG):
                return line[len(PRIMARY_TAG):].strip()
    except OSError:
        pass
    return ""


def recovery_notice(name: str) -> None:
    subprocess.Popen(["sh", "-c", 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; exec starchaser notify --credential-fd=3 "$@" 3<"$token"', "sh", "-a", "Starchaser", "-i", "video-display",
                      "Your laptop screen was turned back on" if name.startswith(("eDP", "LVDS", "DSI"))
                      else "Your screen was turned back on",
                      "The other screen was disconnected. Your saved layout is kept for when it returns."],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


RECOVERED = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "starchaser-display-recovered"


def recover_screen() -> str:
    """A compositor fallback has no physical picture. Enable a connected screen without saving over the dock layout."""
    real = [m for m in monitors() if m["name"] != "FALLBACK" and not m["name"].startswith("HEADLESS-")]
    if not real or any(m["enabled"] for m in real):
        return ""
    chosen = next((m for m in real if m["name"].startswith(("eDP", "LVDS", "DSI"))), real[0])
    hypr_eval('hl.monitor({ output = ' + lua_str(output_of(chosen)) +
              ', mode = "preferred", position = "auto", scale = "auto", disabled = false })')
    try:
        write_atomic(RECOVERED, chosen["name"])
    except OSError:
        pass
    recovery_notice(chosen["name"])
    return chosen["name"]


def attach_reconnected(name: str) -> str:
    """Attach an isolated returning screen to a current edge, keeping the saved dock layout."""
    if PENDING.exists():
        return ""
    live = [m for m in monitors() if m['enabled'] and not m.get('mirror') and m['name'] != 'FALLBACK']
    screen = next((m for m in live if m['name'] == name), None)
    others = [m for m in live if m['name'] != name]
    if not screen or not others:
        return ""

    def rect(m):
        return m['x'], m['y'], m['logicalWidth'], m['logicalHeight']

    def overlaps(a, b):
        x, y, w, h = a
        ox, oy, ow, oh = b
        return x < ox + ow and ox < x + w and y < oy + oh and oy < y + h

    def touches(a, b):
        x, y, w, h = a
        ox, oy, ow, oh = b
        return ((x + w == ox or ox + ow == x) and y < oy + oh and oy < y + h
                or (y + h == oy or oy + oh == y) and x < ox + ow and ox < x + w)

    r = rect(screen)
    boxes = [rect(m) for m in others]
    if any(touches(r, box) or overlaps(r, box) for box in boxes):
        return ""
    x, y, w, h = r
    candidates = []
    for ox, oy, ow, oh in boxes:
        cx = ox if x + w <= ox else ox + ow - w if x >= ox + ow else x
        cy = oy if y + h <= oy else oy + oh - h if y >= oy + oh else y
        for nx, ny in ((ox - w, cy), (ox + ow, cy), (cx, oy - h), (cx, oy + oh)):
            box = nx, ny, w, h
            if not any(overlaps(box, other) for other in boxes):
                candidates.append((nx, ny))
    if not candidates:
        return ""
    nx, ny = min(candidates, key=lambda point: abs(point[0] - x) + abs(point[1] - y))
    # Pin the other live screens too: an explicit position must not displace an auto-positioned screen.
    rules = []
    for m in others + [dict(screen, x=nx, y=ny)]:
        rules.append(f'hl.monitor({{ output = {lua_str(m["name"])}, mode = {lua_str(m["mode"])}, '
                     f'position = "{int(m["x"])}x{int(m["y"])}", scale = {m["scale"]!r}, '
                     f'transform = {int(m["transform"])}, cm = {lua_str(m.get("colorMode") or "srgb")}, '
                     f'bitdepth = {int(m.get("bitDepth", 8))} }})')
    hypr_eval("; ".join(rules))
    return name


def watch() -> None:
    runtime = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
    with (runtime / "starchaser-displays-watch.lock").open("w") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return
        watch_events()


def watch_events() -> None:
    env = dict(os.environ)
    runtime = Path(env.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
    sig = env.get("HYPRLAND_INSTANCE_SIGNATURE", "")
    if not sig:
        return
    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as events:
        events.connect(str(runtime / "hypr" / sig / ".socket2.sock"))
        sync()
        with events.makefile() as lines:
            for line in lines:
                event, _, name = line.strip().partition(">>")
                if event not in ("monitorremoved", "monitoradded", "configreloaded"):
                    continue
                if event == "monitoradded" and RECOVERED.exists():
                    try:
                        recovered = RECOVERED.read_text()
                    except OSError:
                        recovered = ""
                    if recovered and any(m["enabled"] and m["name"] not in (recovered, "FALLBACK")
                           and not m["name"].startswith("HEADLESS-") for m in monitors()):
                        RECOVERED.unlink(missing_ok=True)
                        reload_hypr()
                if event == "monitoradded":
                    attach_reconnected(name)
                elif event == "configreloaded":
                    for m in monitors():
                        attach_reconnected(m['name'])
                sync()


def sync() -> str:
    """Point the cockpit (cockpit.json "main", by connector) and XWayland at the primary display."""
    recover_screen()
    desc = primary_desc()
    name = next((m["name"] for m in monitors() if m["desc"] == desc and m["enabled"]), "") if desc else ""
    COCKPIT.parent.mkdir(parents=True, exist_ok=True)
    # the same lock file starchaser theme's cockpit writers hold: a taskbar change made at the same moment
    # must not be put back by this read-change-write
    with open(COCKPIT.parent / ".cockpit.lock", "w") as lk:
        fcntl.flock(lk, fcntl.LOCK_EX)
        try:
            cfg = json.loads(COCKPIT.read_text())
        except (OSError, ValueError, RecursionError):
            cfg = {"edge": "left"}
        if cfg.get("main", "") != name:
            if name:
                cfg["main"] = name
            else:
                cfg.pop("main", None)
            write_atomic(COCKPIT, json.dumps(cfg, indent=2) + "\n")
    if os.environ.get("DISPLAY") and shutil.which("xrandr"):
        subprocess.run(["xrandr", "--output", name, "--primary"] if name else ["xrandr", "--noprimary"],
                       capture_output=True, timeout=10)
    return name


def reload_hypr() -> str:
    hypr("reload")
    return hypr("configerrors").strip()


def display_setting_error(raw: str) -> str:
    log_display_failure(raw)
    fields = {"transform": "rotation", "scale": "size of text and apps",
              "mode": "resolution or refresh rate", "position": "position",
              "cm": "HDR / color", "bitdepth": "HDR / color", "hdr": "HDR / color",
              "vrr": "adaptive sync"}
    field = re.search(r"\b(transform|scale|mode|position|cm|bitdepth|hdr|vrr)\b", raw, re.I)
    detail = f" (the {fields[field.group().lower()]})" if field else ""
    return f"A display setting wasn't accepted{detail}. Pick a different one, or go back to your last layout."


def main(argv: list, owner="settings", mode="") -> None:
    cmd = argv[0] if argv else "get"
    if cmd in ("confirm", "revert", "sync", "migrate", "watch") and len(argv) > 1:
        usage(f"{cmd} takes no more arguments")
    if cmd == "init" and any(a != "--force" for a in argv[1:]):
        usage("init only takes --force")
    migrated = migrate_layouts()
    if cmd == "migrate":
        print(json.dumps({"migrated": [str(p) for p in migrated]}))
        return
    if cmd == "get":
        if len(argv) > 1:
            usage("get takes no more arguments")
        if settle_stale():      # went back: point the cockpit and XWayland at that layout's main screen too
            sync()
        with layout_lock():
            p = pending() if BACKUP.exists() else {}
            live = monitors()
            print(json.dumps({"monitors": live, "pending": BACKUP.exists(), "primary": primary_desc(),
                              "deadline": p.get("deadline", 0), "before": p.get("before", []),
                              "owner": p.get("owner", "settings"), "changeId": p.get("id", ""),
                              "mode": p.get("mode", "") if p else current_mode(live),
                              "outcome": last_outcome()}))
    elif cmd == "mode" and len(argv) == 2:
        import io
        try:
            layout = mode_layout(argv[1], monitors())
        except ValueError as error:
            print(json.dumps({"ok": False, "errors": str(error)}))
            sys.exit(1)
        previous_input = sys.stdin
        try:
            sys.stdin = io.StringIO(json.dumps(layout))
            main(["apply", "--timeout", "15", "-"], owner="screen-modes", mode=argv[1])
        finally:
            sys.stdin = previous_input
    elif cmd == "init":
        if LAYOUT.exists() and "--force" not in argv:
            sys.exit(f"starchaser displays: {LAYOUT} exists (use --force)")
        write_atomic(LAYOUT, render([{**m} for m in monitors()]))
        print(f"wrote {LAYOUT}")
    elif cmd == "apply":
        # strict: a misspelled option ("--timout 15") must not apply with no way back
        timeout, args, rest = 0, [], argv[1:]
        while rest:
            a = rest.pop(0)
            if a == "--timeout" or a.startswith("--timeout="):
                v = a.split("=", 1)[1] if "=" in a else (rest.pop(0) if rest else "")
                try:
                    timeout = int(v)
                except ValueError:
                    usage("--timeout needs a whole number of seconds")
                if not 1 <= timeout <= 600:
                    usage("--timeout has to be between 1 and 600 seconds")
            elif a.startswith("-") and a != "-":
                usage(f"apply doesn't know the option {a}")
            else:
                args.append(a)
        if not args:
            usage("apply needs a layout file, or - to read it from input")
        if len(args) > 1:
            usage("apply takes one layout file")
        # everything is read and checked before anything is written (no backup, no half-written monitors.lua)
        try:
            layout = json.loads(sys.stdin.read() if args[0] == "-" else Path(args[0]).read_text())
        except OSError as e:
            sys.exit(f"starchaser displays: can't open the layout file {args[0]}: {e.strerror or e}")
        except (UnicodeDecodeError, json.JSONDecodeError, RecursionError):
            # in words, not the parser's "Expecting value: line 1 column 1 (char 0)"
            sys.exit("starchaser displays: the layout isn't readable: it has to be JSON, a list of displays "
                     "(starchaser displays get shows one). Run 'starchaser displays --help' for more help.")
        if not isinstance(layout, list) or not layout or not all(isinstance(m, dict) for m in layout):
            sys.exit("starchaser displays: the layout has to be a list of displays. "
                     "Run 'starchaser displays --help' for more help.")
        if not any(m.get("enabled", True) for m in layout):
            sys.exit("starchaser displays: refusing a layout with no enabled monitor")
        # name what's missing in plain words (display 2 has no "mode"), not as a Python error
        for i, m in enumerate(layout, 1):
            need = ("desc", "mode", "x", "y", "scale") if m.get("enabled", True) else ("desc",)
            gone = [k for k in need if m.get(k) in (None, "")]
            if gone:
                who = f"display {i}" + (f" ({m['name']})" if m.get("name") else "")
                sys.exit(f"starchaser displays: {who} has no " + " or ".join(f'"{k}"' for k in gone)
                         + " in the layout. Run 'starchaser displays --help' for more help.")
            nums = [k for k in ("x", "y", "scale", "transform") if k in m and
                    (isinstance(m[k], bool) or not isinstance(m[k], (int, float)))]
            if nums or (m.get("enabled", True) and not m["scale"] > 0):
                who = f"display {i}" + (f" ({m['name']})" if m.get("name") else "")
                sys.exit(f"starchaser displays: {who} needs a number for " + " and ".join(f'"{k}"' for k in nums) if nums
                         else f"starchaser displays: {who} needs a scale above 0")
        fix_empty_modes(layout)
        try:
            render(layout)
        except (KeyError, TypeError, ValueError, AttributeError) as e:
            bad = e.args[0] if isinstance(e, KeyError) and e.args else str(e)
            sys.exit(f"starchaser displays: the layout has a missing or bad value ({bad})")
        with layout_lock():
            live = monitors()
            # A layout for no screen that is connected here is a mistake (a description is easy to mistype): it
            # would replace the saved rules and change nothing on screen. A screen that is only unplugged for now
            # is fine, as long as one of the layout's displays is connected.
            if not any(m.get("enabled", True) and any(e["desc"] == m["desc"] for e in live) for m in layout):
                sys.exit("starchaser displays: none of the displays in the layout is connected to this computer "
                         "(starchaser displays get shows the connected ones and their descriptions); nothing was changed")
            before = pending().get("before", [])
            if not BACKUP.exists():                   # the layout to return to if not confirmed
                prim = primary_desc()
                before = [{**m, "primary": m["desc"] == prim} for m in live]
                write_atomic(BACKUP, backup_text(before))
            write_atomic(LAYOUT, with_unplugged(layout))
            token = uuid.uuid4().hex
            # Keep the first live snapshot across unconfirmed applies, including ones without a countdown.
            # Written before reload so the dialog and every rollback use the same before-values.
            write_atomic(PENDING, json.dumps({"id": token, "deadline": time.time() + timeout if timeout else 0,
                                           "before": before, "owner": owner, "mode": mode}))
        err = reload_hypr()
        if err:
            err = display_setting_error(err)
        sync()
        if timeout > 0:                           # a watchdog that reverts unless confirm comes first
            subprocess.Popen([sys.executable, os.path.abspath(__file__), "watchdog", token, str(timeout)],
                             start_new_session=True, stdin=subprocess.DEVNULL,
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        print(json.dumps({"ok": not err, "errors": err}))
    elif cmd == "watchdog":                       # internal: watchdog <id> <seconds>
        time.sleep(float(argv[2]))
        with layout_lock():
            if not (pending().get("id") == argv[1] and BACKUP.exists()):   # confirmed, reverted, or another apply
                return
            BACKUP.replace(LAYOUT)
            drop_pending()
        reload_hypr()
        sync()
    elif cmd == "confirm":
        # nothing waiting: the watchdog went back (Keep pressed as the countdown ran out) or no change was
        # ever applied. Saying "kept" would be wrong either way, and Settings shows this line
        with layout_lock():
            if not BACKUP.exists():
                drop_pending()
                sys.exit("starchaser displays: No new layout is waiting to be kept. If it went back on its own, apply it again.")
            record = pending()
            saved = settings()
            saved['screenMode'] = record.get('mode', '')
            write_atomic(DISPLAYS, json.dumps(saved))
            BACKUP.unlink(missing_ok=True)
            drop_pending("kept")
        print("kept")
    elif cmd == "revert":
        with layout_lock():
            if not BACKUP.exists():
                sys.exit("starchaser displays: nothing to revert")
            drop_pending()
            BACKUP.replace(LAYOUT)
        reload_hypr()
        sync()
        print("reverted")
    elif cmd == "hdr" and len(argv) == 3 and argv[2] in HDR_MODES:
        live = monitors()
        if any(m["name"].startswith("SunVD") for m in live):
            sys.exit("starchaser displays: Not while a Moonlight stream is on: the screens are switched out for it. Try again after it ends.")
        m = next((x for x in live if x["name"] == argv[1] or x["desc"] == argv[1]), None)
        if not m:
            sys.exit(f"starchaser displays: no screen {argv[1]}")
        if argv[2] != "off" and not m["hdrCapable"]:
            sys.exit(f"starchaser displays: {m['name']} doesn't support HDR")
        st = settings()
        was_settings = DISPLAYS.read_text() if DISPLAYS.exists() else None     # put back if Hyprland refuses the change
        was_layout = LAYOUT.read_text() if LAYOUT.exists() else None
        if not isinstance(st.get("hdr"), dict):                 # a damaged map starts fresh, like hdr_settings reads it
            st["hdr"] = {}
        st["hdr"][m["desc"]] = argv[2]
        DISPLAYS.parent.mkdir(parents=True, exist_ok=True)
        write_atomic(DISPLAYS, json.dumps(st, indent=2) + "\n")
        # save the layout as it is now (with this screen's HDR in it), then switch the screen live
        prim = primary_desc()
        layout = [{**x, "primary": x["desc"] == prim} for x in live]
        # written whenever no apply waits for Keep, also on a fresh install with no monitors.lua yet (the live
        # layout, as apply keeps it): HDR On is only read back at login from monitors.lua
        with layout_lock():
            if not BACKUP.exists():
                write_atomic(LAYOUT, with_unplugged(layout))
        game_on = (Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "starchaser-game.json").exists()
        want = argv[2] == "on" or (argv[2] == "game" and game_on)
        rule = (f'hl.monitor({{ output = {lua_str(m["name"])}, mode = {lua_str(m["mode"])}, position = "{int(m["x"])}x{int(m["y"])}", '
                f'scale = {snap_scale(m["mode"], m["scale"])!r}, transform = {int(m["transform"])}, cm = "{"hdr" if want else "srgb"}", '
                f'bitdepth = {10 if want else 8} }})')
        # A single explicit position can move other auto-positioned screens and leave them blank. Pin their
        # live layout first, preserving their color settings, before applying this screen's HDR rule.
        pins = [
            (f'hl.monitor({{ output = {lua_str(x["name"])}, mode = {lua_str(x["mode"])}, position = "{int(x["x"])}x{int(x["y"])}", '
             f'scale = {snap_scale(x["mode"], x["scale"])!r}, transform = {int(x["transform"])}, '
             f'cm = {lua_str(x["colorMode"] or "srgb")}, bitdepth = {int(x["bitDepth"])} }})')
            for x in live if x["name"] != m["name"] and x.get("enabled", True)
        ]
        # color management is off unless a screen uses HDR (config/hypr/hyprland.lua says why): on before the screen
        # switches to HDR, off again after the last HDR screen is switched back
        cm_needed = any(v in ("on", "game") for v in hdr_settings(st).values())
        switched = False
        try:
            if want or cm_needed:
                hypr_eval("hl.config({ render = { cm_enabled = true } })")
            hypr_eval("\n".join(pins + [rule]))
            switched = True
            if not cm_needed:
                hypr_eval("hl.config({ render = { cm_enabled = false } })")
        except SystemExit:
            # the screen did not change, so neither the saved choice nor the layout file may say it did
            with layout_lock():
                for path, text in ((DISPLAYS, was_settings), (LAYOUT, was_layout)):
                    if text is None:
                        path.unlink(missing_ok=True)
                    elif not (path is LAYOUT and BACKUP.exists()):
                        write_atomic(path, text)
            # the screen itself switched when only the color-management step failed: do not claim it is as it was
            sys.exit("starchaser displays: " + ("This screen's HDR changed, but it couldn't be finished. Try the switch again."
                                                if switched else "Couldn't switch this screen's HDR. The screen is as it was."))
        print(json.dumps({"ok": True, "screen": m["name"], "hdr": argv[2], "live": "hdr" if want else "srgb"}))
    elif cmd == "watch":
        watch()
    elif cmd == "sync":
        settle_stale()          # at login: an apply nobody could answer before a restart goes back
        print(sync() or "Every screen has a taskbar. With none chosen as main, status icons for apps that keep running in the background (like music or downloads) appear on the largest screen.")
    else:
        if cmd == "hdr":
            usage("hdr needs a screen name and off, on or game, like: starchaser displays hdr DP-1 on")
        elif cmd == "apply":
            usage("wrong arguments for 'apply'")
        elif cmd in ("get", "init", "watchdog", "confirm", "revert", "sync", "migrate"):
            usage(f"wrong arguments for {cmd!r}")
        usage(f"unknown command {cmd!r}")


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 displays: {msg}\nRun 'starchaser displays --help' for more help.", file=sys.stderr)
    sys.exit(2)


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:
        main(sys.argv[1:])
    except OSError as error:        # a settings folder it may not read or write: say so, not a traceback
        sys.exit(f"starchaser displays: couldn't read or save the screen layout ({error.strerror}). "
                 "Check that you can write to ~/.config.")
