#!/usr/bin/env python3
# summary: Match window corners to the desktop frame.
"""starchaser corners: cuts window corners so they match the cockpit frame's cut corners; it runs on its own
from hyprland.lua.

    starchaser corners            run (started from hyprland.lua)
    starchaser corners --once     apply once and exit
    starchaser corners --check    print what it would set, change nothing

It watches Hyprland and, for every window, works out which of its corners sit in one of the cockpit frame's cut
corners and cuts those, so the window's cut runs parallel to the frame's cut at the normal gap. Window, border,
shadow and blur are all drawn by Hyprland. With the cockpit off (the top bar) tiled windows are square and
floating windows have all four corners cut; with it on, Starchaser's own windows always keep theirs.

Advanced: the cut itself is Hyprland's corner math, (|x|^p + |y|^p)^(1/p), where p = 1 is an exact 45-degree
chamfer. Starchaser Linux ships patched corner shaders in config/hypr/shaders in which a per-window
rounding_power in [1, 1.5) is a corner code: mask = floor((p - 1) * 32), bit 0 = top-left, 1 = top-right,
2 = bottom-right, 3 = bottom-left. A cut corner gets a 45-degree cut of the window's radius; the rest stay
square. The daemon writes each window's corner code into its rounding / rounding_power.
"""
import json
import math
import os
import socket
import subprocess
import sys
import threading
import time
from pathlib import Path

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

HOME = Path.home()
# patched rounding/border/shadow + HYPRLAND_COMMIT: this account's own set in ~/.config/hypr/shaders, else Starchaser's
SHADERS = shaders_dir()
COCKPIT = HOME / ".config/starchaser/cockpit.json"
STATE_DIR = Path(os.environ.get("XDG_STATE_HOME", HOME / ".local/state")) / "starchaser"
THEME_STATE = STATE_DIR / "theme.json"      # look.corner_cut: the cut picked in Settings > Appearance > Customize
MASK_BIT = {"tl": 1, "tr": 2, "br": 4, "bl": 8}  # verified on screen (archdev, transform 0)
WINDOW_EVENTS = ("openwindow", "closewindow", "movewindow", "workspace", "changefloatingmode",
                 "fullscreen", "monitoradded", "monitorremoved", "configreloaded", "moveworkspace",
                 "focusedmon", "activespecial", "togglegroup", "pin")


def hypr(*args) -> str:
    signature = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
    if signature:
        runtime = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
        if args[0] == "--batch":
            message = "[[BATCH]]" + args[1]
        else:
            message = ("j/" if "-j" in args else "") + " ".join(a for a in args if a != "-j")
        try:
            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
                client.settimeout(5)
                client.connect(str(runtime / "hypr" / signature / ".socket.sock"))
                client.sendall(message.encode())
                answer = b""
                while chunk := client.recv(65536):
                    answer += chunk
                return answer.decode(errors="replace")
        except OSError:
            return ""
    try:
        return subprocess.run(["hyprctl", *args], capture_output=True, text=True, timeout=5).stdout
    except OSError:
        return ""                                   # no hyprctl: no answer (the callers make do without one)


def hypr_json(what: str):
    try:
        return json.loads(hypr(what, "-j"))
    except ValueError:
        return []


def option_int(name: str, default: int) -> int:
    try:
        return int(json.loads(hypr("getoption", name, "-j")).get("int", default))
    except (ValueError, TypeError):
        return default


def cockpit() -> dict:
    try:
        cfg = json.loads(COCKPIT.read_text())
    except (OSError, ValueError):
        cfg = {}
    return {"bar": cfg.get("mode") == "bar", "edge": cfg.get("edge", "left"), "frame": cfg.get("frame", 6),
            "spine": cfg.get("spine", 48), "chamfer": cfg.get("chamfer", 18)}


