#!/usr/bin/env python3
# summary: Review a window, selection, or error in Ask.
"""Review a window, selection or error in Ask. Nothing is sent until Ask is pressed."""
import configparser
import json
import os
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path

PROMPTS = {'selection':'Explain this selection.', 'rewrite':'Rewrite this text.', 'shorten':'Shorten this text.', 'spelling':'Fix spelling in this text.', 'translate':'Translate this text into English. Ask me if I want a different language.'}


def selection():
    try:
        text = capture('wl-paste', '--primary', '--no-newline')
        if text.strip(): return text
    except subprocess.SubprocessError:
        pass
    try: return capture('wl-paste', '--no-newline')
    except subprocess.SubprocessError: return ''


def selection_bounds():
    # Ask before taking focus. Apps without accessible text fall back to their
    # window bounds. Never move the pointer to find or display a selection.
    try:
        window = json.loads(capture('hyprctl', 'activewindow', '-j'))
    except (ValueError, OSError, subprocess.SubprocessError):
        window = {}
    script = '''import gi, json
gi.require_version('Atspi', '2.0')
from gi.repository import Atspi
pending = [Atspi.get_desktop(0)]
for _ in range(1000):
    if not pending: break
    node = pending.pop()
    try:
        if node.get_state_set().contains(Atspi.StateType.FOCUSED):
            text = node.get_text_iface()
            if text and text.get_n_selections():
                selected = Atspi.Text.get_selection(text, 0)
                box = Atspi.Text.get_character_extents(text, selected.start_offset, Atspi.CoordType.SCREEN)
                relative = Atspi.Text.get_character_extents(text, selected.start_offset, Atspi.CoordType.WINDOW)
                if box.width > 0 and box.height > 0:
                    print(json.dumps(dict(x=box.x, y=box.y, width=box.width, height=box.height,
                                          windowX=relative.x, windowY=relative.y)))
                    break
        pending.extend(node.get_child_at_index(i) for i in range(node.get_child_count()))
    except Exception: pass
'''
    try:
        bounds = json.loads(capture('python3', '-c', script))
        if all(isinstance(bounds.get(k), (int, float)) for k in ('x', 'y', 'width', 'height')):
            # Some Wayland apps report window-relative coordinates for SCREEN.
            # Use the compositor's position without moving or focusing the app.
            if not window.get('xwayland') and (bounds['x'], bounds['y']) == (bounds.get('windowX'), bounds.get('windowY')) and len(window.get('at', [])) == 2:
                bounds['x'] += window['at'][0]
                bounds['y'] += window['at'][1]
            return {key: bounds[key] for key in ('x', 'y', 'width', 'height')}
    except (ValueError, OSError, subprocess.SubprocessError): pass
    try:
        x, y = window['at']; width, height = window['size']
        return {'x': x + width / 2, 'y': y, 'width': 0, 'height': min(height, 80)}
    except (ValueError, KeyError, OSError, subprocess.SubprocessError): return None


def writing_choice():
    return json.dumps({'kind':'writing-chooser', 'text':selection(), 'bounds':selection_bounds()})


def capture(*args):
    return subprocess.run(args, capture_output=True, text=True, timeout=5, check=True).stdout[:12000]


def app_name(window):
    """Use the taskbar's friendly name or the installed app's name, never its desktop ID."""
    cls = str(window.get('class') or '')
    def readable(name):
        name = re.sub(r'\b(?:GNOME|KDE|Xfce)\b', '', str(name), flags=re.I)
        name = ' '.join(name.split())[:120]
        return name if name and not re.match(r'^(?:org|com|net)\.', name) else ''
    supplied = readable(window.get('appName') or '')
    if supplied:
        return supplied
    roots = [os.environ.get('XDG_DATA_HOME') or str(Path.home() / '.local/share')]
    roots += (os.environ.get('XDG_DATA_DIRS') or '/usr/local/share:/usr/share').split(':')
    for root in roots:
        for path in sorted((Path(root) / 'applications').glob('*.desktop')):
            entry = configparser.ConfigParser(interpolation=None, strict=False)
            try:
                entry.read(path)
                app = entry['Desktop Entry']
                if cls and cls.casefold() in (path.stem.casefold(), app.get('StartupWMClass', '').casefold()):
                    return readable(app.get('Name', '')) or 'This app'
            except (OSError, UnicodeError, configparser.Error, KeyError):
                continue
    return 'This app'


def context(kind, detail=''):
    if kind == 'window':
        window = json.loads(detail) if detail else json.loads(capture('hyprctl','activewindow','-j'))
        text = f"Title: {window.get('title','Untitled')}\nApp: {app_name(window)}"
        prompt = 'Help me with this window.'
    elif kind == 'error':
        text, prompt = detail[:12000], 'Help me understand this error.'
    else:
        text = detail or selection()
        prompt = PROMPTS.get(kind)
        if not prompt: raise ValueError('Choose a writing action.')
    label = 'Window' if kind == 'window' else 'Error details' if kind == 'error' else 'Selected text'
    return f'{prompt}\n\n{label}:\n{text}'


def main():
    kind = sys.argv[1] if len(sys.argv) > 1 else 'window'
    text = writing_choice() if kind == 'writing' else context(kind, sys.stdin.read(12000) if kind == 'error' else sys.argv[2] if len(sys.argv)>2 else '')
    root = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}')
    fd, name = tempfile.mkstemp(prefix='ask-draft-', dir=root)
    with os.fdopen(fd,'w') as stream: stream.write(text)
    subprocess.run(['starchaser', 'ask', 'ui'], check=True)
    try:
        for _ in range(30):
            if subprocess.run(['qs','-p',str(Path.home() / '.config/quickshell/ask'),'ipc','call','ask','draftFile',name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0: return
            time.sleep(.1)
        raise RuntimeError("Ask didn't open. Try again.")
    finally:
        # FileView reads asynchronously; it deletes this file after reading.
        pass

if __name__ == '__main__':
    from starchaser_cli import safe_streams
    safe_streams()
    if any(word in ('-h', '--help', 'help') for word in sys.argv[1:]):
        print(__doc__)
        sys.exit(0)
    try: main()
    except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as e: sys.exit(str(e))
