#!/usr/bin/env python3
"""
Apply themdongtrong.md rules to add blank lines in Myanmar OCR files.

Usage:
    python3 add_blank_lines.py <filepath>
    
Rules:
1. Line ends with ။ → insert blank line after (unless next is ---, ##, ###, or in list)
2. Section heading (ဋ)(ဌ)(ဍ)(ဎ) → insert blank line after
3. Before list (က။ / (၁)) → insert blank line before
4. Line ends with ။] → insert blank line after (if next is different section)
"""

import re
import sys


def process_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    new_lines = []
    insert_count = 0
    
    for i, line in enumerate(lines):
        new_lines.append(line)
        stripped = line.rstrip('\n')
        
        if i + 1 >= len(lines):
            break
        
        next_stripped = lines[i+1].rstrip('\n')
        
        # RULE 3: Before a list (က။ / (၁))
        if re.match(r'^[က-အ]။', next_stripped) or re.match(r'^\([၁-၁၀]\)', next_stripped):
            if not (re.match(r'^[က-အ]။', stripped) or re.match(r'^\([၁-၁၀]\)', stripped)):
                new_lines.append('\n')
                insert_count += 1
                continue
        
        # RULE 1 & 4: Line ends with ။ or ။]
        if stripped.endswith('။') or stripped.endswith('။]'):
            # Next is ---, ##, or ### → skip
            if next_stripped == '---' or next_stripped.startswith('##') or next_stripped.startswith('###'):
                continue
            # Next is in a list → skip
            if re.match(r'^[က-အ]။', next_stripped) or re.match(r'^\([၁-၁၀]\)', next_stripped):
                continue
            # Next is already blank → skip (avoid double blank)
            if next_stripped == '':
                continue
            
            new_lines.append('\n')
            insert_count += 1
        
        # RULE 2: Section heading (ဋ)(ဌ)(ဍ)(ဎ)
        if re.match(r'^\([ဍဎဋဌ]\)', stripped):
            if next_stripped != '':
                new_lines.append('\n')
                insert_count += 1
    
    output = ''.join(new_lines)
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(output)
    
    return insert_count


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 add_blank_lines.py <filepath>")
        sys.exit(1)
    
    filepath = sys.argv[1]
    count = process_file(filepath)
    print(f"✅ {filepath}: added {count} blank lines")
    return count


if __name__ == '__main__':
    main()
