#!/usr/bin/env python3
"""Consolidated seed/CLI driver used for the manual browser proof.

Usage: reproduce.py CHECKOUT OUTPUT_ROOT OPENCODE_2_BINARY CONFIG_JSON
Run once per checkout, using a fresh OUTPUT_ROOT for each side.
CONFIG_JSON must provide an authenticated anthropic provider; it is never exported.
After prepare: run T3CODE_DEV_SEED=0 vp run dev in CHECKOUT, then execute the
printed thread-start command. Pair the browser using the dev server's URL.
Browser: open the returned thread by its environment/thread link, hide the thread
details panel, record, type /compact and click Submit message. Wait for the
Context compaction divider, open Usage, select OpenCode only, Tokens, 30 days,
and Refresh usage. Wait for aria-busy=false before taking two identical captures.
Do the same on both commits. Real model output and token counts naturally vary.
"""
import datetime
import json
import pathlib
import shlex
import subprocess
import sys

checkout, parent, binary, source_config = map(pathlib.Path, sys.argv[1:])
root = parent / datetime.datetime.now(datetime.timezone.utc).strftime('run-%Y%m%dT%H%M%S%fZ')
root.mkdir(parents=True)
config = root / 'config'
config.mkdir()
source = json.loads(source_config.read_text())
target = config / 'opencode.json'
target.write_text(json.dumps({'provider': source['provider']}))
target.chmod(0o600)
settings_file = checkout / '.t3/userdata/settings.json'
settings_file.parent.mkdir(parents=True, exist_ok=True)
settings = json.loads(settings_file.read_text()) if settings_file.exists() else {}
settings['idleCompaction'] = 'off'
settings.setdefault('providerInstances', {})['opencode'] = {
    'driver': 'opencode', 'enabled': True,
    'config': {'enabled': True, 'binaryPath': str(binary.resolve())},
    'environment': [
        {'name': name, 'value': str(root / directory), 'sensitive': False}
        for name, directory in [
            ('OPENCODE_CONFIG_DIR', 'config'), ('XDG_DATA_HOME', 'data'),
            ('XDG_STATE_HOME', 'state'), ('XDG_CACHE_HOME', 'cache')
        ]
    ]
}
settings_file.write_text(json.dumps(settings))
workspace = root / 'lighthouse-demo'
workspace.mkdir()
subprocess.run(['git', 'init', '--quiet', '--initial-branch=main', str(workspace)], check=True)
cli = ['node', 'apps/server/src/bin.ts']
add = cli + ['project', 'add', str(workspace), '--title', 'Lighthouse demo', '--base-dir', '.t3']
turn = cli + ['thread', 'start', str(workspace),
    'Write approximately 300 words about lighthouses. Do not use tools or change files.',
    '--title', 'Lighthouses', '--provider', 'opencode', '--model',
    'anthropic/claude-haiku-5-5', '--base-dir', '.t3', '--wait', '--json']
print('After starting the dev server, run from the checkout:')
print(shlex.join(add))
print(shlex.join(turn))
print('Then follow the browser steps in this file’s docstring.')
