"""Generalized version of the seed and CLI commands used for this proof.

For EACH checkout, with a fresh .t3 and installed dependencies:
  python3 reproduce.py setup CHECKOUT SCRATCH
  T3CODE_DEV_SEED=0 vp run dev   # in CHECKOUT, retain its PID
  EVIDENCE_MODEL=<available Claude model> python3 reproduce.py run CHECKOUT SCRATCH

Use a distinct SCRATCH directory per side. Open the resulting threads in the
web client, with the same 1280x800 viewport and light theme. Record starting a
new empty-settings thread and opening it until its reply completes. Crop out
composer/model metadata and environment details before publishing captures.
The empty file simulates the outcome of truncation, not a timed second process.
Credentials remain local; do not upload scratch homes or raw provider logs.
"""
import json, os, pathlib, subprocess, sys
phase, checkout_arg, scratch_arg = sys.argv[1:]
checkout = pathlib.Path(checkout_arg).resolve()
scratch = pathlib.Path(scratch_arg).resolve()
home = scratch / 'claude'
project = scratch / 'project'

def cli(*args):
    return subprocess.run(['node', 'apps/server/src/bin.ts', *args], cwd=checkout, check=True, text=True, capture_output=True).stdout

if phase == 'setup':
    home.mkdir(parents=True, exist_ok=True)
    source = json.loads((pathlib.Path.home()/'.claude/settings.json').read_text()).get('env', {})
    env = {k:v for k,v in source.items() if k in ['ANTHROPIC_BASE_URL','ANTHROPIC_AUTH_TOKEN','NODE_EXTRA_CA_CERTS']}
    (home/'settings.json').write_text(json.dumps({'env':env}))
    (home/'remote-settings.json').write_text('{}')
    project.mkdir(exist_ok=True)
    subprocess.run(['git','init','-q',str(project)],check=True)
    subprocess.run(['git','-C',str(project),'-c','user.name=Evidence','-c','user.email=evidence@example.com','commit','--allow-empty','-qm','fixture'],check=True)
    settings = checkout/'.t3/userdata/settings.json'
    settings.parent.mkdir(parents=True, exist_ok=True)
    data = json.loads(settings.read_text()) if settings.exists() else {}
    data.setdefault('providerInstances', {})['claudeRace'] = {'driver':'claudeAgent','displayName':'Claude permission check','config':{'homePath':str(home)}}
    settings.write_text(json.dumps(data))
elif phase == 'run':
    print(cli('project','add','--base-dir','.t3','--title','Permission race reproduction',str(project)))
    for title, contents in [('Control: valid settings','{}'), ('Empty settings during rewrite','')]:
        (home/'remote-settings.json').write_text(contents)
        print(title)
        print(cli('thread','start','--base-dir','.t3','--provider','claudeRace','--model',os.environ['EVIDENCE_MODEL'],'--title',title,'--wait',str(project),'Reply with just OK.'))
else:
    raise SystemExit('phase must be setup or run')
