#!/usr/bin/env python3
import requests
import time
import re

INPUT_FILE = 'Tam Bao Myn.txt'
OUTPUT_FILE = 'Tam Bao My-Vi.txt'

# Myanmar Unicode range
MYANMAR_RE = re.compile(r'[\u1000-\u109F]')
TRANG_RE = re.compile(r'^\s*\[?\s*TRANG\s+\d+\s*\]?\s*$', re.IGNORECASE)

def is_myanmar(line):
    """Return True if line contains Myanmar characters."""
    return bool(MYANMAR_RE.search(line))

def is_trang(line):
    """Return True if line is a page marker."""
    return bool(TRANG_RE.match(line.strip()))

def translate_myanmar_to_vietnamese(text, max_retries=3):
    """Translate Myanmar text to Vietnamese using MyMemory API."""
    url = "https://api.mymemory.translated.net/get"
    params = {
        'q': text,
        'langpair': 'my|vi'
    }
    for attempt in range(max_retries):
        try:
            resp = requests.get(url, params=params, timeout=30)
            resp.raise_for_status()
            data = resp.json()
            if 'responseData' in data and 'translatedText' in data['responseData']:
                translated = data['responseData']['translatedText']
                return translated
            else:
                print(f"Unexpected response: {data}")
        except Exception as e:
            print(f"Translation error (attempt {attempt+1}): {e}")
            time.sleep(2)
    # Fallback: return original text
    return text

def process_line(line):
    """Process a single line, return list of lines to write."""
    stripped = line.rstrip('\n')
    if not stripped:
        return [line]  # blank line
    if is_trang(stripped):
        return [line]  # page marker, keep as is
    if is_myanmar(stripped):
        # Translate
        translation = translate_myanmar_to_vietnamese(stripped)
        return [line, f"→ {translation}\n"]
    # Non-Myanmar line (maybe Pali romanized, numbers, etc.) – keep as is
    return [line]

def main():
    with open(INPUT_FILE, 'r', encoding='utf-8') as infile:
        lines = infile.readlines()
    
    total_lines = len(lines)
    processed = 0
    myanmar_lines = 0
    
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as outfile:
        for idx, line in enumerate(lines):
            if idx % 10 == 0:
                print(f"Processing line {idx+1}/{total_lines}...")
            to_write = process_line(line)
            outfile.writelines(to_write)
            processed += 1
            if len(to_write) > 1:  # translation added
                myanmar_lines += 1
            # Rate limit: 100 lines per minute ≈ 0.6 seconds per line
            # But translation API call already takes time, so we just wait a bit after each Myanmar line
            if len(to_write) > 1:
                time.sleep(0.6)  # adjust as needed
    
    print(f"Finished. Processed {processed} lines, translated {myanmar_lines} Myanmar lines.")
    print(f"Output saved to {OUTPUT_FILE}")

if __name__ == '__main__':
    main()