def corner_props(win: dict, mon: dict, ck: dict, border: int) -> tuple:
    """(mask, outer cut leg) for one window, or (0, 0) if no corner sits in a frame cut."""
    w, h = mon["width"] / mon["scale"], mon["height"] / mon["scale"]
    if mon.get("transform", 0) % 2 == 1:
        w, h = h, w
    rl, rt, rr, rb = mon["reserved"]
    x0, y0, x1, y1 = mon["x"] + rl, mon["y"] + rt, mon["x"] + w - rr, mon["y"] + h - rb
    k = ck["chamfer"]
    ox, oy = win["at"][0] - border, win["at"][1] - border
    ow, oh = win["size"][0] + 2 * border, win["size"][1] + 2 * border
    corners = {"tl": (ox - x0, oy - y0), "tr": (x1 - (ox + ow), oy - y0),
               "br": (x1 - (ox + ow), y1 - (oy + oh)), "bl": (ox - x0, y1 - (oy + oh))}
    mask, ds = 0, []
    for name, (dx, dy) in corners.items():
        if dx >= -1 and dy >= -1 and abs(dx - dy) <= 2 and min(dx, dy) <= 2 * k:
            mask |= MASK_BIT[name]
            ds.append(max(0.0, min(dx, dy)))
    if not mask:
        return 0, 0.0
    d = sum(ds) / len(ds)
    return mask, k + d * math.sqrt(2) - 2 * d   # outer cut leg: parallel to the frame at gap d


ALWAYS_CUT = ("org.quickshell", "starchaser-firewall")   # Starchaser's own windows (Settings, Ask, the welcome, previews): all four corners cut
ALWAYS_LEG = 14.0
CUT_LEGS = (8, 14, 20)          # Small, Medium, Large in starchaser theme (CORNER_CUT)


def corner_cut() -> float:
    """The cut where all four corners are cut (floating windows with the frame off, Starchaser's own windows): the
    one picked in Settings, read on every pass (a write to theme.json starts one: settings_changes)."""
    try:
        v = json.loads(THEME_STATE.read_text()).get("look", {}).get("corner_cut")
    except (OSError, ValueError, AttributeError):
        return ALWAYS_LEG
    return float(v) if isinstance(v, (int, float)) and v in CUT_LEGS else ALWAYS_LEG


def desired(win: dict, mon: dict, ck: dict, border: int, leg_all: float = ALWAYS_LEG) -> tuple | None:
    """(rounding, rounding_power) strings, or None for stock square corners. leg_all: the cut where all four corners
    are cut."""
    if ck.get("bar"):
        # cockpit off (the top bar), decided 2026-10-08: tiled windows are square, floating windows have all four
        # corners cut, Starchaser's own windows included. A write to cockpit.json (settings_changes) or floating/
        # tiling a window (its event) reshapes it at once.
        if not win.get("floating") or win.get("fullscreen"):
            return None
        mask, leg = 15, leg_all
    elif win.get("class") in ALWAYS_CUT and not win.get("fullscreen"):
        mask, leg = 15, leg_all
    else:
        mask, leg = corner_props(win, mon, ck, border)
    if not mask or win.get("fullscreen", 0) == 2:
        return None
    p = 1.0 + (mask + 0.5) / 32.0
    radius = max(1.0, leg - border)      # the client surface's own cut (border sits outside it)
    rounding = 2.0 * (radius + 1.0) / (p * mon["scale"])   # shader radius = rounding * p/2 * scale - 1
    return f"{rounding:.2f}", f"{p:.6f}"


def moves_corners(win: dict, ck: dict) -> bool:
    """Whether dragging or resizing this window (which sends no event) can change its corners: only a window whose
    cut follows where it sits, i.e. with the frame on, not one of Starchaser's own windows (always all four) and not
    fullscreen. The ticker runs only while one shows, so an open welcome or Settings costs nothing a second."""
    return not ck.get("bar") and win.get("class") not in ALWAYS_CUT and not win.get("fullscreen")


