#!/usr/bin/env python3
# summary: Read or search the offline user manual.
"""usage: starchaser manual [open [CHAPTER] | list | search WORDS | read CHAPTER]
Read the same offline chapters used by Help, menu search, Ask, and coding agents.
With no arguments, open the Manual window. list, search, and read print JSON.
"""
import fcntl
import json
import os
import re
import time
os.environ["QS_DISABLE_CRASH_HANDLER"] = "1"
os.environ["STARCHASER_QML_APP"] = "manual"
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_manual as manual


def ipc(path, method, *args):
    try:
        result = subprocess.run(['qs', '-p', str(path), 'ipc', 'call', '--', 'manual', method, *args],
                                capture_output=True, text=True, timeout=2)
        return result.returncode == 0 and (method != 'ready' or result.stdout.strip() == 'ready')
    except (OSError, subprocess.SubprocessError):
        return False


def focus_manual():
    try:
        result = subprocess.run(['hyprctl', 'clients', '-j'], capture_output=True, text=True, timeout=2)
        for client in json.loads(result.stdout):
            if client.get('class') != 'starchaser-manual': continue
            address = client.get('address', '')
            if not re.fullmatch(r'0x[0-9a-fA-F]+', address): continue
            command = (f'StarchaserWin.restore("{address}")'
                       if client.get('workspace', {}).get('name') == 'special:minimized'
                       else f'hl.dispatch(hl.dsp.focus({{ window = "address:{address}" }}))')
            subprocess.run(['hyprctl', 'eval', command], capture_output=True, timeout=2)
            return
    except (OSError, ValueError, subprocess.SubprocessError):
        pass


def wait_ready(path, process):
    # Hold the launch lock until this instance can answer a second caller.
    end = time.monotonic() + 8
    while process.poll() is None and time.monotonic() < end:
        if ipc(path, 'ready'): return
        time.sleep(.1)


def main(args):
    if any(a in ('--help', '-h') for a in args):
        print(__doc__); return 0
    try:
        if not args or args[0] == 'open' and len(args) <= 2:
            ident = args[1] if len(args) == 2 else ''
            if ident: manual.chapter(ident)
            base = Path(__file__).resolve().parents[1]
            path = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'quickshell/manual'
            if not (path / 'shell.qml').is_file(): path = base / 'config/quickshell/manual'
            runtime = Path(os.environ.get('XDG_RUNTIME_DIR', str(Path.home() / '.cache/starchaser')))
            runtime.mkdir(parents=True, exist_ok=True)
            with (runtime / 'starchaser-manual-launch.lock').open('a') as lock:
                fcntl.flock(lock, fcntl.LOCK_EX)
                if ipc(path, 'open', ident):
                    focus_manual()
                    return 0
                process = subprocess.Popen(['qs', '-p', str(path)], env=dict(os.environ, STARCHASER_MANUAL_CHAPTER=ident),
                                           start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                wait_ready(path, process)
            return 0
        if args == ['list']: result = {'ok': True, 'chapters': manual.chapters()}
        elif len(args) >= 2 and args[0] == 'search': result = {'ok': True, 'chapters': manual.search(' '.join(args[1:]))}
        elif len(args) == 2 and args[0] == 'read': result = {'ok': True, **manual.chapter(args[1])}
        else:
            print(__doc__, file=sys.stderr); return 2
        print(json.dumps(result)); return 0
    except (OSError, ValueError) as error:
        print(json.dumps({'ok': False, 'errors': str(error)})); return 1


if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
