"""Real T3 server + stalled FUSE mount, same public HTTP/WS client sequence per commit.
Usage: python3 prove.py CHECKOUT SIDE [--smoke]
Dependencies: pip install fusepy websockets (or place them in ./python).
No server source is patched; UV_THREADPOOL_SIZE is left unset (Node default: four).
"""
import os, sys, json, time, subprocess, pathlib, uuid, urllib.request, asyncio, signal, socket
ROOT=pathlib.Path(__file__).parent
sys.path.insert(0,str(ROOT/'python'))
from websockets.asyncio.client import connect
checkout=pathlib.Path(sys.argv[1]); side=sys.argv[2]; smoke='--smoke' in sys.argv
run=ROOT/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); run.mkdir()
home=run/'data'; workspace=run/'workspace'; healthy=run/'healthy'
for p in [workspace/'api',workspace/'stalled',healthy/'service']:
    p.mkdir(parents=True)
for p in [workspace/'api',healthy/'service']:
    subprocess.run(['git','init','-q',str(p)],check=True)
start=time.monotonic(); entries=[]; server=None; mount=None; ws=None; jobs=[]
cast=open(run/'session.cast','w'); transcript=open(run/'transcript.txt','w')
cast.write(json.dumps({'version':2,'width':112,'height':32,'timestamp':int(time.time()),'title':'T3 Code real-server stalled-directory reproduction'})+'\n')
def say(msg):
    elapsed=time.monotonic()-start
    line=f'[{elapsed:6.1f}s] {msg}'
    print(line,flush=True); transcript.write(line+'\n'); transcript.flush()
    cast.write(json.dumps([round(elapsed,3),'o',line+'\r\n'])+'\n'); cast.flush()
    entries.append({'elapsed':elapsed,'text':msg})
def http(path, data=None, timeout=5, auth=True):
    headers={'Content-Type':'application/json'}
    if auth: headers['Authorization']='Bearer '+token
    req=urllib.request.Request(origin+path,data=json.dumps(data).encode() if data is not None else None,headers=headers)
    t=time.monotonic()
    try:
        with urllib.request.urlopen(req,timeout=timeout) as resp:
            return {'ok':True,'status':resp.status,'seconds':round(time.monotonic()-t,3),'body':json.load(resp)}
    except Exception as e:
        return {'ok':False,'seconds':round(time.monotonic()-t,3),'error':type(e).__name__}
def blocked():
    p=run/'mount-events.jsonl'
    if not p.exists(): return (0,0)
    data=[json.loads(s) for s in p.read_text().splitlines()]
    return (sum(x['event']=='opendir entered' for x in data),sum(x['event']=='opendir released' for x in data))
def show_http(label,result):
    say(f"{label}: {'HTTP '+str(result['status']) if result['ok'] else 'TIMEOUT / '+result['error']} ({result['seconds']:.3f}s)")
def project(title,path):
    return http('/api/projects/mutate',{'type':'project.create','commandId':str(uuid.uuid4()),'projectId':str(uuid.uuid4()),'title':title,'workspaceRoot':str(path)},timeout=12)
async def rpc(rid,path,timeout=5):
    t=time.monotonic()
    await ws.send(json.dumps({'_tag':'Request','id':str(rid),'tag':'workspace.scanFolders','payload':{'workspaceRoot':str(path)},'headers':[]}))
    try:
        async with asyncio.timeout(timeout):
            while True:
                msg=json.loads(await ws.recv())
                for m in msg if isinstance(msg,list) else [msg]:
                    if str(m.get('requestId'))==str(rid) and m.get('_tag')=='Exit':
                        ex=m['exit']; success=ex.get('_tag')=='Success'
                        folders=ex.get('value',{}).get('folders',[]) if success else []
                        return {'ok':success,'seconds':round(time.monotonic()-t,3),'folders':[f['name'] for f in folders],'exit':ex}
    except TimeoutError:
        return {'ok':False,'seconds':round(time.monotonic()-t,3),'error':'timeout'}
def show_scan(label,result):
    say(f"{label}: {'returned' if result['ok'] else result.get('error','error')} in {result['seconds']:.3f}s; repositories={result.get('folders',[])}")
