#!/usr/bin/env python3
"""Manual real-app proof helper. Run against each revision in its own checkout/home.

Set GOOGLE_GEMINI_BASE_URL externally to the available API-key endpoint.
1. python reproduce.py init CHECKOUT HOME
2. T3CODE_DEV_SEED=0 vp run dev --home-dir HOME  (from CHECKOUT, retain session)
3. Once listening: python reproduce.py seed CHECKOUT HOME
4. Stop that server using its retained terminal session.
5. python reproduce.py stale CHECKOUT HOME
6. Restart with the same command and environment; pair the web browser.
7. python reproduce.py observe CHECKOUT HOME
8. In the blank thread, close thread details, open the model picker, click
   Antigravity. Record this interaction and the resulting full model list.
   Do not chat or press Refresh after the stale-cache restart.

Use a fresh HOME per side. This helper never reads the installed app's data.
"""
import datetime
import json
import os
import pathlib
import subprocess
import sys

phase, checkout_arg, home_arg = sys.argv[1:]
checkout = pathlib.Path(checkout_arg).resolve()
home = pathlib.Path(home_arg).resolve()
cache = home / 'caches/antigravity.json'
settings = home / 'userdata/settings.json'
if phase == 'init':
    if settings.exists():
        raise SystemExit('Refusing to overwrite an existing home')
    settings.parent.mkdir(parents=True, exist_ok=True)
    settings.write_text(json.dumps({
        'providerHealthRefreshInterval': 60000,
        'providerInstances': {'antigravity': {
            'driver': 'antigravity', 'enabled': True,
            'config': {'enabled': True, 'authMethod': 'gemini-api-key',
                       'apiKey': 'dummy-key'},
        }},
    }, indent=2))
elif phase == 'seed':
    cli = ['node', 'apps/server/src/bin.ts']
    subprocess.run(cli + ['project', 'add', '--base-dir', str(home),
                         '--title', 'Model discovery proof', str(checkout)],
                   cwd=checkout, check=True)
    subprocess.run(cli + ['thread', 'start', '--base-dir', str(home),
                         '--provider', 'antigravity', '--model', 'gemini-3.8-flash',
                         '--wait', str(checkout), 'Reply with only the word ok.'],
                   cwd=checkout, check=True)
elif phase == 'stale':
    data = json.loads(cache.read_text())
    if not any(m['slug'] == 'gemini-4-neon' for m in data['models']):
        raise SystemExit('Seed session did not discover Neon')
    data['models'] = [m for m in data['models'] if m['slug'] != 'gemini-4-neon']
    cache.write_text(json.dumps(data, indent=2))
    print('Cached model count:', len(data['models']))
elif phase == 'observe':
    data = json.loads(cache.read_text())
    print(json.dumps({
        'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
        'checkedAt': data['checkedAt'],
        'models': [m['slug'] for m in data['models']],
    }, indent=2))
else:
    raise SystemExit('Unknown phase')
