import re

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

def refine_vietnamese(content):
    """
    Extracts the final Vietnamese translation from a line that may contain multiple stages.
    Example: 'Oṃ namo... → Con xin...' returns 'Con xin...'
    """
    if '→' in content:
        parts = content.split('→')
        content = parts[-1].strip()
    return content

def process_full_file():
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            full_content = f.read()
        
        # Split the text into pages based on the 'TRANG X' markers
        # re.split(..., full_content) returns a list where the delimiters are kept if grouped
        pages = re.split(r'(TRANG \d+)', full_content)
        
        final_output = []
        
        # pages[0] is typically empty if file starts with 'TRANG 1'
        # Thereafter, elements are: [label1, content1, label2, content2, ...]
        for i in range(1, len(pages), 2):
            page_label = pages[i]
            page_content = pages[i+1].strip()
            
            lines = page_content.split('\n')
            processed_page_lines = [page_label]
            
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                
                if line.startswith('→'):
                    # It's a translation line
                    # Skip '→ ' then clean up multiple translations
                    raw_text = line[1:].strip()
                    refined_text = refine_vietnamese(raw_text)
                    processed_page_lines.append(f"→ {refined_text}")
                else:
                    # It's a source (Burmese/Pali) line, keep as is
                    processed_page_lines.append(line)
            
            final_output.append('\n'.join(processed_page_lines))
        
        # Combine pages with a gap
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write('\n\n'.join(final_output))
            
        return True
    except Exception as e:
        print(f"Error during processing: {e}")
        return False

if __name__ == "__main__":
    if process_full_file():
        print(f"Successfully created {output_file}")
    else:
        print("Failed to process the file.")
