#!/usr/bin/env python3
# summary: Start or manage the desktop tour.
"""starchaser tour: the everyday desktop tour (it runs inside the taskbar: cockpit TourState.qml and Tour.qml).

    start [--from-welcome|--from-menu|--from-settings]
                    start the tour (or show the step it's on); the menu is put away first, since the first stop
                    points at it
    next | skip     move the tour on, counting the step as tried or as skipped
    stop            end the tour
    more            on the last card, explore optional terminal keys
    retry           on the last card, go back to the steps that were skipped ("Try skipped steps")
    saw EVENT       tell the tour something happened that the taskbar can't see (Ask sends ask-open,
                    ask-open-noai, ask-question, ask-example; the menu sends keys-open); returns at once when no
                    tour is running
    status          the tour's saved state, as JSON
    practice        open the practice window (a terminal that is safe to close)
    practice-pair   open the layout lesson's second window (the taskbar opens it; it closes when the lesson ends)
    offer CHOICE    note what the welcome's last page offered and what was chosen (tour, skip, closed)
    reset           forget the tour (for testing: the next start begins from the top)
    key             for the taskbar while a tour runs: bind Super+Alt+N to the next step while stdin says "on",
                    and take it away on "off", end of input or the taskbar's exit; prints "taken" instead when
                    that combination already does something else here
    reader-ready    for the taskbar: exit 0 once Orca is listening for AT-SPI announcements, otherwise 1

The state is in ~/.local/state/starchaser/tour.json; the taskbar is its only writer while it runs. Exit 1 with
"The desktop isn't running." when the taskbar can't be reached for next, skip or retry; stop then ends the saved tour.
"""
import fcntl
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_bind_lease import lease

HOME = Path.home()
# Super+Shift+N moves a window down in the Emacs/Readline profile; Super+Alt+N is free in every profile
NEXT_KEY = "SUPER + ALT + N"
NEXT_MODMASK = 64 | 8
STATE = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser/tour.json"
COCKPIT = HOME / ".config/quickshell/cockpit"
MENU = HOME / ".config/quickshell/cockpit"
FROM = ("--from-welcome", "--from-menu", "--from-settings")
CHOICES = ("tour", "skip", "closed")


def usage_error(msg: str) -> None:
    print(f"starchaser tour: {msg}. Run 'starchaser tour --help' for more help.", file=sys.stderr)
    sys.exit(2)


def read_state() -> dict:
    try:
        d = json.loads(STATE.read_text())
    except (OSError, ValueError):
        return {}
    return d if isinstance(d, dict) else {}


def write_state(change) -> dict:
    """Read, change and write tour.json under a lock, through a temporary file renamed over it (one writer at a time,
    and never a half-written file for the taskbar to read)."""
    STATE.parent.mkdir(parents=True, exist_ok=True)
    with open(STATE.parent / ".tour.lock", "a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        d = read_state()
        change(d)
        tmp = STATE.parent / f".tour.json.{os.getpid()}.tmp"
        with open(tmp, "w") as f:
            f.write(json.dumps(d, indent=1) + "\n")
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, STATE)
    return d


def ipc(target_dir: Path, *args: str) -> tuple[int, str]:
    """`qs ipc call` into a running Quickshell config: (exit code, what it printed). 127 when qs isn't installed."""
    if not shutil.which("qs"):
        return 127, ""
    try:
        r = subprocess.run(["qs", "-p", str(target_dir), "ipc", "call", "--", *args], capture_output=True, text=True, timeout=3)
    except (OSError, subprocess.TimeoutExpired):
        return 124, ""
    return r.returncode, r.stdout.strip()


def boot_id() -> str:
    try:
        return Path("/proc/sys/kernel/random/boot_id").read_text().strip()
    except OSError:
        return ""


def reader_ready() -> bool:
    """A running Orca must have registered its announcement listener before the card speaks."""
    try:
        from gi.repository import Gio, GLib
    except ImportError:
        return False

    try:
        def call(bus, dest, path, interface, method, args=None):
            return bus.call_sync(dest, path, interface, method, args, None,
                                 Gio.DBusCallFlags.NONE, 500, None).unpack()

        session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        address, = call(session, 'org.a11y.Bus', '/org/a11y/bus', 'org.a11y.Bus', 'GetAddress')
        bus = Gio.DBusConnection.new_for_address_sync(address,
            Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
            None, None)
        events, = call(bus, 'org.a11y.atspi.Registry', '/org/a11y/atspi/registry',
                       'org.a11y.atspi.Registry', 'GetRegisteredEvents')
        for owner, event in events:
            if event.lower().rstrip(':') != 'object:announcement':
                continue
            pid, = call(bus, 'org.freedesktop.DBus', '/org/freedesktop/DBus',
                        'org.freedesktop.DBus', 'GetConnectionUnixProcessID', GLib.Variant('(s)', (owner,)))
            if Path(f'/proc/{pid}/comm').read_text().strip() == 'orca':
                return True
    except (OSError, GLib.Error):
        return False
    return False


