#!/usr/bin/env python3
"""
Quét context-summary → phát hiện batch bị đứt câu → tạo fix tasks.
Chạy: python3 fix-bridge.py [--dry-run] [--batch N]
"""
import json, os, glob, sys

PROJ = "/home/tuan-nguyen/.openclaw/workspace/014-alahan-srilanka"
VER = "ver-2/Gemini-3-Flash"
ctx_dir = f"{PROJ}/{VER}/context-summary"
vi_dir = f"{PROJ}/{VER}/vi-only"

progress = json.load(open(f"{PROJ}/{VER}/progress.json"))

# Build batch order
batch_map = {b['name']: (i, b) for i, b in enumerate(progress['batches'])}

fixes = []

for i, b in enumerate(progress['batches']):
    if i == 0:
        continue
    prev = progress['batches'][i-1]
    prev_name = prev['name']
    curr_name = b['name']
    
    prev_ctx = f"{ctx_dir}/{prev_name}-context-summary.md"
    if not os.path.exists(prev_ctx):
        continue
    
    with open(prev_ctx) as f:
        content = f.read()
    
    if "## Câu bị đứt" not in content or "[CÒN TIẾP]" not in content:
        continue
    
    # Extract truncated Myanmar text
    idx = content.index("## Câu bị đứt")
    section = content[idx:].strip()
    lines = section.split('\n')
    # Get the actual Myanmar text (skip headers)
    tr_text = ""
    for line in lines:
        line = line.strip()
        if line.startswith('##') or line.startswith('[') or not line:
            continue
        # Check if line contains Myanmar characters
        has_myanmar = any(0x1000 <= ord(c) <= 0x109F for c in line)
        if has_myanmar and '[CÒN TIẾP]' in section:
            tr_text = line.replace('[CÒN TIẾP]', '').strip()
            break
    
    if not tr_text:
        continue
    
    # Check if vi-only exists for current batch
    vi_path = f"{vi_dir}/{curr_name}-vi.md"
    if not os.path.exists(vi_path):
        continue
    
    # Read source first ~500 chars
    src_path = f"{PROJ}/{b['source']}"
    if not os.path.exists(src_path):
        continue
    with open(src_path) as f:
        source_first = f.read(500)
    
    # Read vi-only first ~300 chars
    with open(vi_path) as f:
        vi_first = f.read(300)
    
    fixes.append({
        'prev': prev_name,
        'current': curr_name,
        'truncated_myanmar': tr_text,
        'source_first': source_first,
        'vi_first': vi_first,
        'vi_path': vi_path,
        'ctx_file': prev_ctx,
    })

print(f"🔍 Tổng batch cần fix bridge: {len(fixes)}")
print()

# Output fix queue as JSON for architect to process
fix_queue_path = f"{PROJ}/{VER}/fix-bridge-queue.json"
with open(fix_queue_path, 'w') as f:
    json.dump(fixes, f, indent=2, ensure_ascii=False)
print(f"📋 Queue saved: {fix_queue_path}")

# Print summary of first 5
for fix in fixes[:5]:
    print(f"\n  {fix['prev']} → {fix['current']}")
    print(f"  TR: {fix['truncated_myanmar'][:80]}...")
    print(f"  VI: {fix['vi_first'][:100].replace(chr(10), ' ')}...")

print(f"\n✅ Ready. Architect sẽ spawn translator cho từng batch trong queue.")
