import pathlib, subprocess, os, time, socket, datetime, sys
out=pathlib.Path(__file__).parent / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir()
paths=['/app.txt','/..notes.txt','/..assets/file.txt','/../package.json','/%2e%2e/package.json','/..%2Fpackage.json']
for side, checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    root=pathlib.Path(checkout)
    dist=root/'apps/web/dist'
    (dist/'..assets').mkdir(parents=True,exist_ok=True)
    for name,body in [('index.html','<!doctype html><title>Static proof</title>SPA INDEX BODY'),('app.txt','APP BODY'),('..notes.txt','NOTES BODY'),('..assets/file.txt','ASSET BODY')]:
        (dist/name).write_text(body)
    with socket.socket() as s:
        s.bind(('127.0.0.1',0)); port=s.getsockname()[1]
    log=(out/f'{side}-private-server.log').open('w')
    env=dict(os.environ,T3CODE_DEV_SEED='0')
    env.pop('VITE_DEV_SERVER_URL',None)
    p=subprocess.Popen(['node','apps/server/src/bin.ts','--host','127.0.0.1','--port',str(port),'--base-dir',str(out/f'{side}-state'),'--no-browser'],cwd=root,env=env,stdout=log,stderr=log)
    try:
        for i in range(120):
            if p.poll() is not None: raise RuntimeError('Server exited; inspect private log')
            try:
                r=subprocess.run(['curl','--silent','--output','/dev/null','--write-out','%{http_code}',f'http://127.0.0.1:{port}/app.txt'],capture_output=True,text=True)
                if r.stdout == '200': break
                time.sleep(.25)
            except OSError: time.sleep(.25)
        else: raise RuntimeError('Server did not listen')
        sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip()
        lines=[f'{side.upper()} — real T3 Code HTTP server',f'Commit: {sha}','Environment: Linux; Node '+subprocess.check_output(['node','--version'],text=True).strip(), 'Fresh isolated state; synthetic apps/web/dist; loopback HTTP; no dev proxy.','Driver: curl --path-as-is -i; identical fixtures and requests on both commits.','']
        for path in paths:
            r=subprocess.run(['curl','--silent','--show-error','--path-as-is','-i',f'http://127.0.0.1:{port}{path}'],capture_output=True,text=True,check=True)
            lines += ['GET '+path,r.stdout,'']
        capture=out/f'{side}-responses.txt'
        capture.write_text('\n'.join(lines))
        print(capture.read_text(),flush=True)
    finally:
        p.terminate()
        try: p.wait(timeout=15)
        except subprocess.TimeoutExpired: p.kill(); p.wait()
        log.close()
print('OUTPUT: '+str(out))