def start(origin: str) -> None:
    ipc(MENU, "menu", "hide")          # best effort: no menu running is fine
    code, said = ipc(COCKPIT, "tour", "start", origin)
    if code == 0:
        print(said or "started")
        return
    # the taskbar isn't answering (it is starting, or restarting): leave the tour for it to pick up when it starts
    # (it reads tour.json at start, and watches it)
    now = int(time.time() * 1000)

    def change(d):
        keep = {k: d[k] for k in ("offered", "choice") if k in d}
        d.clear()
        d.update({"v": 1, "active": True, "step": "intro", "phase": "waiting", "results": {}, "boot": boot_id(),
                  "started": now, "resumes": [], "finished": None, "ended": None, "from": origin, **keep})
    write_state(change)
    print("started (the desktop will show it when the taskbar starts)")


def main(argv: list) -> None:
    if not argv:
        print(__doc__.strip(), file=sys.stderr)
        sys.exit(2)
    if argv[0] in ("-h", "--help", "help") or any(x in ("-h", "--help") for x in argv[1:]):
        print(__doc__.strip())
        return
    cmd, rest = argv[0], argv[1:]
    if cmd == "start":
        if len(rest) > 1 or (rest and rest[0] not in FROM):
            usage_error(f"start: unknown option {rest[0]!r} (one of: {', '.join(FROM)})" if rest else "start takes one option")
        start(rest[0][2:] if rest else "command")
    elif cmd in ("next", "skip", "stop", "retry", "more"):
        if rest:
            usage_error(f"{cmd} takes no arguments")
        code, _ = ipc(COCKPIT, "tour", cmd)
        if cmd == "stop":
            # Always record the stop, including when IPC answered during the taskbar's state loading.
            # A restarted or active taskbar watches it, and the menu's Tour rows go away.
            write_state(lambda d: d.update({"active": False, "ended": "ended", "stoppedAt": int(time.time() * 1000)}))
            return
        if code != 0:
            print("The desktop isn't running.", file=sys.stderr)
            sys.exit(1)
    elif cmd == "saw":
        if len(rest) != 1 or not rest[0]:
            usage_error("saw needs one event name, like: saw ask-question")
        # Ask and the menu call this every time: with no tour running it ends here, without starting qs
        if read_state().get("active") is not True:
            return
        ipc(COCKPIT, "tour", "saw", rest[0])
    elif cmd == "status":
        if rest:
            usage_error("status takes no arguments")
        print(json.dumps(read_state()))
    elif cmd == "practice":
        if rest:
            usage_error("practice takes no arguments")
        if not shutil.which("kitty"):
            print("starchaser tour: the practice window needs the terminal (kitty), which isn't installed", file=sys.stderr)
            sys.exit(1)
        # no "are you sure?" on closing it: it runs only `sleep`, and closing it is the lesson.
        # wayland_enable_ime=no: nothing is typed here, so the window never asks for the on-screen keyboard
        subprocess.Popen(["starchaser", "terminal", "-o", "confirm_os_window_close=0", "-o", "wayland_enable_ime=no", "--class", "starchaser-tour-practice", "--title", "Practice window", "sh", "-c",
                          'printf "Follow the\\ntour card.\\n"; exec sleep infinity'],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    elif cmd == "practice-pair":
        if rest:
            usage_error("practice-pair takes no arguments")
        if not shutil.which("kitty"):
            print("starchaser tour: the practice window needs the terminal (kitty), which isn't installed", file=sys.stderr)
            sys.exit(1)
        # the layout lesson's second window: one window looks the same in every layout
        subprocess.Popen(["starchaser", "terminal", "-o", "confirm_os_window_close=0", "-o", "wayland_enable_ime=no", "--class", "starchaser-tour-practice-pair", "--title", "Second practice window", "sh", "-c",
                          'printf "A second window.\\n"; exec sleep infinity'],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    elif cmd == "offer":
        if len(rest) != 1 or rest[0] not in CHOICES:
            usage_error(f"offer needs one of: {', '.join(CHOICES)}")
        write_state(lambda d: d.update({"offered": int(time.time() * 1000), "choice": rest[0]}))
    elif cmd == "key":
        if rest:
            usage_error("key takes no arguments")
        lease("starchaser_tour_next", NEXT_KEY, "starchaser-tour:next", "Next step of the tour (only while it runs)",
              keep_free=(NEXT_MODMASK, "N"))
    elif cmd == "reader-ready":
        if rest:
            usage_error("reader-ready takes no arguments")
        sys.exit(0 if reader_ready() else 1)
    elif cmd == "reset":
        if rest:
            usage_error("reset takes no arguments")
        if read_state().get("active") is True:
            ipc(COCKPIT, "tour", "stop")       # best effort: a running tour ends first, then nothing is left
        try:
            STATE.unlink()
        except FileNotFoundError:
            pass
    else:
        usage_error(f"unknown command {cmd!r}")


if __name__ == "__main__":
    try:
        main(sys.argv[1:])
    except OSError as error:               # a state folder it may not write: say so, not a traceback
        sys.exit(f"starchaser tour: couldn't save the tour state ({error.strerror}). "
                 "Check that you can write to ~/.local/state.")
