#!/usr/bin/env python3
"""
verify-bilingual.py — Kiểm tra file dịch song ngữ Sổ Tay Mahāvihāra (theo đoạn).

Kiểm tra:
  1. Số separator `---` trong output == số separator trong source
  2. Số `## PAGE` headers khớp
  3. Mỗi đoạn có `→` phân cách Myanmar và Việt
  4. Không còn `<mark>` tags

USAGE:
  python3 verify-bilingual.py <source-path> <bilingual-output-path>
"""

import sys
import re


def verify(source_path: str, output_path: str) -> bool:
    with open(source_path) as f:
        source = f.read()
    with open(output_path) as f:
        output = f.read()

    sep = "\n---\n"
    errors = []

    # 1. Separator count
    src_sep = source.count(sep)
    out_sep = output.count(sep)
    if src_sep != out_sep:
        errors.append(f"SEPARATOR MISMATCH: source={src_sep}, output={out_sep}")

    # 2. PAGE count
    src_pages = len(re.findall(r'^## PAGE \d+', source, re.MULTILINE))
    out_pages = len(re.findall(r'^## PAGE \d+', output, re.MULTILINE))
    if src_pages != out_pages:
        errors.append(f"PAGE MISMATCH: source={src_pages}, output={out_pages}")

    # 3. Arrow separators: at least one → per section (sections = separators + 1)
    expected_arrows = out_sep + 1
    arrow_count = output.count('\n\n→\n\n') + output.count('\n→\n')
    if arrow_count < expected_arrows:
        errors.append(f"ARROW WARNING: {arrow_count} → for {expected_arrows} sections (min)")

    # 4. No <mark> tags
    if '<mark>' in output or '</mark>' in output:
        mark_count = output.count('<mark>')
        errors.append(f"MARK TAG: {mark_count} <mark> tags found in output")

    # 5. No Myanmar chars in Vietnamese parts (heuristic: check → sections)
    sections = output.split('\n\n→\n\n')
    for i, sec in enumerate(sections):
        # After → should have Vietnamese, not Myanmar
        pass  # Complex to verify, skip for now

    if errors:
        print("❌ VERIFICATION FAILED:")
        for e in errors:
            print(f"   {e}")
        return False
    else:
        sections = out_sep + 1
        print(f"✅ VERIFIED: {src_sep} separators, {src_pages} pages, {sections} sections")
        print(f"   Arrows: {arrow_count}")
        print(f"   Source: {len(source):,} chars")
        print(f"   Output: {len(output):,} chars")
        return True


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python3 verify-bilingual.py <source.md> <bilingual-output.md>")
        sys.exit(1)
    ok = verify(sys.argv[1], sys.argv[2])
    sys.exit(0 if ok else 1)
