#!/usr/bin/env python3
import importlib.util, json, re, time
from pathlib import Path
PROJECT=Path('/data/video-pipeline/Youtube-Video-Maker/Project/28052026-002-Tran-Quang-Dieu-Bui-Thi-Xuan')
STEP7=PROJECT/'scripts_run_step_07_tts_v2.py'
SCENES=PROJECT/'script/scenes.json'
OUT=PROJECT/'audio/pronunciation_review_candidates_tran_phonetic_scene070_more'

def log(m): print(time.strftime('%Y-%m-%d %H:%M:%S ')+m, flush=True)

def main():
    OUT.mkdir(parents=True, exist_ok=True)
    spec=importlib.util.spec_from_file_location('step7', STEP7)
    mod=importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
    scenes={s['scene_id']:s for s in json.loads(SCENES.read_text(encoding='utf-8'))['scenes']}
    s=scenes['scene_070']
    base,changes=mod.normalize(s['narration'])
    variants=[]
    # Candidate 1 was closest: use the same Chần workaround, with small payload changes
    # to force new TTS takes and reduce unrelated word mistakes.
    chan=re.sub(r'\btrần\s+quang\s+diệu\b','Chần Quang Diệu',base,flags=re.I)
    variants.append(('chan_same_take01', chan))
    variants.append(('chan_same_take02', chan))
    variants.append(('chan_comma_before', re.sub(r'\bchần\s+quang\s+diệu\b', ', Chần Quang Diệu', chan, flags=re.I)))
    variants.append(('chan_name_pause', re.sub(r'\bchần\s+quang\s+diệu\b','Chần, Quang Diệu',chan,flags=re.I)))
    variants.append(('chan_sentence_split', re.sub(r'\bchần\s+quang\s+diệu\b','. Chần Quang Diệu',chan,flags=re.I)))
    variants.append(('chan_with_bui_pause', re.sub(r'\bchần\s+quang\s+diệu\s+và\s+bùi\s+thị\s+xuân\b','Chần Quang Diệu, và Bùi Thị Xuân',chan,flags=re.I)))
    old_audio_dir=mod.AUDIO_DIR; mod.AUDIO_DIR=OUT
    try:
        for i,(name,tts) in enumerate(variants,1):
            cand_id=f'scene_070_chanmore_cand{i:02d}_{name}'
            item={'scene_id':cand_id,'narration':s['narration'],'tts_text':tts,'normalization':changes+[name],'output':str(OUT/f'{cand_id}.wav')}
            log(f'GEN {cand_id}')
            r=mod.generate(item)
            log(f"{r.get('status')} {cand_id} dur={r.get('duration')}")
    finally:
        mod.AUDIO_DIR=old_audio_dir
if __name__=='__main__': main()
