#!/usr/bin/env python3
"""Assemble Vietnamese SRT (002): map _vi.txt translations back to srt_map.json timestamps."""
import json, os, re, glob

PREFIX = "002"
PROJ = "/home/tuan-nguyen/.openclaw/workspace/015-phu_de_video"
OUT = os.path.join(PROJ, "output")

with open(os.path.join(OUT, f"{PREFIX}_srt_map.json"), encoding='utf-8') as f:
    records = json.load(f)

# Parse all _vi.txt → {index: vietnamese}
vi = {}
for path in sorted(glob.glob(os.path.join(OUT, "batches", f"{PREFIX}_batch_*_vi.txt"))):
    with open(path, encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            m = re.match(r'\[(\d+)\]\s*(.*)', line)
            if m:
                vi[int(m.group(1))] = m.group(2).strip()

print(f"translated lines loaded: {len(vi)} / {len(records)} records")

# Build Vietnamese SRT
missing = []
srt_path = os.path.join(OUT, f"{PREFIX}_final_vi.srt")
with open(srt_path, 'w', encoding='utf-8') as f:
    for r in records:
        idx0 = r['index'] - 1  # 0-based
        text = vi.get(idx0, '')
        if not text:
            missing.append(r['index'])
            continue
        f.write(f"{r['index']}\n{r['start']} --> {r['end']}\n{text}\n\n")

print(f"missing translations: {len(missing)}")
if missing:
    print(f"  (indices without translation): {missing[:20]}{'...' if len(missing)>20 else ''}")

# Bilingual text file
bil_path = os.path.join(OUT, f"{PREFIX}_bilingual.txt")
with open(bil_path, 'w', encoding='utf-8') as f:
    for r in records:
        idx0 = r['index'] - 1
        f.write(f"[{idx0}] {r['myanmar']}\n")
        if idx0 in vi:
            f.write(f"     {vi[idx0]}\n")
        f.write('\n')

print(f"→ {srt_path}")
print(f"→ {bil_path}")
