#!/usr/bin/env python3
"""
Assemble 001_final_vi.srt + 001_bilingual.txt sau khi fix chunk 012.
Reuse bản dịch cũ theo text-matching + bản dịch mới của chunk 012.
"""
import json, os, re, glob

PROJ = "/home/tuan-nguyen/.openclaw/workspace/015-phu_de_video"
OUT = os.path.join(PROJ, "output")
BK = None
# find backup dir
for d in sorted(glob.glob(os.path.join(PROJ, "_backup", "001_fix_chunk012_*"))):
    BK = d  # last one
if not BK:
    raise SystemExit("no backup dir found")

# ── Load old vi (text -> vi) ──
old_vi_by_idx = {}
for p in sorted(glob.glob(os.path.join(BK, "batches", "001_batch_*_vi.txt"))):
    for line in open(p, encoding='utf-8'):
        m = re.match(r'\[(\d+)\]\s*(.*)', line.strip())
        if m:
            old_vi_by_idx[int(m.group(1))] = m.group(2).strip()

old_recs = json.load(open(os.path.join(BK, "001_srt_map.json"), encoding='utf-8'))
old_text_to_vi = {}
for r in old_recs:
    idx0 = r['index'] - 1
    old_text_to_vi.setdefault(r['myanmar'], old_vi_by_idx.get(idx0, ''))

# ── Load new translations (chunk 012) ──
new_vi_by_idx = {}
npath = "/tmp/001_unmatched_vi.txt"
if os.path.exists(npath):
    for line in open(npath, encoding='utf-8'):
        m = re.match(r'\[(\d+)\]\s*(.*)', line.strip())
        if m:
            new_vi_by_idx[int(m.group(1))] = m.group(2).strip()

# ── Load new records ──
records = json.load(open(os.path.join(OUT, "001_srt_map.json"), encoding='utf-8'))

# ── Build final vi ──
missing = []
vi_final = {}
for r in records:
    idx0 = r['index'] - 1
    t = r['myanmar']
    if t in old_text_to_vi and old_text_to_vi[t]:
        vi_final[idx0] = old_text_to_vi[t]
    elif idx0 in new_vi_by_idx and new_vi_by_idx[idx0]:
        vi_final[idx0] = new_vi_by_idx[idx0]
    else:
        missing.append(r['index'])

print(f"records: {len(records)} | translated: {len(vi_final)} | missing: {len(missing)}")
if missing:
    print(f"  missing indices: {missing[:30]}{'...' if len(missing)>30 else ''}")

# ── Write Vietnamese SRT ──
srt_path = os.path.join(OUT, "001_final_vi.srt")
with open(srt_path, 'w', encoding='utf-8') as f:
    for r in records:
        idx0 = r['index'] - 1
        if idx0 in vi_final:
            f.write(f"{r['index']}\n{r['start']} --> {r['end']}\n{vi_final[idx0]}\n\n")

# ── Write bilingual ──
bil_path = os.path.join(OUT, "001_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_final:
            f.write(f"     {vi_final[idx0]}\n")
        f.write('\n')

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