#!/usr/bin/env python3
"""Ghép tất cả vi-only files → 1 file hoàn chỉnh."""
import json, os, glob

PROJ = "/home/tuan-nguyen/.openclaw/workspace/014-alahan-srilanka"
VER = "ver-2/Gemini-3-Flash"
vi_dir = f"{PROJ}/{VER}/vi-only"
output = f"{PROJ}/Tieu-Su-Cac-Vi-Alahan-Srilanka.md"

with open(f"{PROJ}/{VER}/progress.json") as f:
    data = json.load(f)

# File name → batch name mapping
file_map = {}
for f in glob.glob(f"{vi_dir}/*-vi.md"):
    name = os.path.basename(f).replace('-vi.md', '')
    file_map[name] = f

merged = []
missing = []
page_count = 0

for b in data['batches']:
    name = b['name']
    if name not in file_map:
        missing.append(name)
        continue
    
    with open(file_map[name]) as f:
        content = f.read()
    
    # Đếm số trang
    page_count += content.count('## PAGE')
    
    # Xóa ## PAGE headers (chỉ giữ nội dung)
    lines = content.split('\n')
    cleaned = []
    for line in lines:
        if line.startswith('## PAGE'):
            continue  # bỏ page marker
        cleaned.append(line)
    
    merged.append('\n'.join(cleaned).strip())

# Ghi output
with open(output, 'w') as f:
    f.write('# Tiểu Sử Các Vị A-La-Hán (Sīhaḷa Ariya)\n\n')
    f.write('\n\n'.join(merged))

print(f"✅ Merged: {len(merged)}/{len(data['batches'])} batches")
print(f"   Pages: ~{page_count}")
print(f"   Missing: {len(missing)}")
if missing:
    for m in missing:
        print(f"     ❌ {m}")
print(f"   Output: {output}")
print(f"   Size: {os.path.getsize(output):,} bytes")
