import argparse, subprocess, pathlib, os, time, json, re, urllib.request, urllib.error, signal
p=argparse.ArgumentParser(); p.add_argument('--checkout',required=True); p.add_argument('--home',required=True); p.add_argument('--output',required=True); p.add_argument('--port',required=True); a=p.parse_args()
out=pathlib.Path(a.output); out.mkdir(parents=True,exist_ok=True)
home=pathlib.Path(a.home); transcript=[]; server=None
base=['node','apps/server/src/bin.ts']
def clean(s):
    s=re.sub(r'\x1b\[[0-9;?]*[A-Za-z]','',s)
    s=s.replace(a.home,'<isolated test home>').replace(a.checkout,'<checkout>')
    s=re.sub(r'factory-agent-\d\+clerk_test@ping.gg','<test account>',s)
    s=re.sub(r'Path: .*','Path: <isolated tunnel-client install>',s)
    return s

def show(s,clear=False):
    s=clean(s); transcript.append(s)
    if clear: print('\033[2J\033[H',end='')
    print(s,flush=True)
    (out/'transcript.txt').write_text('\n\n'.join(transcript))

def cli(*args):
    r=subprocess.run(base+list(args)+['--base-dir',a.home],cwd=a.checkout,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,env=os.environ,timeout=50)
    return r.stdout

def start():
    global server
    log=open(out/f'server-{time.time_ns()}.private.log','w')
    server=subprocess.Popen(base+['serve','--base-dir',a.home,'--port',a.port,'--no-browser'],cwd=a.checkout,stdout=log,stderr=subprocess.STDOUT,env=os.environ)

def stop():
    global server
    if server is not None:
        server.terminate()
        try: server.wait(timeout=20)
        except subprocess.TimeoutExpired: server.kill(); server.wait()
        server=None

def status_until(predicate):
    deadline=time.monotonic()+180
    while time.monotonic()<deadline:
        s=cli('connect','status')
        if predicate(s): return s
        time.sleep(2)
    raise RuntimeError('Status did not reach the required real-world condition: '+clean(s))

sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=a.checkout,text=True).strip()
print('\033[?25l',end='')
try:
    show(f'T3 CONNECT — real CLI proof | commit {sha[:10]}\nLinux · fresh isolated data · test relay · same steps on both commits\nAccount authorized with connect login --headless; connect link completed.\nPaths and test-account identity omitted from displayed command output.',True)
    show('$ t3 serve\nStarting the real server and waiting for a reachable tunnel...')
    start()
    healthy=status_until(lambda s:'Other devices can reach this machine' in s)
    show('$ t3 connect status\n'+healthy)
    time.sleep(3)
    token=json.loads((home/'userdata/secrets/cloud-cli-oauth-token.bin').read_text())['accessToken']
    env_id=(home/'userdata/environment-id').read_text().strip()
    relay=os.environ['T3CODE_RELAY_URL'].rstrip('/')
    request_script="""let input=''; for await (const c of process.stdin) input+=c; const {url,token}=JSON.parse(input); const r=await fetch(url,{method:'DELETE',headers:{Authorization:'Bearer '+token}}); console.log(JSON.stringify({code:r.status,body:await r.text()}));"""
    response=subprocess.run(['node','--input-type=module','-e',request_script],input=json.dumps({'url':relay+'/v1/client/environment-links/'+env_id,'token':token}),text=True,stdout=subprocess.PIPE,check=True,timeout=60)
    revoked=json.loads(response.stdout);code=revoked['code'];body=revoked['body']
    show('Revoking this test environment through relay DELETE /v1/client/environment-links/<id>\nRelay response: HTTP '+str(code)+'\n'+body)
    broken=status_until(lambda s:'1016' in s)
    show(f'AFTER REVOCATION | commit {sha[:10]}\n$ t3 connect status\n'+broken,True)
    (out/'after-revocation.txt').write_text(clean(broken))
    facts=json.loads(cli('connect','status','--json'))['reachability']
    (out/'reachability.json').write_text(json.dumps(facts,indent=2))
    (out/'revocation-ready').touch()
    time.sleep(5)
    show('$ stop server; t3 serve\nFollowing the restart advice once...')
    stop(); start()
    restarted=status_until(lambda s:'1016' in s or 'Other devices can reach this machine' in s)
    show(f'AFTER ONE RESTART | commit {sha[:10]}\n$ t3 connect status\n'+restarted,True)
    (out/'after-restart.txt').write_text(clean(restarted))
    (out/'result.json').write_text(json.dumps({'sha':sha,'saw1016':True,'restartAdvice':'Fix: Restart T3 Code' in broken,'relinkAdvice':'Fix: Link this environment again.' in broken,'afterRestartReachable':'Other devices can reach this machine' in restarted},indent=2))
    (out/'done').touch()
    time.sleep(15)
finally:
    stop()
