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 download; fresh model directory; cancel after 100 MB')
    t=threading.Thread(target=request); t.start(); n=0; high=0; drops=0
    while t.is_alive():
        current=max([v for p,v in sizes()] or [0]); high=max(high,current)
        if current>=100_000_000: break
        frame(n); n+=1; time.sleep(.1)
    event(f'Before cancel: {high:,} bytes on disk')
    req=urllib.request.Request(f'http://127.0.0.1:{port}/api/voice/models/cancel',data=json.dumps({'modelId':'handy-computer/Qwen3-ASR-0.6B-gguf'}).encode(),headers={'Authorization':'Bearer '+tok,'Content-Type':'application/json'})
    with urllib.request.urlopen(req,timeout=20) as r: cancel=json.load(r)
    t.join(timeout=20)
    event('POST cancel response received')
    retained=max([v for p,v in sizes()] or [0]); event(f'After cancel: {retained:,} partial bytes retained')
    frame(n); n+=1
    process.terminate(); process.wait(timeout=10)
    event('Stopped server; restarting with the same data directory')
    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):
        frame(n); n+=1
        try:
            ready=urllib.request.Request(f'http://127.0.0.1:{port}/api/voice/models',headers={'Authorization':'Bearer '+tok})
            with urllib.request.urlopen(ready,timeout=1) as r:
                if r.status==200: break
        except Exception: time.sleep(.25)
    after_restart=max([v for p,v in sizes()] or [0]); event(f'After restart: {after_restart:,} partial bytes retained')
    event('POST download again; same real model')
    result.clear(); t=threading.Thread(target=request); t.start(); lastreport=after_restart
    while t.is_alive() and time.monotonic()-started<180:
        current=max([v for p,v in sizes()] or [0]); high=max(high,current)
        if current>=lastreport+60_000_000:
            event(f'On disk: {current:,} bytes'); 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 retry: '+(', '.join(f'{"partial" if p.name.endswith(".part") else "complete"} {v:,} bytes' for p,v in files) or 'NONE'))
    result.update(beforeCancel=high,afterCancel=retained,afterRestart=after_restart)
    for p,v in files:
        if p.name.endswith('.gguf'):
            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)
