#!/usr/bin/env python3
from pathlib import Path
import hashlib,json,subprocess,urllib.request,time
P=Path(__file__).resolve().parents[1];assert P.name=='031-Vi-Sao-Dung-Day-Qua-Nhanh-Khien-Ban-Hoa-Mat';URL='http://192.168.1.104:8021/stickman-render-gpu'
def sha(f):return hashlib.sha256(Path(f).read_bytes()).hexdigest()
def dur(f):return float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','default=nw=1:nk=1',str(f)]))
def post(job,scenes,audio,out):
 req={'job_id':job,'scenes':scenes,'audio_path':str(audio),'output_path':str(out),'width':1920,'height':1080,'fps':30,'transition':'cut','timeline_start_sec':0,'timeline_end_sec':dur(audio)}
 log=P/'logs'/f'render_{job}.json';log.write_text(json.dumps({'request':{**req,'audio_sha256':sha(audio),'scene_count':len(scenes)}} ,indent=2)+'\n')
 r=urllib.request.urlopen(urllib.request.Request(URL,data=json.dumps(req).encode(),headers={'Content-Type':'application/json'},method='POST'),timeout=1800);body=json.load(r);log.write_text(json.dumps({'request':req,'response':body},indent=2)+'\n');return body
intro=P/'images/intro_poster.png';outro=P/'images/outro_poster.png';main=P/'prompts/image_prompts.json';tl=json.loads((P/'asr/timeline.json').read_text())
post('031-intro',[{'image_path':str(intro),'duration':dur(P/'audio/intro_padded.wav')}],P/'audio/intro_padded.wav',P/'video/intro.mp4')
post('031-outro',[{'image_path':str(outro),'duration':dur(P/'audio/outro.wav')}],P/'audio/outro.wav',P/'video/outro.mp4')
scenes=[{'image_path':x['image_path'],'duration':x['duration']} for x in tl['scenes']];post('031-main',scenes,P/'audio/full_narration.wav',P/'video/output/main.mp4')
print('GPU_RENDER_GATE PASS')
# Ensure scene count source is canonical timeline and not an accidental split.
assert len(scenes)==54
