import os, sys, sqlite3, time, subprocess, hashlib, stat, datetime
from pathlib import Path
checkout, output, label, sha = sys.argv[1:]
run = Path(output) / (label + '-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
home = run / 'home'
(home / 'userdata/attachments').mkdir(parents=True)
os.chmod(home / 'userdata', 0o755)
with sqlite3.connect(home / 'userdata/statev2.sqlite') as db:
    db.execute('CREATE TABLE fixture (id INTEGER)')
upload = home / 'userdata/attachments/upload.part'
upload.write_bytes(b'synthetic pending upload\n')
old = time.time() - 2*86400
os.utime(upload, (old, old))
def snapshot():
    lines=[]
    for p in [home, *sorted(home.rglob('*'))]:
        s=p.stat()
        name='.' if p==home else str(p.relative_to(home))
        lines.append(f'{stat.filemode(s.st_mode)} {name}' + (f' sha256={hashlib.sha256(p.read_bytes()).hexdigest()}' if p.is_file() else ''))
    return '\n'.join(lines)
before=snapshot()
env=dict(os.environ, T3CODE_TRACE_FILE=str(home/'trace/trace.ndjson'), NO_COLOR='1', T3CODE_DEV_SEED='0')
command=['node',str(Path(checkout)/'apps/server/dist/bin.mjs'),'doctor','--fix','--dry-run','--base-dir',str(home)]
result=subprocess.run(command, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=checkout)
after=snapshot()
text=f"{label.upper()} — real built CLI\nCommit: {sha}\nEnvironment: Linux x86_64, Node {subprocess.check_output(['node','--version'],text=True).strip()}, fresh synthetic data home\nCommand: T3CODE_TRACE_FILE=<home>/trace/trace.ndjson t3 doctor --fix --dry-run --base-dir <home>\nSeed: SQLite CREATE TABLE fixture; userdata mode 0755; upload.part aged 2 days\n\nBEFORE\n{before}\n\nCOMMAND OUTPUT (exit {result.returncode})\n{result.stdout}\nAFTER\n{after}\n\nFilesystem identical: {before==after}\n"
text=text.replace(str(home),'<home>').replace(checkout,'<checkout>')
(run/'transcript.txt').write_text(text)
print(text)
print('TRANSCRIPT '+str(run/'transcript.txt'))
