#!/usr/bin/env python3
"""Simple formatting for Sadi markdown."""
import re

def main():
    import os
    base = "/home/tuan-nguyen/.openclaw/workspace/Chuan Muc Sadi"
    raw_path = os.path.join(base, "Sadi-216-220-qwen.md")
    out_path = os.path.join(base, "extracted", "Sadi-216-220-edited.md")
    
    with open(raw_path, "r", encoding="utf-8") as f:
        raw = f.read()
    
    # Remove the single-line structure: split by ## Trang
    # But they are not separated by newlines, so we need to insert them
    raw = raw.replace("## Trang", "\n## Trang")
    
    lines = []
    sections = raw.split("\n## Trang")
    
    for i, sec in enumerate(sections):
        sec = sec.strip()
        if not sec:
            continue
        if i == 0:
            lines.append(f"# {sec}")
            lines.append("")
            continue
        
        # Extract page number
        m = re.match(r'(\d+)\s+(.*)', sec)
        if m:
            page_num = m.group(1)
            content = m.group(2)
        else:
            page_num = sec
            content = ""
        
        lines.append(f"## Trang {page_num}")
        lines.append("")
        
        if content.startswith("None"):
            lines.append("*(Trang bìa/trống)*")
            lines.append("")
            continue
        
        # Remove "None" at start of content
        content = re.sub(r'^None\s*', '', content)
        
        # Split into logical chunks at လည်းကောင်း, double း, major markers
        # Strategy: keep Pāḷi verses together, commentary items together
        
        # First, split at Pāḷi verse numbers (၁) etc
        content = re.sub(r'(?<=[။])\s*(?=[\(（][၀၁၂၃၄၅၆၇၈၉]+[\)）])', '\n', content)
        
        # Split at Myanmar numbers with း
        content = re.sub(r'(?<=[။])\s*(?=[၀၁၂၃၄၅၆၇၈၉]+။)', '\n', content)
        
        # Now process lines
        for line in content.split('\n'):
            line = line.strip()
            if not line:
                continue
            # If line is long enough, keep as paragraph
            # If short, might need grouping - but let's keep simple
            lines.append(line)
        
        lines.append("")
    
    # Write
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    with open(out_path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))
    
    print(f"✅ Formatted: {out_path}")
    print(f"   Lines: {len(lines)}")

if __name__ == "__main__":
    main()
