import random
import uuid
import time
import math
from urllib.parse import quote
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

from app.utils import custom_base64
from app.utils.common import get_proxies
from app.utils.custom_base64 import CustomBase64


class GenCookie:
    xft_key = "01hltm8JcnEfqy4t"
    xft_iv = "Fsxdviz5BSekw320"
    xfcs_key = "YuoCK92D8mhzMCIQ"
    xfcs_iv = "MBwPm05VuDBq4sst"
    url = 'https://xlab.baidu.com/jnmq'
    headers = {
        'Sec-Ch-Ua-Platform': '"Windows"',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
        'Sec-Ch-Ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Sec-Ch-Ua-Mobile': '?0',
        'Accept': '*/*',
        'Origin': 'https://help.baidu.com',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://help.baidu.com/',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Priority': 'u=1, i'
    }

    @staticmethod
    def aes_decrypt(ciphertext_hex: str, key_str: str, iv_str: str) -> str:
        # 将密钥和IV从字符串编码为字节
        key = key_str.encode('utf-8')
        iv = iv_str.encode('utf-8')

        # 验证密钥和IV的长度（AES-128要求16字节）
        if len(key) != 16:
            raise ValueError("密钥长度必须为16字节")
        if len(iv) != 16:
            raise ValueError("IV长度必须为16字节")

        # 将HEX密文字符串转换为字节
        ciphertext = bytes.fromhex(ciphertext_hex)

        # 创建AES-CBC解密器并解密数据
        cipher = (
            AES.new(key, AES.MODE_CBC, iv))
        decrypted_data = cipher.decrypt(ciphertext)

        # 去除填充并解码为明文
        plaintext = unpad(decrypted_data, AES.block_size).decode('utf-8')
        return plaintext

    @staticmethod
    def aes_encrypt(plaintext: str, key_str: str, iv_str: str) -> str:
        key = key_str.encode('utf-8')
        iv = iv_str.encode('utf-8')
        if len(key) != 16:
            raise ValueError("密钥长度必须为16字节")
        if len(iv) != 16:
            raise ValueError("IV长度必须为16字节")
        # 将明文填充并转换为字节
        to_encrypt_data = pad(plaintext.encode('utf-8'), AES.block_size)
        # 创建AES-CBC加密器并加密数据
        cipher = AES.new(key, AES.MODE_CBC, iv)
        ciphertext = cipher.encrypt(to_encrypt_data)
        # 返回大写的HEX字符串
        return ciphertext.hex().upper()

    @staticmethod
    def get_timestamp():
        return math.ceil(time.time() * 1000)

    @staticmethod
    def get_uuid_str():
        return str(uuid.uuid4()).lower()

    @staticmethod
    def get_cookie(cookie_name, timestamp=''):
        if cookie_name == 'XFI':
            return GenCookie.get_uuid_str()

        if cookie_name == 'XFCS':
            plain_text = f'{timestamp}#ooox'
            return GenCookie.aes_encrypt(plain_text, GenCookie.xfcs_key, GenCookie.xfcs_iv)

    @staticmethod
    def get_xft_cookie(xfi, cookie, json_data_28='', json_data_ts='', json_data_x=''):
        json_data_28 = r'''{"na":true,"fn":true,"wnd":true,"fnc":"J is not a function\nTypeError: J is not a function\n    at Object.JnZbY (https://xlab.baidu.com/res/bundle.p.php:1:91494)\n    at eval (eval at D (https://xlab.baidu.com/res/bundle.p.php:1:91853), <anonymous>:7:24)\n    at D (https://xlab.baidu.com/res/bundle.p.php:1:91853)\n    at C2 (https://xlab.baidu.com/res/bundle.p.php:1:131002)\n    at Object.QGCWm (https://xlab.baidu.com/res/bundle.p.php:1:123081)\n    at C3 (https://xlab.baidu.com/res/bundle.p.php:1:131494)","fns":"Function.prototype.toString requires that 'this' be a Function\nTypeError: Function.prototype.toString requires that 'this' be a Function\n    at toString (<anonymous>)\n    at Object.JnZbY (https://xlab.baidu.com/res/bundle.p.php:1:91494)\n    at eval (eval at D (https://xlab.baidu.com/res/bundle.p.php:1:92223), <anonymous>:7:76)\n    at D (https://xlab.baidu.com/res/bundle.p.php:1:92223)\n    at C2 (https://xlab.baidu.com/res/bundle.p.php:1:131002)\n    at Object.QGCWm (https://xlab.baidu.com/res/bundle.p.php:1:123081)\n    at C3 (https://xlab.baidu.com/res/bundle.p.php:1:131494)","fnpc":"function call() { [native code] }","fnps":"function toString() { [native code] }","wglp":true} '''
        json_data_29 = 'b30'
        json_data_gd = xfi
        json_data_sk = 'p'
        json_data_ts = '{"d":' + str(
            GenCookie.get_timestamp()) + ',"qc":"https://help.baidu.com/jubao?source=search","v":"error","iv":30,"vb":33,"pv":"ooxo","dw":"fine","fx":5,"pq":"1728*1117","c":"1728*1030","ra":"38-","ot":"landscape-primary","ls":"error","ks":"1728*1029","ke":false,"w":-480,"uy":"Asia/Shanghai","bx":1,"fh":5984,"tt":[0,false,false],"hd":[false,"visible"],"tx":2,"nw":["Google Inc. (Apple)","ANGLE (Apple, ANGLE Metal Renderer: Apple M3 Max, Unspecified Version)"],"bb":{"vendorSub":"","productSub":"20030107","vendor":"Google Inc.","maxTouchPoints":0,"scheduling":{},"userActivation":{"hasBeenActive":false,"isActive":false},"doNotTrack":{},"geolocation":{},"connection":{"onchange":{},"effectiveType":"4g","rtt":100,"downlink":2.2,"saveData":false},"pdfViewerEnabled":true,"webkitTemporaryStorage":{},"webkitPersistentStorage":{},"windowControlsOverlay":{"visible":false,"ongeometrychange":{}},"hardwareConcurrency":14,"cookieEnabled":true,"appCodeName":"Mozilla","appName":"Netscape","appVersion":"5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36","platform":"MacIntel","product":"Gecko","userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36","language":"zh-CN","languages":{"0":"zh-CN","1":"zh"},"onLine":true,"webdriver":false,"deprecatedRunAdAuctionEnforcesKAnonymity":false,"protectedAudience":{},"bluetooth":{},"storageBuckets":{},"clipboard":{},"credentials":{},"keyboard":{},"managed":{"onmanagedconfigurationchange":{}},"mediaDevices":{"ondevicechange":{}},"storage":{},"serviceWorker":{"controller":{},"ready":{},"oncontrollerchange":{},"onmessage":{},"onmessageerror":{}},"virtualKeyboard":{"boundingRect":{"x":0,"y":0,"width":0,"height":0,"top":0,"right":0,"bottom":0,"left":0},"overlaysContent":false,"ongeometrychange":{}},"wakeLock":{},"deviceMemory":8,"userAgentData":{"brands":{"0":{"brand":"Chromium","version":"134"},"1":{"brand":"Not:A-Brand","version":"24"},"2":{"brand":"Google Chrome","version":"134"}},"mobile":false,"platform":"macOS"},"login":{},"ink":{},"mediaCapabilities":{},"devicePosture":{"type":"continuous","onchange":{}},"hid":{"onconnect":{},"ondisconnect":{}},"locks":{},"gpu":{"wgslLanguageFeatures":{"size":4}},"mediaSession":{"metadata":{},"playbackState":"none"},"permissions":{},"presentation":{"defaultRequest":{},"receiver":{}},"usb":{"onconnect":{},"ondisconnect":{}},"xr":{"ondevicechange":{}},"serial":{"onconnect":{},"ondisconnect":{}},"w":false,"u":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36","v":"Google Inc.","p":"MacIntel","t":0,"c":14},"tw":["navigation","trustedTypes","onbeforeinput","onbeforematch","onbeforetoggle","oncontentvisibilityautostatechange","scheduler","chrome","launchQueue","sharedStorage","documentPictureInPicture","getScreenDetails","queryLocalFonts","originAgentCluster","onpageswap","onpagereveal","credentialless","fence","onscrollend","onscrollsnapchange","onscrollsnapchanging","_hmt","T","baidu","$BAIDU$","baiduInstance","Sizzle","$","jQuery","isSingleInstanceProd","isLoginInstance","saveInitInstance","getInitInstance","passport","upsmsStore","YY_TPL_CONFIG","body","exeJsonp","initSearchForm","showPage","getOS","getBrowser","userAgent","$Class","footer","SetTab","login","uploadImg","customDDl","_bdhm_loaded_fb481430f1a5a6c7044229532823b9fd","mini_tangram_log_3g2jxp","a0K","a0C","sugapi","protocol","suggestParam","suggestion","searchSugCbk","parseJSON","reloadPage","proxy","TipTog","Popup","vaildForm","checkform","uploadControl","quesPage","searchPage","mmm","specialObject","popObject","tousuForm","jubaoForm"],"ps":[["PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["Chrome%20PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["Chromium%20PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["Microsoft%20Edge%20PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["WebKit%20built-in%20PDF","internal-pdf-viewer","Portable%20Document%20Format"]],"cx":"6b5a85e2","ub":true,"xn":true,"zu":false,"tm":[false,false],"ut":true,"yp":true,"uz":true,"ch":true,"xx":{"chrome":true,"app":true},"um":[0]} '
        # json_data_ts = '{"d":'+ str(gen_cookie.get_timestamp()) +',"qc":"https://help.baidu.com/jubao?source=search","v":"https://www.baidu.com/s?wd=aaa&rsv_spt=1&rsv_iqid=0xbfd5e8930195ecd1&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_dl=tb&rsv_enter=1&rsv_sug3=4&rsv_sug1=4&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&prefixsug=aaa&rsp=5&inputT=375&rsv_sug4=557&p_tk=7492XAv14v6WVtYVmfp2uARL8xBGjUO8gSvuOCD5kvVwUHcZAYDBbXgYNJUEh1TsGb9FlyB3lreXpmYMtb08ujLbz%2Bfmeqo7pHumOknR%2Fgtz9Lq%2FfiuC2wL4oeRhnocw6FTp7ma5r34KLRI6RHYD2SqSPw%3D%3D&p_timestamp=1741793172&p_sign=2e0f6e82e90baec91b5b52700b20a9c3&p_signature=ee2b6b945968237e864b7fb77f042ae6&__pc2ps_ab=7492XAv14v6WVtYVmfp2uARL8xBGjUO8gSvuOCD5kvVwUHcZAYDBbXgYNJUEh1TsGb9FlyB3lreXpmYMtb08ujLbz%2Bfmeqo7pHumOknR%2Fgtz9Lq%2FfiuC2wL4oeRhnocw6FTp7ma5r34KLRI6RHYD2SqSPw%3D%3D|1741793172|ee2b6b945968237e864b7fb77f042ae6|2e0f6e82e90baec91b5b52700b20a9c3","iv":24,"vb":33,"pv":"oxxo","dw":"fine","fx":5,"pq":"2560*1440","c":"2560*1392","ra":"-","ot":"landscape-primary","ls":"error","ks":"2564*1396","ke":false,"w":-480,"uy":"Asia/Shanghai","bx":1,"fh":5984,"tt":[0,false,false],"hd":[false,"visible"],"tx":1.5,"nw":["Google Inc. (Google)","ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"],"bb":{"vendorSub":"","productSub":"20030107","vendor":"Google Inc.","maxTouchPoints":0,"scheduling":{},"userActivation":{"hasBeenActive":true,"isActive":true},"doNotTrack":{},"geolocation":{},"connection":{"onchange":{},"effectiveType":"4g","rtt":50,"downlink":1.4,"saveData":false},"pdfViewerEnabled":true,"webkitTemporaryStorage":{},"webkitPersistentStorage":{},"windowControlsOverlay":{"visible":false,"ongeometrychange":{}},"hardwareConcurrency":12,"cookieEnabled":true,"appCodeName":"Mozilla","appName":"Netscape","appVersion":"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36","platform":"Win32","product":"Gecko","userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36","language":"zh-CN","languages":{"0":"zh-CN"},"onLine":true,"webdriver":false,"deprecatedRunAdAuctionEnforcesKAnonymity":false,"protectedAudience":{},"bluetooth":{},"storageBuckets":{},"clipboard":{},"credentials":{},"keyboard":{},"managed":{"onmanagedconfigurationchange":{}},"mediaDevices":{"ondevicechange":{}},"storage":{},"serviceWorker":{"controller":{},"ready":{},"oncontrollerchange":{},"onmessage":{},"onmessageerror":{}},"virtualKeyboard":{"boundingRect":{"x":0,"y":0,"width":0,"height":0,"top":0,"right":0,"bottom":0,"left":0},"overlaysContent":false,"ongeometrychange":{}},"wakeLock":{},"deviceMemory":8,"userAgentData":{"brands":{"0":{"brand":"Chromium","version":"134"},"1":{"brand":"Not:A-Brand","version":"24"},"2":{"brand":"Google Chrome","version":"134"}},"mobile":false,"platform":"Windows"},"cookieDeprecationLabel":{},"login":{},"ink":{},"mediaCapabilities":{},"devicePosture":{"type":"continuous","onchange":{}},"hid":{"onconnect":{},"ondisconnect":{}},"locks":{},"gpu":{"wgslLanguageFeatures":{"size":4}},"mediaSession":{"metadata":{},"playbackState":"none"},"permissions":{},"presentation":{"defaultRequest":{},"receiver":{}},"usb":{"onconnect":{},"ondisconnect":{}},"xr":{"ondevicechange":{}},"serial":{"onconnect":{},"ondisconnect":{}},"w":false,"u":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36","v":"Google Inc.","p":"Win32","t":0,"c":12},"tw":["navigation","trustedTypes","onbeforeinput","onbeforematch","onbeforetoggle","oncontentvisibilityautostatechange","scheduler","chrome","launchQueue","sharedStorage","documentPictureInPicture","getScreenDetails","queryLocalFonts","originAgentCluster","onpageswap","onpagereveal","credentialless","fence","onscrollend","onscrollsnapchange","onscrollsnapchanging","define","ethereum","_hmt","T","baidu","$BAIDU$","baiduInstance","Sizzle","$","jQuery","isSingleInstanceProd","isLoginInstance","saveInitInstance","getInitInstance","passport","upsmsStore","YY_TPL_CONFIG","body","exeJsonp","initSearchForm","showPage","getOS","getBrowser","userAgent","$Class","footer","SetTab","login","uploadImg","customDDl","_bdhm_loaded_fb481430f1a5a6c7044229532823b9fd","mini_tangram_log_dikjbw","mini_tangram_log_jzofcu","a0K","a0C","sugapi","protocol","suggestParam","suggestion","searchSugCbk","parseJSON","reloadPage","proxy","TipTog","Popup","vaildForm","checkform","uploadControl","quesPage","searchPage","mmm","specialObject","popObject","tousuForm","jubaoForm"],"ps":[["PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["Chrome%20PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["Chromium%20PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["Microsoft%20Edge%20PDF%20Viewer","internal-pdf-viewer","Portable%20Document%20Format"],["WebKit%20built-in%20PDF","internal-pdf-viewer","Portable%20Document%20Format"]],"cx":"73d1b57b","ub":true,"xn":true,"zu":false,"tm":[false,false],"ut":true,"yp":true,"uz":true,"ch":true,"xx":{"chrome":true,"app":true},"um":[1]}'
        json_data_ub = '0.8.5'
        json_data_x = '{"lz":"n/a","bz":[71,false],"gg":[1197130899456,0],"su":[176,{"others":157,"chrome":19}],"l":true,"nb":false,"e":[0,null,null,null],"t":true,"bn":false,"iu":[false,null,null,null],"io":"oooooooooooooooooooooooooooo","nh":"ooooooooooooooooooooooooooooooooooooooooooooooooo","p":"4565C4B32DBA773AF9F3978E7815A945","ud":"n/a","sf":"00000000000000"} '
        plain_text = f'{{"28":"{CustomBase64.encode(json_data_28)}","29":"{(json_data_29)}","gd":"{json_data_gd}"' + \
                     f',"sk":"{json_data_sk}","ts":"{CustomBase64.encode(json_data_ts)}","ub":"{json_data_ub}"' + \
                     f',"x":"{CustomBase64.encode(json_data_x)}"}}'
        # print(plain_text)
        encrypted_text = GenCookie.aes_encrypt(plain_text, GenCookie.xft_key, GenCookie.xft_iv)
        post_data = {'p': encrypted_text}
        headers_copy = GenCookie.headers.copy()
        headers_copy.update({'cookie': cookie})
        resp = requests.post(url=GenCookie.url, headers=headers_copy, data=post_data, proxies=get_proxies())
        return resp.json().get('s')
        # post to https://xlab.baidu.com/jnmq p=enc

    @staticmethod
    def run(cookie):
        try:
            xfi_cookie = GenCookie.get_cookie('XFI')
            xfcs_cookie = GenCookie.get_cookie('XFCS', str(GenCookie.get_timestamp()))
            xft_cookie = GenCookie.get_xft_cookie(xfi_cookie, cookie=cookie)
            # urlencode
            xft_cookie = quote(xft_cookie)
            time_stamp = math.ceil(time.time())
            final_cookie = f'{cookie}; Hm_lvt_fb481430f1a5a6c7044229532823b9fd={time_stamp - random.randint(800, 1000)};Hm_lvt_fb481430f1a5a6c7044229532823b9fd={time_stamp}; XFI={xfi_cookie}; XFCS={xfcs_cookie}; XFT={xft_cookie};'
        except Exception as e:
            # 这里是什么意思？原来代码就这么写的，没动过
            return
            final_cookie = f'{cookie}; Hm_lvt_fb481430f1a5a6c7044229532823b9fd={time_stamp - random.randint(800, 1000)};Hm_lvt_fb481430f1a5a6c7044229532823b9fd={time_stamp}; XFI={xfi_cookie}; XFCS={xfcs_cookie}; '
        return final_cookie
