import re

def process_file(input_path, output_path):
    with open(input_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # Split into sections based on TRANG X markers
    pages = re.split(r'(TRANG \d+)', content)
    
    processed_pages = []
    
    # pages list will be ['', 'TRANG 1', 'content...', 'TRANG 2', ...]
    for i in range(1, len(pages), 2):
        page_header = pages[i]
        page_content = pages[i+1]
        
        # Split content into lines
        lines = page_content.strip().split('\n')
        
        page_result = []
        page_result.append(page_header)
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
                
            # If it's a translation line (starts with →)
            if line.startswith('→'):
                # Extract text and handle nested arrows if any
                clean_text = line[1:].strip()
                # If there is another arrow like Pali -> Eng -> Vie, take the last part or handle accordingly
                # The user examples show: Pali -> Eng -> Vie
                # Example: → Oṃ namo... → Con xin...
                if '→' in clean_text:
                    parts = clean_text.split('→')
                    # Keep everything but clean them
                    clean_parts = [p.strip() for p in parts]
                    page_result.append(' | '.join(clean_parts))
                else:
                    page_result.append(clean_text)
            else:
                # Original Burmese or Pali line
                page_result.append(line)
        
        processed_pages.append('\n'.join(page_result))
    
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write('\n\n'.join(processed_pages))

if __name__ == "__main__":
    process_file('Tam Bao.txt', 'Tam Bao Processed.txt')
