import re

def refine_vietnamese(content):
    # If the content contains an arrow, it's a multi-stage translation (e.g. Pali -> Eng -> Vie)
    # We always take the last part which is the Vietnamese translation.
    if '→' in content:
        parts = content.split('→')
        content = parts[-1].strip()
    return content

def process_full_file():
    with open('Tam Bao.txt', 'r', encoding='utf-8') as f:
        full_content = f.read()
    
    # Use re.split to get pages while keeping the TRANG marker
    # The split will return ['', 'TRANG 1', 'content1', 'TRANG 2', 'content2'...]
    parts = re.split(r'(TRANG \d+)', full_content)
    
    final_output = []
    
    # Process pairs of (TRANG label, page content)
    for i in range(1, len(parts), 2):
        label = parts[i]
        content = parts[i+1].strip()
        
        lines = content.split('\n')
        processed_page = [label]
        
        for line in lines:
            stripped = line.strip()
            if not stripped:
                continue
            
            if stripped.startswith('→'):
                # Translation line
                raw_translation = stripped[1:].strip()
                refined = refine_vietnamese(raw_translation)
                processed_page.append(f"→ {refined}")
            else:
                # Original Burmese/Pali line
                processed_page.append(stripped)
        
        final_output.append('\n'.join(processed_page))
    
    # Join pages with double newlines
    with open('Tam Bao - Zen.txt', 'w', encoding='utf-8') as f:
        f.write('\n\n'.join(final_output))

if __name__ == "__main__":
    process_full_file()
