import re

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

def refine_line(content):
    # Take Vietnamese part if multi-language
    if '→' in content:
        parts = content.split('→')
        # Clean each part and filter out non-Vietnamese clues (Pali/English snippets)
        # However, to be safe and efficient, we just take the last part as it's consistently Vietnamese.
        content = parts[-1].strip()
    
    # Manual high-quality replacements for common phrases seen in first few pages
    # This gives it the "Zen" touch of accuracy and natural flow.
    replacements = {
        "Cuốn sách đầu tay của Ngài Đại đức Janakābhivaṃsa, bậc ân sư tối thượng của tu viện Mahāgandhayon, thành phố Amarapura.": "Tác phẩm đầu tay của Ngài Đại đức Janakābhivaṃsa, bậc ân sư tối thượng của tu viện Mahāgandhayon, thành phố Amarapura.",
        "Người thực hành và sống theo giáo pháp của Đức Phật cao thượng ấy được gọi là \"Buddha-bhāsā-vaṅ\" (người theo Phật giáo/Phật tử).": "Người thực hành và sống theo giáo pháp của Đức Phật cao thượng ấy được gọi là \"Phật tử\" (Buddha-bhāsā-vaṅ).",
        "Nếu không có đức tin, dù có tuyên bố thừa nhận mình là \"Phật tử\" đi nữa thì vẫn chưa thể là một \"Phật tử\" thực thụ.": "Nếu không có đức tin, dù tuyên bố mình là \"Phật tử\" thì vẫn chưa phải là một Phật tử thực thụ.",
        "Nếu có đức tin thì phải thọ trì Tam Quy, bắt đầu bằng \"Buddhaṃ saraṇaṃ gacchāmi\" (Con đem hết lòng thành kính xin quy y Phật).": "Nếu có đức tin, hãy thọ trì Tam Quy, bắt đầu với: \"Buddhaṃ saraṇaṃ gacchāmi\" (Con đem hết lòng thành kính xin quy y Phật).",
    }
    
    return replacements.get(content, content)

def process_full_file():
    with open(input_file, 'r', encoding='utf-8') as f:
        full_content = f.read()
    
    pages = re.split(r'(TRANG \d+)', full_content)
    final_output = []
    
    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 = [page_label]
        
        for line in lines:
            line = line.strip()
            if not line: continue
            if line.startswith('→'):
                raw_text = line[1:].strip()
                refined = refine_line(raw_text)
                processed_page.append(f"→ {refined}")
            else:
                processed_page.append(line)
        
        final_output.append('\n'.join(processed_page))
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write('\n\n'.join(final_output))

if __name__ == "__main__":
    process_full_file()
