import requests

import jingrow
from jingrow.ai.utils.utils import update_status_progress, update_progress, send_notification, get_jingrow_api_headers, get_jingrow_api_url

# 默认的系统消息和用户内容
default_system_message = """
你是一位专业的中译英翻译专家。请将提供的中文内容翻译成地道、流畅的英文，确保保留原文的风格和语境。
翻译时要注意原文的专业术语和表达方式，使翻译结果符合英语的最佳实践。
只需返回翻译后的英文内容，不要包含任何其他说明或注释。
"""

default_user_content = "请将以下中文内容翻译成英文：\n\n{text}"

ai_settings = jingrow.get_single("Ai Settings")

# 定义请求ChatGPT的函数
def send_to_chatgpt(system_message, user_content):
    chatgpt_api_url = jingrow.db.get_single_value("Ai Settings", "chatgpt_api_url")
    chatgpt_api_key = jingrow.db.get_single_value("Ai Settings", "chatgpt_api_key")
    chatgpt_api_model = jingrow.db.get_single_value("Ai Settings", "chatgpt_api_model")
    
    payload = {
        "model": chatgpt_api_model,
        "messages": [
            {
                "role": "system", 
                "content": system_message
            },
            {
                "role": "user", 
                "content": user_content
            }
        ],
        "temperature": 0.3,
        "top_p": 0.9
    }
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {chatgpt_api_key}"
    }
    
    try:
        response = requests.post(chatgpt_api_url, headers=headers, json=payload)
        
        if response.status_code != 200:
            jingrow.log_error(f"Error: {response.status_code}, {response.text}", "GPT API 请求失败")
            return None
        
        return response.json()
    except Exception as e:
        jingrow.log_error(f"ChatGPT API请求异常: {str(e)}", "API请求异常")
        return None

# 定义请求DeepSeek的函数
def send_to_deepseek(system_message, user_content):
    deepseek_api_url = jingrow.db.get_single_value("Ai Settings", "deepseek_api_url")
    deepseek_api_key = ai_settings.get_password("deepseek_api_key", raise_exception=False)
    deepseek_api_model = jingrow.db.get_single_value("Ai Settings", "deepseek_api_model")
    
    payload = {
        "model": deepseek_api_model,
        "messages": [
            {
                "role": "system", 
                "content": system_message
            },
            {
                "role": "user", 
                "content": user_content
            }
        ],
        "temperature": 0.3,
        "top_p": 0.9
    }
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {deepseek_api_key}"
    }
    
    try:
        response = requests.post(deepseek_api_url, headers=headers, json=payload)
        
        if response.status_code != 200:
            jingrow.log_error(f"Error: {response.status_code}, {response.text}", "DeepSeek API 请求失败")
            return None
            
        return response.json()
    except Exception as e:
        jingrow.log_error(f"DeepSeek API请求异常: {str(e)}", "API请求异常")
        return None

# 定义请求Doubao的函数
def send_to_doubao(system_message, user_content):
    doubao_api_url = jingrow.db.get_single_value("Ai Settings", "doubao_api_url")
    doubao_api_key = ai_settings.get_password("doubao_api_key", raise_exception=False)
    doubao_api_model = jingrow.db.get_single_value("Ai Settings", "doubao_api_model")
    
    payload = {
        "model": doubao_api_model,
        "messages": [
            {
                "role": "system", 
                "content": system_message
            },
            {
                "role": "user", 
                "content": user_content
            }
        ],
        "temperature": 0.3,
        "top_p": 0.9
    }
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {doubao_api_key}"
    }
    
    try:
        response = requests.post(doubao_api_url, headers=headers, json=payload)
        
        if response.status_code != 200:
            jingrow.log_error(f"Error: {response.status_code}, {response.text}", "Doubao API 请求失败")
            return None
            
        return response.json()
    except Exception as e:
        jingrow.log_error(f"Doubao API请求异常: {str(e)}", "API请求异常")
        return None

# 定义处理翻译任务的函数
def process_translate_task(pg_name, pagetype):
    try:
        # 获取页面对象
        pg = jingrow.get_pg(pagetype, pg_name)
        if not pg:
            jingrow.log_error("处理翻译任务失败", f"找不到文档: {pagetype} {pg_name}")
            return False
        
        # 检查必要的字段
        if not hasattr(pg, "prompts_zh") or not pg.prompts_zh:
            jingrow.log_error("缺少中文内容", "翻译任务处理失败")
            return False
        
        # 更新状态为"任务进行中"
        update_status_progress(pagetype, pg_name, "任务进行中", 20)
        
        # 获取中文内容
        chinese_content = pg.prompts_zh
        
        # 更新进度为60%
        update_progress(pg_name, 60, pagetype)
        
        # 调用翻译函数获取英文翻译
        english_translation = get_translated_prompts(chinese_content)
        
        if not english_translation:
            return False
            
        # 更新文档
        jingrow.db.set_value(pagetype, pg_name, "prompts", english_translation)
        update_status_progress(pagetype, pg_name, "已翻译", 100)
        return True
            
    except Exception as e:
        jingrow.log_error(f"处理翻译任务时发生错误: {str(e)}", "翻译任务处理失败")
        update_status_progress(pagetype, pg_name, "任务未完成", 0)
        return False

# 调用Jingrow API获取翻译
def call_jtranslate_api(source_text, system_message=None, user_content=None):
    try:
        # 获取API URL
        api_url = f"{get_jingrow_api_url()}/jtranslate/get"
        
        headers = get_jingrow_api_headers()
        if not headers:
            send_notification("Jingrow API 未设置，请在 AI设置 中设置 Jingrow Api Key 和 Jingrow Api Secret")
            return None
            
        request_data = {"source_text": source_text}
        
        # 如果提供了自定义提示词，添加到请求数据中
        if system_message:
            request_data["system_message"] = system_message
        if user_content:
            request_data["user_content"] = user_content
            
        resp = requests.post(api_url, json=request_data, headers=headers)
        if resp.status_code != 200:
            return None
        try:
            resp_json = resp.json()
        except Exception:
            return None
        # 优先找data字段，其次找message.data
        data = resp_json.get("data") or (resp_json.get("message") or {}).get("data")
        return data or None
    except Exception:
        return None

# 翻译函数只负责翻译
def get_translated_prompts(source_text):
    try:
        translation_model = jingrow.db.get_single_value("Ai Settings", "translation_model")
        system_message = jingrow.db.get_single_value("Ai Settings", "translate_system_message") or default_system_message
        user_content = jingrow.db.get_single_value("Ai Settings", "translate_user_content") or default_user_content
        
        if translation_model == "Jingrow":
            data = call_jtranslate_api(source_text, system_message, user_content.format(text=source_text))
            if data:
                return data.get("english_translation")
            return None

        # 使用选定的模型进行翻译
        translation_response = None
        if translation_model == "DeepSeek":
            translation_response = send_to_deepseek(system_message, user_content.format(text=source_text))
        elif translation_model == "Doubao":
            translation_response = send_to_doubao(system_message, user_content.format(text=source_text))
        else:  # 默认使用ChatGPT
            translation_response = send_to_chatgpt(system_message, user_content.format(text=source_text))
        
        if translation_response is None:
            return None
        
        choices = translation_response.get("choices", [])
        if not choices:
            return None
        
        # 获取翻译结果
        english_translation = choices[0].get("message", {}).get("content", "").strip()    
        return english_translation
    except Exception as e:
        jingrow.log_error(f"翻译失败: {str(e)}", "翻译处理错误")
        return None

