#!/usr/bin/env python3
# summary: Copy a private-details-free problem report for review.
"""usage: starchaser problem report [get|copy]
Gather limited versions, model support names, and recent error counts locally.
copy opens the review in Settings before anything goes on the clipboard. Nothing is uploaded. Review before sharing.
Raw logs, account names, serial numbers, network names and addresses are omitted.
"""
import json
import platform
import subprocess
import sys
from pathlib import Path


def run(*args):
    try: return subprocess.run(args, capture_output=True, text=True, timeout=15)
    except (OSError, subprocess.SubprocessError): return subprocess.CompletedProcess(args, 1, '', '')


def last_update(path=Path('/var/lib/starchaser/last-update.json')):
    from datetime import datetime, timezone
    try:
        data = json.loads(path.read_text())
        stamp = data.get('time')
        if stamp is None and all(type(data.get(k)) is int and data[k] > 0 for k in ('number', 'last')):
            stamp = path.stat().st_mtime
        if type(stamp) not in (int, float) or not 946684800 <= stamp <= 4102444800:
            raise ValueError('timestamp')
        return 'Last update record (UTC): ' + datetime.fromtimestamp(stamp, timezone.utc).strftime('%Y-%m-%d %H:%M')
    except (OSError, ValueError, TypeError, AttributeError):
        return 'Last update: unavailable'


def report():
    lines = ['Starchaser problem report', 'Review before sharing. No raw log messages or device identifiers are included.',
             'Architecture: ' + platform.machine()]
    result = run('pacman', '-Q', 'starchaser-desktop', 'linux', 'hyprland', 'quickshell', 'pipewire', 'networkmanager')
    # Accept only known package names and version characters; never echo diagnostics.
    import re
    for line in result.stdout.splitlines():
        if re.fullmatch(r'(?:starchaser-desktop|linux|hyprland|quickshell|pipewire|networkmanager) [A-Za-z0-9.+_:~-]+', line):
            lines.append(line)
    sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'system/usr/local/lib/starchaser'))
    sys.path.append('/usr/local/lib/starchaser')
    import hardware
    profiles = hardware.model_quirks()
    lines.append('Model support: ' + (', '.join(row['title'] for row in profiles) or 'No matching model profile'))
    rows = hardware.detect()
    lines.append('Detected categories: ' + ', '.join(row['title'] for row in rows if row['detected']))
    result = run('journalctl', '--user', '--since=-1h', '--priority=0..3', '--output=json', '--no-pager', '-n', '200')
    count = sum(1 for line in result.stdout.splitlines() if line.startswith('{'))
    categories = {}
    for line in result.stdout.splitlines():
        try:
            message = json.loads(line).get('MESSAGE', '')
        except (ValueError, AttributeError):
            continue
        if not isinstance(message, str):
            continue
        category = 'Unclassified errors'
        for pattern, label in ((r'out of memory|oom|cannot allocate memory', 'Out of memory'),
                               (r'no space left|disk full', 'Storage full'),
                               (r'permission denied|not authorized', 'Permission denied'),
                               (r'timed? out|timeout', 'Timed out'),
                               (r'segfault|segmentation fault|core dumped', 'App crash'),
                               (r'failed to connect|connection refused|unreachable', 'Connection failed'),
                               (r'no such file|not found', 'Missing file or service')):
            if re.search(pattern, message, re.I):
                category = label
                break
        categories[category] = categories.get(category, 0) + 1
    lines.append('Recent user-session errors (past hour, up to 200): ' + (str(count) if result.returncode == 0 else 'Could not read'))
    lines.extend(label + ': ' + str(count) for label, count in sorted(categories.items()))
    if categories.get('Unclassified errors'):
        lines.append('Counts only. Raw messages are omitted to protect private details.')
    lines.append(last_update())
    lines.extend(['', 'What I expected:', 'What happened:', 'Steps to reproduce:'])
    return '\n'.join(lines)


def main(args):
    if args in (['-h'], ['--help']): print(__doc__); return 0
    if args not in ([], ['get'], ['copy']): print(__doc__, file=sys.stderr); return 2
    try:
        if args == ['copy']:
            opened = subprocess.run(['starchaser', 'settings', 'hardware', '@report'], timeout=10)
            if opened.returncode: raise ValueError("Settings couldn't open.")
            print(json.dumps({'ok': True, 'message': 'Review the report in Settings, then choose Copy this report.'})); return 0
        text = report()
        print(json.dumps({'ok': True, 'report': text, 'message': 'Report ready to review.'})); return 0
    except (OSError, ValueError, subprocess.SubprocessError):
        print(json.dumps({'ok': False, 'errors': "The problem report couldn't be prepared. Check that the desktop session is running and try again."})); return 1


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