# translate.py

import hashlib
import random
import requests
import settings


def iso_to_baidu_lang(iso_code: str) -> str:
    """将 ISO 639-1 语言代码转换为百度翻译所需代码"""
    code = settings.BAIDU_LANG_MAP.get(iso_code.lower())
    if code is None:
        raise ValueError(f"不支持的语言代码: {iso_code}")
    return code


def translate_text(text: str, source_lang: str = "auto", target_lang: str = "zh") -> dict:
    """
    使用百度翻译 API 进行多语言翻译
    :param text: 原文
    :param source_lang: 源语言 ISO 代码（如 'ko', 'en'），默认 'auto' 自动检测
    :param target_lang: 目标语言 ISO 代码，默认 'zh'
    :return: {'success': bool, 'translated_text': str, 'error': str (optional)}
    """
    if not text or not text.strip():
        return {"success": False, "error": "输入文本为空"}

    try:
        from_lang = "auto" if source_lang == "auto" else iso_to_baidu_lang(source_lang)
        to_lang = iso_to_baidu_lang(target_lang)
    except ValueError as e:
        return {"success": False, "error": str(e)}

    q = text[:settings.MAX_TEXT_LENGTH]

    try:
        salt = random.randint(32768, 65536)
        sign_str = settings.BAIDU_APP_ID + q + str(salt) + settings.BAIDU_SECRET_KEY
        sign = hashlib.md5(sign_str.encode()).hexdigest()

        payload = {
            'q': q,
            'from': from_lang,
            'to': to_lang,
            'appid': settings.BAIDU_APP_ID,
            'salt': salt,
            'sign': sign
        }

        response = requests.post(
            "https://fanyi-api.baidu.com/api/trans/vip/translate",
            data=payload,
            timeout=settings.TIMEOUT
        )
        response.raise_for_status()
        result = response.json()

        if 'error_code' in result:
            error_msg = f"百度API错误 {result.get('error_code')}: {result.get('error_msg', '')}"
            return {"success": False, "error": error_msg}

        if 'trans_result' not in result or not result['trans_result']:
            return {"success": False, "error": "翻译结果为空"}

        translated = result['trans_result'][0]['dst']
        return {"success": True, "translated_text": translated}

    except requests.exceptions.RequestException as e:
        return {"success": False, "error": f"网络请求失败: {str(e)}"}
    except Exception as e:
        return {"success": False, "error": f"未知错误: {str(e)}"}
