#!/usr/bin/env python3
"""Capture the real Android app after opening a seeded thread and enabling airplane mode.
Usage: capture.py SESSION OUTPUT_DIRECTORY LABEL [--video]
The caller launches the matching checkout's Metro/dev client and pairs its fresh server.
"""
import json, pathlib, subprocess, sys, time
session, output, label = sys.argv[1:4]
video = '--video' in sys.argv[4:]
out = pathlib.Path(output)
out.mkdir(parents=True, exist_ok=True)
def device(*args):
    return subprocess.run(['agent-device', *args, '--session', session], check=True, capture_output=True, text=True).stdout
if video:
    device('record', 'start', str(out / f'{label}.mp4'), '--hide-touches')
raw = device('snapshot', '--raw', '--json')
(out / f'{label}-raw.json').write_text(raw)
data = json.loads(raw)['data']
pill = [n for n in data['nodes'] if n.get('label') == 'You are offline' and n.get('type') == 'android.widget.Button']
summary = {'label': label, 'viewport': data.get('viewport'), 'androidSnapshot': data.get('androidSnapshot'), 'pill': pill,
 'anchors': [{k:n.get(k) for k in ('label','type','rect','visibleToUser')} for n in data['nodes'] if n.get('label') in ['Ask anything', 'Agent: Show a short greeting.', 'first fixture turn complete','Agent: Ask a question.', 'Strict schemas (Recommended)', 'UI flexibility','Submit answers']]}
(out / f'{label}-summary.json').write_text(json.dumps(summary, indent=2))
if video:
    time.sleep(5)
    device('record', 'stop')
else:
    for attempt in range(4):
        a = out / f'{label}-{attempt}-a.png'
        b = out / f'{label}-{attempt}-b.png'
        device('screenshot', str(a))
        time.sleep(.5)
        device('screenshot', str(b))
        result = subprocess.run(['compare', '-metric', 'AE', str(a), str(b), 'null:'], capture_output=True, text=True)
        if result.returncode == 0:
            (out / f'{label}.png').write_bytes(b.read_bytes())
            summary['stableScreenshotPair'] = [a.name, b.name]
            summary['changedPixels'] = 0
            (out / f'{label}-summary.json').write_text(json.dumps(summary, indent=2))
            break
    else:
        raise SystemExit('No identical screenshot pair; use video for a changing screen.')
print(json.dumps(summary, indent=2))
