#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
火山方舟翻译测试脚本（Python版本）
使用火山方舟SDK进行中文到西班牙语的翻译测试
"""

import os
import time
from volcenginesdkarkruntime import Ark


class VolcanoTranslator:
    """火山方舟翻译器"""
    
    def __init__(self, api_key: str, model: str = "doubao-seed-1-6-thinking-250715"):
        """
        初始化翻译器
        :param api_key: API密钥
        :param model: 模型ID
        """
        self.client = Ark(api_key=api_key)
        self.model = model
    
    def translate_address(self, address: str) -> dict:
        """
        翻译地址
        :param address: 中文地址
        :return: 翻译结果字典
        """
        system_prompt = """你是一位专业的中西翻译专家,擅长翻译中国的地址信息。请将提供的中文地址准确翻译成西班牙语。

翻译要求:
1. 保持地址的层级结构(省-市-区-街道-门牌号-房间号)
2. 地名采用拼音或官方西语译名,必要时保留中文并附注拼音
3. 保留重要的数字、楼号、房间号等信息
4. 符合西班牙语地址表达习惯
5. 只输出翻译后的西班牙语地址,不要添加任何解释

示例格式:
中文: 云南省昆明市五华区菱角塘北区14幢704室
西语: Unidad 14, Habitación 704, Urbanización Lingjiaotang Norte, Distrito Wuhua, Ciudad de Kunming, Provincia de Yunnan"""
        
        user_prompt = f"请将以下中文地址翻译成西班牙语:\n\n{address}"
        
        return self._call_api(system_prompt, user_prompt)
    
    def translate_business_scope(self, business_scope: str) -> dict:
        """
        翻译营业范围
        :param business_scope: 中文营业范围
        :return: 翻译结果字典
        """
        system_prompt = """你是一位专业的中西商务翻译专家,擅长翻译中国企业的营业范围。请将提供的中文营业范围准确翻译成西班牙语。

翻译要求:
1. 准确翻译每一项业务内容
2. 保持专业术语的准确性
3. 使用分号(;)分隔不同的业务项目
4. 符合西班牙语商务文件的表达习惯
5. 只输出翻译后的西班牙语营业范围,不要添加任何解释

常见术语参考:
- 技术服务 = servicios técnicos
- 技术开发 = desarrollo técnico
- 技术咨询 = consultoría técnica
- 批发 = venta al por mayor
- 零售 = venta al por menor
- 销售 = venta
- 租赁 = arrendamiento"""
        
        user_prompt = f"请将以下中文营业范围翻译成西班牙语:\n\n{business_scope}"
        
        return self._call_api(system_prompt, user_prompt)
    
    def translate(self, text: str, text_type: str = "general") -> dict:
        """
        通用翻译方法
        :param text: 待翻译文本
        :param text_type: 类型 (address/business_scope/general)
        :return: 翻译结果字典
        """
        if text_type == "address":
            return self.translate_address(text)
        elif text_type == "business_scope":
            return self.translate_business_scope(text)
        else:
            system_prompt = "你是一位专业的中西翻译专家。请将提供的中文准确翻译成西班牙语,只输出翻译结果。"
            return self._call_api(system_prompt, text)
    
    def _call_api(self, system_prompt: str, user_prompt: str) -> dict:
        """
        调用火山方舟API
        :param system_prompt: 系统提示词
        :param user_prompt: 用户提示词
        :return: 结果字典
        """
        try:
            start_time = time.time()
            
            completion = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ]
            )
            
            end_time = time.time()
            duration = round((end_time - start_time) * 1000, 2)  # 毫秒
            
            return {
                "success": True,
                "translation": completion.choices[0].message.content.strip(),
                "usage": {
                    "prompt_tokens": completion.usage.prompt_tokens,
                    "completion_tokens": completion.usage.completion_tokens,
                    "total_tokens": completion.usage.total_tokens
                },
                "duration_ms": duration,
                "model": completion.model
            }
        
        except Exception as e:
            end_time = time.time()
            duration = round((end_time - start_time) * 1000, 2)
            
            return {
                "success": False,
                "error": str(e),
                "translation": None,
                "duration_ms": duration
            }


def main():
    """主测试函数"""
    
    # 配置API Key
    # 方式1: 从环境变量读取
    api_key = os.environ.get("ARK_API_KEY")
    
    # 方式2: 直接设置（不推荐，仅用于测试）
    if not api_key:
        api_key = "d91aa1ca-8e34-490a-9a1d-eb3a7b794484"  # 替换为你的API Key
    
    # 模型ID
    model = "doubao-seed-1-6-thinking-250715"
    
    print("=" * 60)
    print("火山方舟翻译测试（Python版本）")
    print("=" * 60)
    print()
    
    # 初始化翻译器
    translator = VolcanoTranslator(api_key, model)
    
    total_duration = 0
    
    # 测试1: 翻译地址
    print("【测试1: 翻译地址】")
    address1 = "广州市海珠区新业路55号之21-B60-2房"
    print(f"原文: {address1}")
    
    result1 = translator.translate_address(address1)
    
    if result1["success"]:
        print(f"译文: {result1['translation']}")
        print(f"消耗tokens: {result1['usage']['total_tokens']}")
        print(f"执行时长: {result1['duration_ms']} 毫秒")
        total_duration += result1['duration_ms']
    else:
        print(f"错误: {result1['error']}")
        print(f"执行时长: {result1['duration_ms']} 毫秒")
    
    print()
    
    # 测试2: 翻译营业范围
    print("【测试2: 翻译营业范围】")
    business_scope = "技术服务、技术开发、技术咨询、技术交流、技术转让、技术推广;电子元器件批发;互联网销售(除销售需要许可的商品);计算机及通讯设备租赁;计算机软硬件及辅助设备零售;金属材料销售;包装材料及制品销售;办公设备耗材销售;橡胶制品销售;塑料制品销售;塑料加工专用设备销售"
    print(f"原文: {business_scope}")
    
    result2 = translator.translate_business_scope(business_scope)
    
    if result2["success"]:
        print(f"译文: {result2['translation']}")
        print(f"消耗tokens: {result2['usage']['total_tokens']}")
        print(f"执行时长: {result2['duration_ms']} 毫秒")
        total_duration += result2['duration_ms']
    else:
        print(f"错误: {result2['error']}")
        print(f"执行时长: {result2['duration_ms']} 毫秒")
    
    print()
    
    # 测试3: 翻译另一个地址
    print("【测试3: 翻译营业执照地址】")
    address2 = "北京市朝阳区建国路88号SOHO现代城A座1501室"
    print(f"原文: {address2}")
    
    result3 = translator.translate(address2, "address")
    
    if result3["success"]:
        print(f"译文: {result3['translation']}")
        print(f"消耗tokens: {result3['usage']['total_tokens']}")
        print(f"执行时长: {result3['duration_ms']} 毫秒")
        total_duration += result3['duration_ms']
    else:
        print(f"错误: {result3['error']}")
        print(f"执行时长: {result3['duration_ms']} 毫秒")
    
    print()
    print("=" * 60)
    print("测试完成")
    print(f"总执行时长: {total_duration} 毫秒 ({round(total_duration / 1000, 2)} 秒)")
    print("=" * 60)


if __name__ == "__main__":
    main()