#!/usr/bin/env python3
# summary: Choose desktop layouts and floating desktop dock settings.
"""Usage: starchaser desktops [status | cycle [back] | current tiling|scrolling|floating | default [tiling|scrolling|floating]
       | dock position bottom|left|right | dock autohide on|off
       | notice small-window
       | dock pin ID | dock unpin ID | dock reorder ID ID ...]

Tiling is the initial default. Changing the default affects new and empty desktops.
Occupied desktops, including windows minimized to the dock, keep their layout.
"""
import fcntl
import json
import os
import subprocess
import sys
from pathlib import Path

STATE = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "starchaser"
MODES = ("tiling", "scrolling", "floating")
MINIMIZED = Path.home() / ".local/state/starchaser/minimized"


def read():
    try:
        data = json.loads((STATE / "desktop-layouts.json").read_text())
    except FileNotFoundError:
        data = {}
    data.setdefault("default", "tiling")
    data.setdefault("modes", {})
    data.setdefault("dock", {})
    return data


def code(data):
    modes = ",".join(f'[{json.dumps(k)}]={json.dumps(v)}' for k, v in data["modes"].items())
    return 'StarchaserLayouts.configure({default=' + json.dumps(data["default"]) + ', modes={' + modes + '}})'


def atomic(path, text):
    tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    try:
        with tmp.open("w") as stream:
            stream.write(text)
            stream.flush()
            os.fsync(stream.fileno())
        tmp.replace(path)
    finally:
        tmp.unlink(missing_ok=True)


def save(data):
    STATE.mkdir(parents=True, exist_ok=True)
    atomic(STATE / "desktop-layouts.json", json.dumps(data) + "\n")


def query(name):
    result = subprocess.run(["hyprctl", name, "-j"], capture_output=True, text=True, timeout=10, check=True)
    return json.loads(result.stdout)


def apply(data):
    result = subprocess.run(["hyprctl", "eval", code(data)], capture_output=True, text=True, timeout=10)
    if result.returncode or "error" in result.stdout.lower():
        # A live API error can arrive after part of the arrangement changed. Restore the last saved choices
        # best-effort before reporting failure; never persist an arrangement the compositor rejected.
        subprocess.run(["hyprctl", "eval", code(read())], capture_output=True, text=True, timeout=10)
        raise RuntimeError(result.stderr or result.stdout or "Couldn't change the desktop layout.")


def set_default(mode):
    data = read()
    workspaces, clients = query("workspaces"), query("clients")
    if not isinstance(workspaces, list) or not isinstance(clients, list):
        raise RuntimeError("Couldn't read the open windows. Nothing was changed.")
    busy = {str(w["id"]) for w in workspaces if w.get("id", 0) > 0 and w.get("windows", 0)}
    # Use the window manager's existing origin records rather than maintaining a second minimize history.
    try:
        records = MINIMIZED.read_text().splitlines()
    except FileNotFoundError:
        records = []
    live = {w.get("address") for w in clients if w.get("workspace", {}).get("name") == "special:minimized"}
    for record in records:
        fields = record.split("\t")
        if len(fields) >= 2 and fields[0] in live and fields[1].isdigit():
            busy.add(fields[1])
    data["modes"] = {key: data["modes"].get(key, data["default"]) for key in busy}
    data["default"] = mode
    apply(data)
    save(data)


def notify_layout(workspace, mode):
    args = ["starchaser", "notify", "-a", "Starchaser", "-t", "1800", "-h",
            "string:x-canonical-private-synchronous:starchaser-layout", f"Desktop {workspace}: {mode.title()}"]
    token = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "starchaser-notifications" / "token"
    try:
        stream = token.open("rb")
    except FileNotFoundError:
        subprocess.run(args, check=False, stdout=subprocess.DEVNULL)
        return
    with stream:
        subprocess.run([*args[:2], f"--credential-fd={stream.fileno()}", *args[2:]], pass_fds=(stream.fileno(),),
                       check=False, stdout=subprocess.DEVNULL)


def notice_small_window():
    """Say once per sign-in why a narrow new window opened maximized."""
    runtime = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
    marker = runtime / "starchaser-small-window-notice"
    try:
        fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
    except FileExistsError:
        return
    os.close(fd)
    args = ["starchaser", "notify", "-a", "Starchaser", "-t", "6000", "Opened maximized: not enough room to tile it",
            "To put it back beside the others, choose Restore size in its taskbar preview, or use the Maximize shortcut (Settings > Shortcuts)."]
    token = runtime / "starchaser-notifications" / "token"
    try:
        stream = token.open("rb")
    except FileNotFoundError:
        subprocess.run(args, check=False, stdout=subprocess.DEVNULL)
        return
    with stream:
        subprocess.run([*args[:2], f"--credential-fd={stream.fileno()}", *args[2:]], pass_fds=(stream.fileno(),),
                       check=False, stdout=subprocess.DEVNULL)


def main(args):
    if args in (["--help"], ["-h"]):
        print(__doc__)
        return 0
    if args == ["notice", "small-window"]:
        notice_small_window()
        return 0
    if not args or args == ["status"]:
        print(json.dumps(read()))
        return 0
    if args == ["default"]:
        print(read()["default"])
        return 0
    STATE.mkdir(parents=True, exist_ok=True)
    with (STATE / ".desktop-layouts.lock").open("a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        if len(args) == 2 and args[0] == "default" and args[1] in MODES:
            set_default(args[1])
        elif args in (["cycle"], ["cycle", "back"]) or (len(args) == 2 and args[0] == "current" and args[1] in MODES):
            workspace = query("activeworkspace").get("id", 0)
            if not isinstance(workspace, int) or workspace < 1:
                raise RuntimeError("Choose a regular desktop first.")
            data = read()
            current = data["modes"].get(str(workspace), data["default"])
            mode = args[1] if args[0] == "current" else MODES[(MODES.index(current) + (-1 if "back" in args else 1)) % 3]
            data["modes"][str(workspace)] = mode
            apply(data)
            save(data)
            notify_layout(workspace, mode)
        elif len(args) >= 3 and args[0] == "dock":
            data = read()
            dock = data["dock"]
            option, values = args[1], args[2:]
            if option == "position" and len(values) == 1 and values[0] in ("bottom", "left", "right"):
                dock[option] = values[0]
            elif option == "autohide" and values in (["on"], ["off"]):
                dock[option] = values[0] == "on"
            elif option in ("pin", "unpin", "reorder") and all(v and all(c.isalnum() or c in "._-" for c in v) for v in values):
                pins = dock.get("pins", [])
                if option == "reorder":
                    dock["pins"] = list(dict.fromkeys(pins + values[:1]))
                    dock["order"] = list(dict.fromkeys(values[1:]))
                else:
                    dock["pins"] = list(dict.fromkeys(pins + values)) if option == "pin" else [p for p in pins if p not in values]
            else:
                print(__doc__, file=sys.stderr)
                return 2
            save(data)
        else:
            print(__doc__, file=sys.stderr)
            return 2
    print(json.dumps(read()))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
        print(f"starchaser desktops: {error}", file=sys.stderr)
        sys.exit(1)
