import os,sys,time,json,subprocess,threading,urllib.request,urllib.error,pathlib,re,datetime,hashlib
from PIL import Image,ImageDraw,ImageFont
checkout,root,side,sha,port=sys.argv[1:]; port=int(port)
out=pathlib.Path(root)/f'{side}-{datetime.datetime.now().strftime("%H%M%S")}'; out.mkdir()
data=out/'data'; frames=out/'frames'; frames.mkdir()
log=[]; started=time.monotonic(); result={}; process=None
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
def event(s):
    line=f'{time.monotonic()-started:6.1f}s  {s}'; print(line,flush=True); log.append(line)
    (out/'transcript.txt').write_text('\n'.join(log)+'\n')
def sizes():
    files=list(data.rglob('*.gguf*'))
    return [(p,p.stat().st_size) for p in files if p.is_file() and p.name.startswith('Qwen3-ASR-0.6B-Q8_0.gguf') and (p.name.endswith('.part') or p.name.endswith('.gguf'))]
def frame(n):
    im=Image.new('RGB',(1280,720),'#10151e'); d=ImageDraw.Draw(im)
    d.text((32,24),f'Issue 46604 | {side.upper()} | {sha[:10]}',font=font,fill='#f1f5f9')
    d.text((32,60),'Linux real server | real Hugging Face / CloudFront | Qwen3-ASR 0.6B Q8',font=small,fill='#9caec5')
    for i,l in enumerate(log[-18:]): d.text((32,110+i*29),l,font=small,fill='#d5e3f5')
    d.text((32,676),'Live driver output: socket drops target only this server; no mock service.',font=small,fill='#9caec5')
    im.save(frames/f'{n:06d}.png'); return im
try:
    env=dict(os.environ,T3CODE_DEV_SEED='0')
    serverlog=open(out/'private-server.log','w')
    process=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(data),'--port',str(port),'--host','127.0.0.1'],cwd=checkout,env=env,stdout=serverlog,stderr=subprocess.STDOUT)
    for _ in range(120):
        try:
            urllib.request.urlopen(f'http://127.0.0.1:{port}/api/voice/models',timeout=1)
            break
        except urllib.error.HTTPError: break
        except Exception: time.sleep(.5)
    tok=subprocess.check_output(['node','apps/server/src/bin.ts','auth','session','issue','--base-dir',str(data),'--token-only'],cwd=checkout,env=env,text=True).strip()
    def request():
        req=urllib.request.Request(f'http://127.0.0.1:{port}/api/voice/models/download',data=json.dumps({'modelId':'handy-computer/Qwen3-ASR-0.6B-gguf'}).encode(),headers={'Authorization':'Bearer '+tok,'Content-Type':'application/json'})
        try:
            with urllib.request.urlopen(req,timeout=180) as r: result.update(status=r.status,body=json.load(r))
        except urllib.error.HTTPError as e: result.update(status=e.code,body=e.read().decode())
        except Exception as e: result.update(error=type(e).__name__+': '+str(e))
    event('POST /api/voice/models/download; fresh model directory')
    t=threading.Thread(target=request); t.start(); n=0; drops=0; lastdrop=0; lastreport=0; high=0
    while t.is_alive() and time.monotonic()-started<180:
        files=sizes(); current=max([s for p,s in files] or [0]); high=max(high,current)
        if current-lastdrop>=60_000_000 and drops<5:
            ss=subprocess.check_output(['sudo','-n','ss','-Htnp','state','established','dport','=','443'],text=True)
            killed=0
            for line in ss.splitlines():
                if f'pid={process.pid},' not in line: continue
                cols=line.split(); local=cols[2]; peer=cols[3]; lp=local.rsplit(':',1)[1]; pp=peer.rsplit(':',1)[1]
                subprocess.run(['sudo','-n','ss','-K','state','established','sport','=',lp,'dport','=',pp],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True); killed+=1
            if killed:
                drops+=1; lastdrop=current; event(f'DROP {drops}: closed server HTTPS socket(s) at {current:,} bytes')
        if current>=lastreport+25_000_000:
            event(f'On disk: {current:,} bytes ({100*current/850423456:.1f}%)'); lastreport=current
        frame(n); n+=1; time.sleep(.25)
    t.join(timeout=1)
    event(f'Download response: HTTP {result.get("status", "no response")}')
    files=sizes(); event('Files after response: '+(', '.join(f'{"partial" if p.name.endswith(".part") else "complete"} {s:,} bytes' for p,s in files) or 'NONE'))
    event(f'Connection drops injected: {drops}; peak bytes observed: {high:,}')
    for p,s in files:
        if p.name.endswith('.gguf'):
            event('Computing SHA-256 of completed real model...')
            digest=hashlib.file_digest(open(p,'rb'),'sha256').hexdigest(); event('SHA-256: '+digest[:32]); event('         '+digest[32:]); result['sha256']=digest
    result.update(drops=drops,peak=high,files=[{'kind':'partial' if p.name.endswith('.part') else 'complete','bytes':s} for p,s in files])
    (out/'result.json').write_text(json.dumps(result,indent=2))
    for _ in range(16): final=frame(n); n+=1
    final.save(out/'final.png')
finally:
    if process:
        process.terminate()
        try: process.wait(timeout=10)
        except subprocess.TimeoutExpired: process.kill(); process.wait()
subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','4','-i',str(frames/'%06d.png'),'-c:v','libx264','-pix_fmt','yuv420p',str(out/'recording.mp4')],check=True)
print('OUTPUT '+str(out),flush=True)