def settings_changes(changed) -> None:
    """Call changed() whenever cockpit.json or theme.json is written (the frame turned on or off, another cut picked
    in Settings): inotify on their folders, so the change shows at once without reading them every second."""
    import ctypes
    import struct
    libc = ctypes.CDLL(None, use_errno=True)
    fd = libc.inotify_init1(os.O_CLOEXEC)
    if fd < 0:
        return
    names = {os.fsencode(COCKPIT.name), os.fsencode(THEME_STATE.name)}
    try:
        watched = 0
        for folder in {COCKPIT.parent, THEME_STATE.parent}:
            folder.mkdir(parents=True, exist_ok=True)
            # IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_DELETE: written in place, or a temp file renamed over it
            watched += libc.inotify_add_watch(fd, os.fsencode(folder), 0x08 | 0x80 | 0x100 | 0x200) >= 0
        if not watched:
            return
        while True:
            raw, offset, hit = os.read(fd, 65536), 0, False
            while offset + 16 <= len(raw):
                _, mask, _, length = struct.unpack_from("iIII", raw, offset)
                hit |= raw[offset + 16:offset + 16 + length].split(b"\0", 1)[0] in names or bool(mask & 0x4000)
                offset += 16 + length
            if hit:
                changed()
    except OSError:
        return
    finally:
        os.close(fd)


def ws_key(ws) -> str:
    """A workspace's identity in Hyprland's JSON: its name (special workspaces have no "id"), else its id."""
    ws = ws or {}
    return str(ws.get("name") or ws.get("id") or "")


class Corners:
    def __init__(self, dry=False):
        self.dry = dry
        self.applied: dict = {}
        self.lock = threading.Lock()
        self.follow = threading.Event()

    def run_once(self) -> None:
        with self.lock:
            ck = cockpit()
            leg_all = corner_cut()
            border = option_int("general:border_size", 2)
            mons = {m["id"]: m for m in hypr_json("monitors")}
            # Hyprland 0.57 reports a special workspace (the drop-down terminal's) without an "id": key workspaces by
            # name, so one such window no longer stops the corners of every other window (QA 2026-11-09)
            visible = {ws_key(m.get("activeWorkspace")) for m in mons.values()} | \
                      {ws_key(m.get("specialWorkspace")) for m in mons.values() if ws_key(m.get("specialWorkspace"))}
            cmds, seen, sent = [], set(), {}
            clients = hypr_json("clients")
            following = any(c.get("mapped") and not c.get("hidden") and moves_corners(c, ck) and
                            (c.get("pinned") or ws_key(c.get("workspace")) in visible) for c in clients)
            if following:
                self.follow.set()
            else:
                self.follow.clear()
            for c in clients:
                if not c.get("mapped") or c["monitor"] not in mons:
                    continue
                addr = c["address"]
                seen.add(addr)
                if ws_key(c.get("workspace")) not in visible and addr in self.applied:
                    continue  # keep what it had; recomputed when its workspace is shown
                want = desired(c, mons[c["monitor"]], ck, border, leg_all)
                if self.applied.get(addr, "unset") == want:
                    continue
                if want is None:             # stock square corners (also clears stale cuts at startup)
                    want_r, want_p = "0", "2"
                else:
                    want_r, want_p = want
                cmds += [f'dispatch hl.dsp.window.set_prop({{ prop = "rounding", value = "{want_r}", window = "address:{addr}" }})',
                         f'dispatch hl.dsp.window.set_prop({{ prop = "rounding_power", value = "{want_p}", window = "address:{addr}" }})']
                if self.dry:
                    print(f"{c['class'][:16]:<16} {c['at']} {c['size']} -> rounding {want_r} power {want_p}")
                sent[addr] = want
            for gone in set(self.applied) - seen:
                del self.applied[gone]
            if self.dry and not cmds:
                print(f"No windows to change ({len(seen)} checked)")
            if not cmds or self.dry:
                return
            # recorded as applied only once Hyprland said "ok" to every command: a batch that failed or timed out
            # (a busy compositor at sign-in) was remembered as done, and that window kept its old corners for good,
            # even across a cockpit on/off (seen on qa-3, 2026-10-08)
            try:
                out = hypr("--batch", " ; ".join(cmds))
            except (OSError, subprocess.SubprocessError):
                out = ""
            if out.count("ok") >= len(cmds):
                self.applied.update(sent)
            else:
                for addr in sent:
                    self.applied.pop(addr, None)

    def listen(self) -> None:
        sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "")
        path = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "hypr" / sig / ".socket2.sock"
        pending = threading.Event()

        def worker():
            while True:
                pending.wait()
                time.sleep(0.06)          # let layout settle; coalesce bursts
                pending.clear()
                try:
                    self.run_once()
                except Exception as e:     # never die on one bad read
                    print(f"starchaser corners: {e}", file=sys.stderr)

        def ticker():                      # drags / resizes send no event (only while such a window shows)
            while True:
                self.follow.wait()
                time.sleep(1.0)
                if self.follow.is_set():
                    pending.set()

        threading.Thread(target=worker, daemon=True).start()
        threading.Thread(target=ticker, daemon=True).start()
        threading.Thread(target=settings_changes, args=(pending.set,), daemon=True).start()
        pending.set()
        while True:
            try:
                s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                s.connect(str(path))
                buf = b""
                while True:
                    data = s.recv(4096)
                    if not data:
                        break
                    buf += data
                    *lines, buf = buf.split(b"\n")
                    if any(l.split(b">>")[0].decode(errors="replace").startswith(WINDOW_EVENTS) for l in lines):
                        pending.set()
            except OSError:
                time.sleep(2)


