import os
import re
import sys
import time
import requests
import urllib.parse

if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass
if hasattr(sys.stderr, 'reconfigure'):
    try:
        sys.stderr.reconfigure(encoding='utf-8')
    except Exception:
        pass

# Danh mục các ngôn ngữ mục tiêu (Mã ngôn ngữ: Tên hiển thị)
TARGET_LANGUAGES = {
    'de': 'German (Deutsch)',
    'fr': 'French (Français)',
    'es': 'Spanish (Español)',
    'ja': 'Japanese (日本語)',
    'vi': 'Vietnamese (Tiếng Việt)'
}

def translate_text_gtx(text, target_lang, source_lang='en'):
    """Dịch văn bản qua Google Translate GTX endpoint"""
    if not text.strip():
        return text
    url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl={source_lang}&tl={target_lang}&dt=t&q={urllib.parse.quote(text)}"
    try:
        res = requests.get(url, timeout=10)
        if res.status_code == 200:
            data = res.json()
            # Ghép tất cả các câu kết quả
            translated = "".join([part[0] for part in data[0] if part[0]])
            return translated
    except Exception as e:
        pass
    return text

def parse_srt(srt_path):
    """Đọc file SRT và trích xuất danh sách các block: (index, timing, text)"""
    with open(srt_path, 'r', encoding='utf-8') as f:
        content = f.read()

    blocks = re.split(r'\n\s*\n', content.strip())
    parsed = []
    for b in blocks:
        lines = b.strip().split('\n')
        if len(lines) >= 3:
            idx = lines[0].strip()
            timing = lines[1].strip()
            text = ' '.join([l.strip() for l in lines[2:]])
            parsed.append((idx, timing, text))
    return parsed

def write_srt(output_path, blocks_with_translated_text):
    """Ghi lại file SRT với nội dung đã dịch"""
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with open(output_path, 'w', encoding='utf-8') as f:
        for idx, timing, text in blocks_with_translated_text:
            f.write(f"{idx}\n{timing}\n{text}\n\n")

def generate_multilingual_subtitles_for_ep(source_en_srt, output_dir=None):
    """
    Tự động dịch file phụ đề tiếng Anh sang 5 ngôn ngữ RPM cao nhất thế giới:
    Đức (de), Pháp (fr), Tây Ban Nha (es), Nhật Bản (ja), Việt Nam (vi)
    """
    if output_dir is None:
        output_dir = os.path.dirname(source_en_srt)

    base_name = os.path.splitext(os.path.basename(source_en_srt))[0]
    ep_prefix = re.sub(r'_[a-z]{2}$', '', base_name)

    print(f"\n=======================================================", flush=True)
    print(f"DỊCH PHỤ ĐỀ ĐA NGÔN NGỮ CHO: {os.path.basename(source_en_srt)}", flush=True)
    print(f"Thư mục đích: {output_dir}", flush=True)
    print(f"=======================================================", flush=True)

    parsed = parse_srt(source_en_srt)
    if not parsed:
        print("Lỗi: File SRT rỗng hoặc sai định dạng!")
        return {}

    generated_files = {'en': source_en_srt}

    for lang_code, lang_name in TARGET_LANGUAGES.items():
        out_file = os.path.join(output_dir, f"{ep_prefix}_{lang_code}.srt")
        if os.path.exists(out_file) and os.path.getsize(out_file) > 100:
            print(f" -> Đã có sẵn [{lang_name}]: {os.path.basename(out_file)}", flush=True)
            generated_files[lang_code] = out_file
            continue

        print(f" -> Đang dịch sang [{lang_name}] ({len(parsed)} đoạn thoại)...", flush=True)
        translated_blocks = []
        for idx, timing, text in parsed:
            tr_text = translate_text_gtx(text, lang_code, source_lang='en')
            translated_blocks.append((idx, timing, tr_text))
            time.sleep(0.05) # tránh spam

        write_srt(out_file, translated_blocks)
        print(f"    [Xong] Đã xuất bản: {os.path.basename(out_file)}", flush=True)
        generated_files[lang_code] = out_file

    return generated_files

if __name__ == '__main__':
    source_srt = 'content/subtitles/ep1/ep1_en.srt'
    if not os.path.exists(source_srt):
        source_srt = 'downloads/ep1_en.srt'
    generate_multilingual_subtitles_for_ep(source_srt, 'content/subtitles/ep1')
