import re

# File paths
input_file = 'Tam Bao.txt'
output_file = 'Tam Bao - Zen.txt'

def refine_vietnamese(content):
    # This logic cleans up the translation line
    # If it contains multiple arrows (e.g., Pali -> Eng -> Vie), take the last one.
    if '→' in content:
        parts = content.split('→')
        content = parts[-1].strip()
    return content

def process_full_file():
    with open(input_file, 'r', encoding='utf-8') as f:
        full_content = f.read()
    
    # Split by pages using the TRANG X marker
    # We want to keep the marker in the output
    pages = re.split(r'(TRANG \d+)', full_content)
    
    final_output = []
    
    # pages list starts with an empty string or preamble
    # Then it follows: marker, content, marker, content...
    for i in range(1, len(pages), 2):
        page_marker = pages[i]
        page_text = pages[i+1].strip()
        
        lines = page_text.split('\n')
        processed_lines = [page_marker]
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            if line.startswith('→'):
                # Clean up translation line
                content = line[1:].strip()
                refined = refine_vietnamese(content)
                processed_lines.append(f"→ {refined}")
            else:
                # Keep original Burmese/Pali line
                processed_lines.append(line)
        
        final_output.append('\n'.join(processed_lines))
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write('\n\n'.join(final_output))

if __name__ == "__main__":
    process_full_file()
