#!/usr/bin/env python3
"""Run the same real, locally built CLI on two commits; save verbatim output.
Usage: python3 capture-cli.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_DIRECTORY
Requires each checkout's apps/server/dist/bin.mjs (vp run build:bundle).
No mocks, real-user state, service installation, or network access are needed.
"""
import os, sys, subprocess, pathlib, datetime, re, time
from PIL import Image, ImageDraw, ImageFont
base, head, output = map(pathlib.Path, sys.argv[1:])
run = output / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run.mkdir(parents=True)
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 19)
for side, checkout in [('before', base), ('after', head)]:
    cwd = run / side
    cwd.mkdir()
    env = dict(os.environ)
    for key in list(env):
        if key.startswith('T3CODE_') or key in ('VITE_HTTP_URL','VITE_WS_URL'):
            env.pop(key)
    env.update(DBUS_SESSION_BUS_ADDRESS='unix:path=' + str(cwd / 'absent-bus'),
               XDG_CONFIG_HOME=str(cwd / 'xdg'), T3CODE_DEV_SEED='0', NO_COLOR='1', TERM='dumb')
    sha = subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    text = f'{side.upper()} | {sha[:10]} | Linux CLI transcript\n'
    text += 'Built CLI; fresh selected home; isolated user bus/config; stdin non-TTY.\n'
    text += 'Commands run from the same relative directory in separate fresh fixtures.\n\n'
    for args in [('status',), ('up','--no-lan'), ('status',)]:
        command = [args[0], '--base-dir', './t3-other', *args[1:]]
        result = subprocess.run(['node',str(checkout / 'apps/server/dist/bin.mjs'),*command],
            cwd=cwd,env=env,stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=60)
        text += '$ t3 ' + ' '.join(command) + '\n' + result.stdout + f'[exit {result.returncode}]\n\n'
    text = re.sub(r'\x1b\[[0-9;]*m','',text)
    (run / (side+'.txt')).write_text(text)
    print(text)
    lines = text.splitlines()
    width = 1320
    height = 120 + len(lines)*29
    def draw():
        image = Image.new('RGB',(width,height),'#111827')
        d = ImageDraw.Draw(image)
        d.text((28,25),'PR 31878 — real CLI output',font=font,fill='#93c5fd')
        for n,line in enumerate(lines):
            d.text((28,80+n*29),line,font=font,fill=('#86efac' if line.startswith('$') else '#e5e7eb'))
        return image
    first = draw()
    time.sleep(.5)
    second = draw()
    assert first.tobytes() == second.tobytes()
    second.save(run / (side+'.png'))
print('Evidence directory:',run)