def write_status(on: bool) -> None:
    """corners.json: Settings' corner-cut row says "Corner cuts are off on this computer right now" when they are."""
    try:
        STATE_DIR.mkdir(parents=True, exist_ok=True)
        tmp = STATE_DIR / f".corners.json.{os.getpid()}.tmp"
        tmp.write_text(json.dumps({"corners": "on" if on else "off"}) + "\n")
        os.replace(tmp, STATE_DIR / "corners.json")
    except OSError:
        pass        # best effort: without it Settings assumes the cuts work


def load_shaders() -> bool:
    ok = _load_shaders()
    write_status(ok)
    return ok


def _load_shaders() -> bool:
    """Load the patched corner shaders, but only for the exact Hyprland build they were written
    for: they replace Hyprland's own files, so a mismatch after an update could break rendering.
    On a mismatch Hyprland keeps its stock shaders (windows stay square) and the user is told."""
    try:
        want = (SHADERS / "HYPRLAND_COMMIT").read_text().strip()
        have = json.loads(hypr("version", "-j")).get("commit", "")
    except (OSError, ValueError):
        return False
    if not want or not have or not have.startswith(want[:12]) and not want.startswith(have[:12]):
        hypr("reloadshaders")  # back to stock
        try:
            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", "-u", "critical", "Starchaser corners paused",
                            f"Hyprland was updated ({have[:8]}); the corner shaders were made for {want[:8]}. "
                            "Windows stay square until the shaders are updated."], capture_output=True)
        except OSError:
            pass
        return False
    # hyprctl answers "ok" only when Hyprland took the shaders; anything else means it kept or fell back to its stock
    # ones, and the corner properties are only right for the patched shaders, so that stops here
    res = hypr("reloadshaders", str(SHADERS)).strip()
    if res != "ok":
        hypr("reloadshaders")  # back to stock
        try:
            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", "-u", "critical", "Starchaser corners paused",
                            "Hyprland didn't accept the corner shaders. Windows stay square until the shaders are fixed."],
                           capture_output=True)
        except OSError:
            pass
        print(f"starchaser corners: Hyprland rejected the shaders in {SHADERS}: {res or 'no answer'}", file=sys.stderr)
        return False
    return True


def single_instance() -> None:
    """One daemon per session: a second one would fight the first over every window's corners."""
    import fcntl
    lock = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-corners.lock"
    global _LOCK
    _LOCK = open(lock, "w")
    try:
        fcntl.flock(_LOCK, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        print("starchaser corners: already running", file=sys.stderr)
        sys.exit(0)


if __name__ == "__main__":
    args = sys.argv[1:]
    if any(a in ("-h", "--help", "help") for a in args):
        print(__doc__)
        sys.exit(0)
    unknown = [a for a in args if a not in ("--check", "--once")]
    if unknown:
        sys.exit(usage_error("starchaser corners", f"unknown option {unknown[0]!r}",
                             "[--once] [--check]", ("--once", "--check", "--help")))
    if not args:
        single_instance()
    if "--check" not in sys.argv and not load_shaders():
        print("starchaser corners: shaders not loaded (Hyprland version mismatch, or Hyprland rejected them); exiting",
              file=sys.stderr)
        sys.exit(1)
    if "--check" in sys.argv:
        Corners(dry=True).run_once()
    elif "--once" in sys.argv:
        Corners().run_once()
    else:
        Corners().listen()
