#!/usr/bin/env python3
"""
Re-merge 001 after fixing chunk 012.
Writes 001_final.srt + 001_srt_map.json + 001_myanmar_lines.txt (KHÔNG đụng batches/progress của 002).
"""
import os, re, json
from pathlib import Path

PREFIX = "001"
PROJ = "/home/tuan-nguyen/.openclaw/workspace/015-phu_de_video"
TRANS_DIR = os.path.join(PROJ, "output", "transcripts")
OUT_DIR = os.path.join(PROJ, "output")
CHUNK_DURATION = 120.0
OVERLAP = 0.3
EFFECTIVE = CHUNK_DURATION - OVERLAP

TS_RE = re.compile(
    r'(\d{1,2}):(\d{2}):(\d{2}),(\d{3})\s*-->\s*(\d{1,2}):(\d{2}):(\d{2}),(\d{3})'
)

def to_sec(h, m, s, ms):
    return int(h) * 3600 + int(m) * 60 + int(s) + int(ms) / 1000.0

def parse_srt(path):
    with open(path, encoding='utf-8') as f:
        content = f.read()
    segs = []
    for block in content.strip().split('\n\n'):
        lines = block.split('\n')
        if len(lines) < 3:
            continue
        m = TS_RE.match(lines[1].strip())
        if not m:
            continue
        start = to_sec(m.group(1), m.group(2), m.group(3), m.group(4))
        end = to_sec(m.group(5), m.group(6), m.group(7), m.group(8))
        text = '\n'.join(lines[2:]).strip()
        if text:
            segs.append((start, end, text))
    return segs

def fmt(sec):
    h = int(sec // 3600)
    m = int((sec % 3600) // 60)
    s = int(sec % 60)
    ms = int(round((sec - int(sec)) * 1000))
    if ms >= 1000:
        ms -= 1000
        s += 1
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

all_segs = []
chunk_files = sorted(Path(TRANS_DIR).glob(f"{PREFIX}_clean_chunk_*_gemini.srt"))
print(f"Found {len(chunk_files)} chunk SRTs")

for cf in chunk_files:
    m = re.search(r'chunk_(\d+)', cf.name)
    idx = int(m.group(1))
    offset = idx * EFFECTIVE
    for (start, end, text) in parse_srt(str(cf)):
        all_segs.append((start + offset, end + offset, text))

all_segs.sort(key=lambda x: x[0])
print(f"Total merged segments: {len(all_segs)}")

final_srt = os.path.join(OUT_DIR, f"{PREFIX}_final.srt")
with open(final_srt, 'w', encoding='utf-8') as f:
    for i, (start, end, text) in enumerate(all_segs, 1):
        f.write(f"{i}\n{fmt(start)} --> {fmt(end)}\n{text}\n\n")

records = []
for i, (start, end, text) in enumerate(all_segs):
    records.append({"index": i + 1, "start": fmt(start), "end": fmt(end),
                    "myanmar": text})

with open(os.path.join(OUT_DIR, f"{PREFIX}_srt_map.json"), 'w', encoding='utf-8') as f:
    json.dump(records, f, ensure_ascii=False, indent=2)

with open(os.path.join(OUT_DIR, f"{PREFIX}_myanmar_lines.txt"), 'w', encoding='utf-8') as f:
    for r in records:
        f.write(f"[{r['index'] - 1}] {r['myanmar']}\n")

print(f"→ {final_srt} ({len(records)} records)")
print(f"→ {os.path.join(OUT_DIR, f'{PREFIX}_srt_map.json')}")