async def main():
    global server,mount,ws,token,origin
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    say('T3 Code real server | '+side+' | '+sha)
    say('Linux; isolated fresh database; default four libuv workers; HTTP + WebSocket client')
    mount=subprocess.Popen([sys.executable,str(ROOT/'stalled-mount.py'),str(workspace/'stalled'),str(run/'release'),str(run/'mount-events.jsonl')],stdout=open(run/'mount-private.log','w'),stderr=subprocess.STDOUT)
    for _ in range(100):
        if os.path.ismount(workspace/'stalled'): break
        if mount.poll() is not None: raise RuntimeError('FUSE mount failed; see private mount log')
        await asyncio.sleep(.05)
    else: raise RuntimeError('FUSE not mounted')
    env=os.environ.copy(); env.pop('UV_THREADPOOL_SIZE',None); env['T3CODE_DEV_SEED']='0'
    with socket.socket() as free:
        free.bind(('127.0.0.1',0)); port=str(free.getsockname()[1])
    server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',port,'--no-browser','--base-dir',str(home)],cwd=checkout,env=env,stdout=open(run/'server-private.log','w'),stderr=subprocess.STDOUT)
    runtime=home/'userdata/server-runtime.json'
    for _ in range(600):
        if runtime.exists(): break
        if server.poll() is not None: raise RuntimeError('Server exited; see private server log')
        await asyncio.sleep(.1)
    else: raise RuntimeError('Server startup timeout')
    origin=json.loads(runtime.read_text())['origin']
    issued=subprocess.run(['node','apps/server/src/bin.ts','auth','session','issue','--token-only','--label','stalled-directory-proof','--base-dir',str(home)],cwd=checkout,env=env,text=True,capture_output=True,timeout=30)
    if issued.returncode: raise RuntimeError('Auth session issue failed')
    token=issued.stdout.strip()
    ticket=http('/api/auth/websocket-ticket',{})
    if not ticket['ok']: raise RuntimeError('WS ticket failed')
    ws=await connect(origin.replace('http','ws',1)+'/ws?orchestrationProtocol=2&wsTicket='+urllib.parse.quote(ticket['body']['ticket']))
    say('Independent client authenticated over HTTP and WebSocket')
    r=await asyncio.to_thread(project,'Healthy project',healthy); show_http('Create ordinary project',r)
    if not r['ok']: raise RuntimeError('Healthy project creation failed')
    r=await rpc(1,healthy); show_scan('Baseline healthy discovery',r)
    initial=await asyncio.to_thread(http,'/.well-known/t3/environment',auth=False); show_http('Baseline environment',initial)
    r=await asyncio.to_thread(project,'Blocked listing project',workspace); show_http('Add project containing api/.git + stalled FUSE child',r)
    if not r['ok']: raise RuntimeError('Blocked project creation failed')
    s=await rpc(2,workspace); show_scan('Baseline project discovery',s)
    (run/'release.stall').touch()
    say('Enable stall: FUSE opendir now waits indefinitely until release')
    results=[]
    for i in range(1, 2 if smoke else 5):
        await asyncio.sleep(3 if smoke else 31.5)
        say(f'Project read #{i} (interval '+('3s smoke' if smoke else '>30s')+')')
        r=await asyncio.to_thread(http,'/api/projects'); show_http('GET /api/projects',r)
        await asyncio.sleep(2.5)
        entered,released=blocked(); say(f'FUSE listings: entered={entered}, released={released}, blocked={entered-released}')
        e=await asyncio.to_thread(http,'/.well-known/t3/environment',auth=False); show_http('Environment request',e)
        s=await rpc(10+i,healthy); show_scan('Other project discovery',s)
        results.append({'read':r,'environment':e,'healthyScan':s,'blocked':entered-released})
    s=await rpc(50,workspace); show_scan('Explicit blocked-project scan',s)
    say('Release the stalled FUSE listing')
    (run/'release').touch()
    await asyncio.sleep(3)
    entered,released=blocked(); say(f'FUSE listings after release: entered={entered}, released={released}')
    e=await asyncio.to_thread(http,'/.well-known/t3/environment',auth=False); show_http('Environment after release',e)
    recovered=await rpc(51,workspace); show_scan('Discovery after release',recovered)
    # Wait beyond sync interval before reading again, then read its committed discovery.
    if not smoke: await asyncio.sleep(31.5)
    r=await asyncio.to_thread(http,'/api/projects')
    await asyncio.sleep(1)
    r=await asyncio.to_thread(http,'/api/projects')
    folders=[]
    if r['ok']:
        folders=[f['name'] for p in r['body']['projects'] if p['title']=='Blocked listing project' for f in p['trackedFolders']]
    say('Project stored discovery after another sync: '+str(folders))
    summary={'side':side,'sha':sha,'results':results,'blockedScan':s,'recoveredScan':recovered,'recoveredFolders':folders,'entries':entries}
    (run/'results.json').write_text(json.dumps(summary,indent=2))
    say('Run complete; raw RPC responses and timestamped mount events retained')
try:
    asyncio.run(main())
finally:
    (run/'release').touch()
    if mount:
        subprocess.run(['fusermount3','-u',str(workspace/'stalled')],capture_output=True)
    if server:
        server.terminate()
        try: server.wait(15)
        except subprocess.TimeoutExpired: server.kill(); server.wait()
    if mount:
        mount.terminate()
        try: mount.wait(5)
        except subprocess.TimeoutExpired: mount.kill(); mount.wait()
    cast.close(); transcript.close()
