import sys
import io
import aiohttp
import asyncio
import langid

# 设置标准输出为 UTF-8 编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 获取命令行参数中的输入文本
originalText = sys.argv[1]

# 设置你的 DeepL API 密钥 
# 进入这个网址注册获取，填入邀请码可以额外获得20W额度，  付费的话每个月4元50万字数
#  邀请码：OPk8XTjdGU   https://deepl-pro.com/#/translate?referral_code=OPk8XTjdGU
auth_key = ""  # 替换为你的实际 API 密钥 
server_url = "https://api.deepl-pro.com"

async def translate(session, text, target_lang):
    headers = {
        "Authorization": f"DeepL-Auth-Key {auth_key}"
    }
    data = {
        "text": text,
        "target_lang": target_lang
    }
    async with session.post(f"{server_url}/v2/translate", headers=headers, data=data) as response:
        return await response.json()

async def main():
    # 检查输入文本的字符数是否超过9个字符
    if len(originalText) > 9:
        # 使用 langid 进行语言检测
        detected_lang, confidence = langid.classify(originalText)

        # 根据检测到的语言选择目标语言
        if detected_lang in ['zh', 'zh-cn', 'zh-tw']:
            target_lang = "EN-GB"  # 或者 "EN-US"
        else:
            target_lang = "ZH"

        async with aiohttp.ClientSession() as session:
            result = await translate(session, originalText, target_lang)
            translation = result['translations'][0]['text']

            # 构建输出字符串
            output = f"""
            <html>
            <head>
            <style type="text/css">
            button {{
                font-size: 11px;
                padding: 1px 3px;
                float: right;
                background-color: lightblue;
                border: none;
                border-radius: 3px;
                cursor: pointer;
            }}
            #copy-status-1 {{
                font-size: 11px;
                margin-left: 10px;
                color: green;
            }}
            </style>
            </head>
            <body>
            {originalText}<br>
            {'-' * 9}<br>
            {translation}<br>
            <button onclick="copyToClipboard1('{translation}')">Copy Translation</button>
            <span id="copy-status-1"></span>
            <script type="text/javascript">
            function copyToClipboard1(text) {{
                var dummy = document.createElement("textarea");
                document.body.appendChild(dummy);
                dummy.value = text;
                dummy.select();
                document.execCommand("copy");
                document.body.removeChild(dummy);
                document.getElementById("copy-status-1").innerText = "已复制";
                setTimeout(() => {{
                    document.getElementById("copy-status-1").innerText = "";
                }}, 2000);
            }}
            </script>
            </body>
            </html>
            """

            # 打印输出字符串
            print(output)
    else:
        # 如果字符数不超过9个字符，直接退出脚本，不进行任何操作
        sys.exit()

if __name__ == '__main__':
    asyncio.run(main())