#!/usr/bin/env python3
import json, wave, urllib.request, time
from pathlib import Path
PROJECT = Path('/data/video-pipeline/Channel-Loi-Co-Nhan/project/195-Dung-De-Mot-Ngay-Luoi-Bien-Thanh-Mot-Doi-No')
ENDPOINT='http://192.168.1.104:8005/compose-tts'
PROBE='http://192.168.1.104:8002/probe'
PAUSE=0.5

def post(url,payload,timeout=7200):
    req=urllib.request.Request(url,data=json.dumps(payload,ensure_ascii=False).encode(),headers={'Content-Type':'application/json'},method='POST')
    with urllib.request.urlopen(req,timeout=timeout) as r:
        return json.loads(r.read().decode())

def wav_dur(p):
    with wave.open(str(p),'rb') as w:
        return w.getnframes()/float(w.getframerate())

def main():
    data=json.loads((PROJECT/'script/scenes.json').read_text(encoding='utf-8'))
    t=0.0; timeline=[]; segs=[]
    for idx,sc in enumerate(data['scenes'],1):
        ap=PROJECT/'audio/voice_segments'/sc['scene_id']/'seg_001.wav'
        d=wav_dur(ap); start=t; speech_end=t+d; end=speech_end+PAUSE
        segs.append({'segment_index':idx,'start':round(start,3),'end':round(speech_end,3),'audio_path':str(ap),'source_text':sc['narration'],'translated_text':'','status':'ok'})
        timeline.append({'scene_id':sc['scene_id'],'voice_segment_id':sc['scene_id']+'_seg_001','segment_index_in_scene':1,'audio_path':str(ap),'image_path':str(PROJECT/'images/scenes'/(sc['scene_id']+'.png')),'text':sc['narration'],'start':round(start,3),'end':round(end,3),'speech_end':round(speech_end,3),'duration':round(d+PAUSE,3),'audio_duration':round(d,3),'pause_sec':PAUSE})
        t=end
    out=PROJECT/'audio/master_narration.wav'; out.parent.mkdir(parents=True,exist_ok=True)
    payload={'job_id':PROJECT.name+'_step05_master_narration','work_dir':str(PROJECT),'output_audio_path':str(out),'tts_segments':segs,'pause_sec':PAUSE}
    resp=post(ENDPOINT,payload)
    probe=post(PROBE,{'input_path':str(out)},timeout=120)
    dur=float(probe.get('format',{}).get('duration') or probe.get('duration') or t)
    (PROJECT/'audio/master_narration_timeline.json').write_text(json.dumps({'duration_sec':dur,'items':timeline},ensure_ascii=False,indent=2),encoding='utf-8')
    (PROJECT/'audio/master_audio_probe.json').write_text(json.dumps(probe,ensure_ascii=False,indent=2),encoding='utf-8')
    (PROJECT/'logs/step05_compose_tts_manifest.json').write_text(json.dumps({'endpoint':ENDPOINT,'payload':payload,'response':resp,'probe':probe},ensure_ascii=False,indent=2),encoding='utf-8')
    print('DONE compose',dur)
if __name__=='__main__': main()
