#!/usr/bin/env python3
"""Synthetic reproduction; run identically in each commit's isolated dev server.

Start each checkout with T3CODE_DEV_SEED=0 vp run dev first.
Set PROBE_MODEL to the same available OpenCode model on both runs.
Run: python3 reproduce.py CHECKOUT WORKSPACE_ROOT OUTPUT_DIR
The output directory must be new. No live application data is used.
AI-assisted; verified with the tests and tools listed above.
"""
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys

checkout, workspace_root, output = map(lambda p: Path(p).resolve(), sys.argv[1:])
output.mkdir(parents=True, exist_ok=False)
workspace_root.mkdir(parents=True, exist_ok=True)
home = checkout / '.t3'

def command(args, cwd=checkout):
    return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout

def cli(args):
    return command(['node', 'apps/server/src/bin.ts', *args, '--base-dir', str(home)])

for title in ['Project A', 'Project B']:
    workspace = workspace_root / title
    workspace.mkdir(exist_ok=True)
    if not (workspace / '.git').exists():
        command(['git', 'init', '-q', '--initial-branch=main'], workspace)
        (workspace / 'README.md').write_text('Synthetic browser access reproduction.\n')
        command(['git', 'add', '.'], workspace)
        command(['git', '-c', 'user.name=Evidence', '-c', 'user.email=evidence@example.invalid',
                 'commit', '-qm', 'Initial'], workspace)
    with sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro', uri=True) as db:
        exists = db.execute('select 1 from projection_projects where workspace_root=?',
                            (str(workspace),)).fetchone()
    if not exists:
        cli(['project', 'add', str(workspace), '--title', title])

with sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro', uri=True) as db:
    project_a = db.execute('select project_id from projection_projects where workspace_root=?',
                           (str(workspace_root / 'Project A'),)).fetchone()[0]
settings_file = home / 'userdata/settings.json'
settings = json.loads(settings_file.read_text())
settings['projectSettingsOverrides'] = {project_a: {'enableAgentBrowserAccess': True}}
# Global browser access is deliberately omitted: its default is on.
settings.pop('enableAgentBrowserAccess', None)
settings.setdefault('providerInstances', {})['opencode'] = {'driver': 'opencode', 'enabled': True}
settings_file.write_text(json.dumps(settings, indent=2))

prompt = ('Call preview_status exactly once. Do not open or navigate a tab. '
          'Report whether the tool was denied by permissions or returned normal browser status. '
          'Quote the actual tool response. Do not mention model identifiers or filesystem paths.')
result = cli(['thread', 'start', str(workspace_root / 'Project B'), prompt,
              '--provider', 'opencode', '--model', os.environ['PROBE_MODEL'],
              '--title', 'Browser access proof', '--json'])
(output / 'launched.json').write_text(result)
print(result, end='')
