#!/usr/bin/env python3
"""Portable form of the scratch fixture commands used for the Retry recordings.

Usage: python3 service-fixture.py <prepare|run|fail|upgrade> CHECKOUT OUTPUT PORT
Run prepare, then run in a retained terminal. Pair the browser, disable real providers,
create a synthetic project, run fail, and start the sidebar update. After failure,
stop the retained run with Ctrl-C, run upgrade, and run again. Keep the browser open.
The only app-file edit is apps/server/package.json's version metadata.
"""
import json, os, pathlib, shutil, subprocess, sys
mode, checkout_arg, output_arg, port = sys.argv[1:]
checkout = pathlib.Path(checkout_arg).resolve()
output = pathlib.Path(output_arg).resolve()
home = output / 'home'
node = shutil.which('node')

def package_version(version):
    package = checkout / 'apps/server/package.json'
    data = json.loads(package.read_text())
    data['version'] = version
    package.write_text(json.dumps(data, indent=2) + '\n')

def select(version):
    (home / 'runtime/service-state.json').write_text(json.dumps({'protocol': 4, 'activeVersion': version}))

def runtime(version, fail=False):
    folder = home / 'runtime/versions' / version
    folder.mkdir(parents=True, exist_ok=True)
    script = '#!/bin/sh\nexit 1\n' if fail else '#!/bin/sh\nexec '+str(node)+' '+str(checkout/'apps/server/src/bin.ts')+' "$@"\n'
    (folder / 't3').write_text(script)
    (folder / 't3').chmod(0o755)
    (folder / '.install-complete').write_text(version)

if mode == 'prepare':
    output.mkdir(parents=True, exist_ok=True)
    runtime('0.1.8')
    runtime('0.1.9')
    package_version('0.1.8')
    select('0.1.8')
    (output / 'launch.mjs').write_text('import {main} from '+json.dumps(str(checkout/'apps/server/src/serviceLauncher.ts'))+'; await main();\n')
    (home / 'service.env').write_text('T3CODE_PORT='+port+'\nT3CODE_HOST=127.0.0.1\nT3CODE_NO_BROWSER=true\nT3CODE_DEV_SEED=0\nT3CODE_TELEMETRY_ENABLED=false\n')
elif mode == 'run':
    subprocess.run([node, str(output/'launch.mjs')], cwd=checkout, env={**os.environ, 'T3CODE_DEV_SEED':'0', 'T3CODE_HOME':str(home)})
elif mode == 'fail':
    # After server startup pruning: intentionally fail the real staged preflight.
    runtime('0.1.9', fail=True)
elif mode == 'upgrade':
    # The service must be stopped; the browser stays open with its failed run retained.
    package_version('0.1.9')
    runtime('0.1.9')
    select('0.1.9')
else:
    raise SystemExit('unknown mode')
