#!/usr/bin/env python3
# summary: Pick a window, screen, area, or color from the frozen desktop.
"""Pick a window, screen or area over the frozen desktop, without moving the pointer."""
import json
import os
os.environ["QS_DISABLE_CRASH_HANDLER"] = "1"
os.environ["STARCHASER_QML_APP"] = "capture"
import re
import subprocess
import sys
from pathlib import Path


def monitor_rect(m):
    w, h = m['width'] / m.get('scale', 1), m['height'] / m.get('scale', 1)
    if m.get('transform', 0) % 2:
        w, h = h, w
    return (m['x'], m['y'], w, h)


def visible_windows(windows, monitors):
    active = {m.get('activeWorkspace', {}).get('id') for m in monitors}
    active |= {m.get('specialWorkspace', {}).get('id') for m in monitors if m.get('specialWorkspace', {}).get('id', 0) != 0}
    result = []
    for w in sorted(windows, key=lambda item: item.get('focusHistoryID', 999)):
        if not w.get('mapped') or w.get('hidden') or w.get('workspace', {}).get('id') not in active:
            continue
        x, y = w['at']
        width, height = w['size']
        rects = [monitor_rect(m) for m in monitors]
        if not rects:
            continue
        left, top = min(r[0] for r in rects), min(r[1] for r in rects)
        right, bottom = max(r[0] + r[2] for r in rects), max(r[1] + r[3] for r in rects)
        width, height = min(x + width, right) - max(x, left), min(y + height, bottom) - max(y, top)
        x, y = max(x, left), max(y, top)
        if width > 0 and height > 0:
            result.append({'address': w['address'], 'title': w.get('title', 'Window'), 'x': x, 'y': y, 'width': width, 'height': height})
    return result


def validate_region(region, monitors):
    match = re.fullmatch(r'(-?\d+),(-?\d+) (\d+)x(\d+)', region)
    if not match or not monitors:
        return None
    x, y, w, h = map(int, match.groups())
    rects = [monitor_rect(m) for m in monitors]
    left, top = min(r[0] for r in rects), min(r[1] for r in rects)
    right, bottom = max(r[0] + r[2] for r in rects), max(r[1] + r[3] for r in rects)
    if w <= 0 or h <= 0 or x < left or y < top or x + w > right or y + h > bottom:
        return None
    if not any(x < rx + rw and y < ry + rh and x + w > rx and y + h > ry for rx, ry, rw, rh in rects):
        return None
    return region


def main(args):
    if args in (['--help'], ['-h']):
        print('Usage: starchaser capture picker <captured-frame> [--color]\nClick a window, drag an area, or use the on-screen keyboard controls. Esc cancels.')
        return 0
    if len(args) not in (1, 2) or (len(args) == 2 and args[1] != '--color') or not Path(args[0]).is_file():
        print('Usage: starchaser capture picker <captured-frame> [--color]', file=sys.stderr)
        return 2
    try:
        def read(what):
            return json.loads(subprocess.run(['hyprctl', what, '-j'], capture_output=True, text=True, check=True, timeout=5).stdout)
        monitors = read('monitors')
        windows = visible_windows(read('clients'), monitors)
        state = Path(os.environ.get('XDG_STATE_HOME', Path.home() / '.local/state')) / 'starchaser/capture-region'
        last = validate_region(state.read_text().strip(), monitors) if state.exists() else None
        folder = Path(__file__).resolve().parents[1] / 'config/quickshell/capture'
        config = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'quickshell/capture'
        if config.is_dir():
            folder = config
        env = dict(os.environ, STARCHASER_CAPTURE_FRAME=str(Path(args[0]).resolve()),
                   STARCHASER_CAPTURE_WINDOWS=json.dumps(windows), STARCHASER_CAPTURE_MONITORS=json.dumps(monitors),
                   STARCHASER_CAPTURE_LAST=last or '', STARCHASER_CAPTURE_COLOR='1' if len(args) == 2 else '0')
        proc = subprocess.run(['qs', '-p', str(folder)], env=env, capture_output=True, text=True)
        matches = re.findall(r'STARCHASER_CAPTURE=(-?\d+,-?\d+ \d+x\d+)', proc.stdout + proc.stderr)
        region = validate_region(matches[-1], monitors) if matches else None
        if region:
            if len(args) == 2:  # A sampled pixel must not replace the last screenshot area.
                print(region)
                return 0
            # The last area is personal state; an atomic rename keeps concurrent readers from seeing half of it.
            state.parent.mkdir(parents=True, exist_ok=True)
            tmp = state.with_name(f'.capture-region.{os.getpid()}.tmp')
            try:
                with tmp.open('w') as out:
                    out.write(region + '\n')
                    out.flush()
                    os.fsync(out.fileno())
                tmp.replace(state)
            finally:
                tmp.unlink(missing_ok=True)
            print(region)
            return 0
        if proc.returncode:
            print('The capture picker could not open. Try again.', file=sys.stderr)
            return 1
        return 0  # Esc or Close leaves the clipboard untouched.
    except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error:
        print(f'The capture picker could not open: {error}', file=sys.stderr)
        return 1


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