#!/usr/bin/env python3
"""Drive a real protocol-1 host and its protocol-2 upgrade with the same identity.
Usage: host-driver.py LEGACY_CHECKOUT CURRENT_CHECKOUT LEGACY_HOME UPGRADED_HOME RUN_DIR
Inputs on stdin: legacy, current, quit. Each switch stops only the child it spawned.
Before use: link the legacy home to the factory relay via the real CLI, stop it,
then copy that synthetic home to UPGRADED_HOME. No mocked services or responses.
Load the test-stage environment before running; logs contain secrets and stay local.
"""
import datetime,json,os,pathlib,signal,subprocess,sys,time,urllib.request
legacy,current,legacy_home,current_home,out=sys.argv[1:]
run=pathlib.Path(out)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run.mkdir(parents=True)
child=None
seq=0

def stop():
    global child
    if child is not None and child.poll() is None:
        child.send_signal(signal.SIGINT)
        child.wait(timeout=45)
    child=None
try:
    for command in sys.stdin:
        command=command.strip()
        if command not in ('legacy','current','quit'): continue
        stop()
        if command=='quit': break
        seq+=1
        cwd,home=(legacy,legacy_home) if command=='legacy' else (current,current_home)
        env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_ENVIRONMENT_LABEL':'Upgrade proof host'}
        log=open(run/f'{seq}-{command}.log','w')
        child=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','0.0.0.0','--port','14601','--base-dir',home],cwd=cwd,env=env,stdout=log,stderr=subprocess.STDOUT)
        for attempt in range(90):
            if child.poll() is not None: raise RuntimeError('host exited; inspect local log')
            try:
                with urllib.request.urlopen('http://127.0.0.1:14601/.well-known/t3/environment',timeout=1) as response: descriptor=json.load(response)
                print(json.dumps({'transition':command,'at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'protocol':descriptor.get('orchestrationProtocolVersion')}),flush=True)
                break
            except OSError: time.sleep(1)
        else: raise RuntimeError('host did not start')
finally:
    stop()
