"""Run from either installed checkout. No mocked provider or recorded answers."""
import json, os, pathlib, subprocess, tempfile, time, urllib.request
root = pathlib.Path.cwd()
run = pathlib.Path(tempfile.mkdtemp(prefix='pr-link-proof-'))
home = run / 't3home'
(home / 'userdata').mkdir(parents=True)
(home / 'userdata/settings.json').write_text(json.dumps({
    'sidebarAutoSettleOnMerge': False,
    'providerInstances': {'opencode': {'driver': 'opencode', 'enabled': True}}
}))
project = run / 'project'
project.mkdir()
subprocess.run(['git', 'init', '-q', str(project)], check=True)
cli = ['node', 'apps/server/src/bin.ts']
log = (run / 'server.log').open('w')
server = subprocess.Popen(cli + ['serve', '--base-dir', str(home), '--port', '38721'],
    env={**os.environ, 'T3CODE_DEV_SEED': '0'}, stdout=log, stderr=log)
try:
    for attempt in range(120):
        try:
            urllib.request.urlopen('http://127.0.0.1:38721', timeout=1)
            break
        except Exception:
            if server.poll() is not None: raise RuntimeError('Server exited')
            time.sleep(1)
    subprocess.run(cli + ['project', 'add', str(project), '--title', 'PR linking evidence', '--base-dir', str(home)], check=True)
    prompt = 'Load the link_pull_request tool. Quote its exact description, then say whether that description promises a linked PR merging will settle this thread. Auto-settle merged threads is off. Do not change files or link any PR. Base your answer on the actual loaded tool description, not assumptions.'
    reply = subprocess.run(cli + ['thread', 'start', str(project), prompt, '--provider', 'opencode', '--model', 'anthropic/claude-sonnet-5-5', '--title', 'PR linking description', '--wait', '--base-dir', str(home)], text=True, capture_output=True, check=True)
    print(reply.stdout)
    print('Persisted sidebarAutoSettleOnMerge:', json.loads((home / 'userdata/settings.json').read_text())['sidebarAutoSettleOnMerge'])
finally:
    server.terminate()
    server.wait(timeout=30)
    log.close()
