import base64
import json
import hashlib
import json
import time

import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from commons_lang import object_utils
from language_translation.translate.provider.base import BaseProvider


class YoudaoProvider(BaseProvider):

    def __init__(
            self,
            from_lang: str,
            to_lang: str,
            cookie: str = None,
            **kwargs
    ):
        if not cookie:
            raise ValueError("cookie is required")
        super().__init__(from_lang, to_lang, cookie, **kwargs)
        self.timestamp = str(int(time.time() * 1000))
        key = hashlib.md5(
            "ydsecret://query/key/B*RGygVywfNBwpmBaZg*WT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl".encode()
        ).digest()
        iv = hashlib.md5(
            "ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4".encode()
        ).digest()
        self.cipher = AES.new(key, AES.MODE_CBC, iv)

    def __get_sign(self):
        e = f"client=fanyideskweb&mysticTime={self.timestamp}&product=webfanyi&key=Vy4EQ1uwPkUoqvcP1nIu6WiAjxFeA3Y9"
        return hashlib.md5(e.encode()).hexdigest()

    def __get_response(self, text: str):
        headers = {
            "Cookie": self.cookie,
            "Referer": "https://fanyi.youdao.com/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
        }
        data = {
            "i": text,
            "from": "auto",
            "to": "",
            "domain": "0",
            "dictResult": "true",
            "keyid": "webfanyi",
            "sign": self.__get_sign(),
            "client": "fanyideskweb",
            "product": "webfanyi",
            "appVersion": "1.0.0",
            "vendor": "web",
            "pointParam": "client,mysticTime,product",
            "mysticTime": self.timestamp,
            "keyfrom": "fanyi.web",
            "mid": "1",
            "screen": "1",
            "model": "1",
            "network": "wifi",
            "abtest": "0",
            "yduuid": "abcdefg",
        }
        return requests.post("https://dict.youdao.com/webtranslate", headers=headers, data=data).text

    def __encrypt_data(self, resp):
        ciphertext = base64.urlsafe_b64decode(resp)
        plaintext = unpad(self.cipher.decrypt(ciphertext), AES.block_size)
        return plaintext.decode()

    def translate(self, text: str) -> str | None:
        resp = self.__get_response(text)
        if resp:
            data = self.__encrypt_data(resp)
            results = object_utils.get(json.loads(data), "translateResult", [])
            if object_utils.is_not_empty(results):
                return object_utils.get(results[0][0], "tgt")
        return None
