#!/usr/bin/env python3
"""Run the real CLI against an empty home; never modify the installed service.
Usage: python3 prove.py CHECKOUT OUTPUT_ROOT LABEL SHA
Only scratch-directory prefixes are replaced with <scratch> in public captures.
Requires node, ImageMagick convert, ffmpeg; no mocked commands or application code.
"""
import datetime, html, json, os, pathlib, subprocess, sys, textwrap, time
checkout, output_root, label, sha = sys.argv[1:]
root = pathlib.Path(output_root).resolve()
run = root / (label + '-' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S'))
run.mkdir(parents=True)
home = run / 'home-a'
home.mkdir()
lines = [f'{label.upper()} | {sha}', 'Linux / systemd user service / Node source CLI',
         'Empty scratch T3 home; existing service belongs to %h/.t3.',
         'Scratch path prefix normalized to <scratch>.', '']
frames=[]
start=time.monotonic()
def render():
    wrapped=[]
    for line in lines:
        wrapped.extend(textwrap.wrap(line, width=110, replace_whitespace=False, drop_whitespace=False) or [''])
    svg=['<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1120">', '<rect width="1600" height="1120" fill="#111827"/>']
    for i,line in enumerate(wrapped):
        color='#93c5fd' if line.startswith('$') else '#e5e7eb'
        svg.append(f'<text x="32" y="{40+i*27}" font-family="DejaVu Sans Mono" font-size="21" fill="{color}">{html.escape(line)}</text>')
    svg.append('</svg>')
    p=run/f'frame-{len(frames):03d}'
    p.with_suffix('.svg').write_text('\n'.join(svg))
    subprocess.run(['convert',str(p.with_suffix('.svg')),str(p.with_suffix('.png'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
    frames.append((str(p.with_suffix('.png')),time.monotonic()-start))
render()
commands=[
 ('systemctl --user is-active t3code.service', ['systemctl','--user','is-active','t3code.service']),
 ('node src/bin.ts service status', ['node','src/bin.ts','service','status']),
 ('node src/bin.ts uninstall --base-dir <scratch>/home-a --yes', ['node','src/bin.ts','uninstall','--base-dir',str(home),'--yes']),
 ('systemctl --user is-active t3code.service', ['systemctl','--user','is-active','t3code.service'])]
results=[]
for display,cmd in commands:
    lines.append('$ '+display); render()
    proc=subprocess.Popen(cmd,cwd=pathlib.Path(checkout)/'apps/server',stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,env={**os.environ,'NO_COLOR':'1','T3CODE_DEV_SEED':'0'})
    output=[]
    for line in proc.stdout:
        clean=line.rstrip('\n').replace(str(run),'<scratch>')
        output.append(clean); lines.append(clean); render()
    rc=proc.wait(); lines.append(f'[exit {rc}]'); lines.append(''); render()
    results.append({'command':display,'exit':rc,'output':'\n'.join(output)})
    time.sleep(1)
(run/'transcript.txt').write_text('\n'.join(lines)+'\n')
(run/'commands.json').write_text(json.dumps(results,indent=2))
subprocess.run(['cp',frames[-1][0],str(run/'capture.png')],check=True)
concat=[]
for i,(path,stamp) in enumerate(frames):
    duration=(frames[i+1][1]-stamp) if i+1<len(frames) else 4
    concat.extend([f"file '{path}'",f'duration {duration:.3f}'])
concat.append(f"file '{frames[-1][0]}'")
(run/'frames.txt').write_text('\n'.join(concat))
subprocess.run(['ffmpeg','-y','-loglevel','error','-f','concat','-safe','0','-i',str(run/'frames.txt'),'-vf','fps=12','-c:v','libx264','-pix_fmt','yuv420p',str(run/'recording.mp4')],check=True)
print(run)
print((run/'transcript.txt').read_text())
