import json

import requests
import urllib3

from fake_useragent import FakeUserAgent
from requests.adapters import HTTPAdapter


def get_did(user_agent):
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Host": "www.kuaishou.com",
        "Sec-Ch-Ua": '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        "Sec-Ch-Ua-Mobile": "?0",
        "Sec-Ch-Ua-Platform": '"macOS"',
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": user_agent
    }
    response = requests.get('https://www.kuaishou.com/search/video?searchKey=', headers=headers)
    value_list = response.cookies.values()
    for v in value_list:
        if "web_" in v:
            return v
    return ""


def get_captchaSession(did, user_agent):
    payload = {
        "operationName": "graphqlSearchUser",
        "variables": {
            "keyword": "周大爷不服老"
        },
        "query": "query graphqlSearchUser($keyword: String, $pcursor: String, $searchSessionId: String) {\n  visionSearchUser(keyword: $keyword, pcursor: $pcursor, searchSessionId: $searchSessionId) {\n    result\n    users {\n      fansCount\n      photoCount\n      isFollowing\n      user_id\n      headurl\n      user_text\n      user_name\n      verified\n      verifiedDetail {\n        description\n        iconType\n        newVerified\n        musicCompany\n        type\n        __typename\n      }\n      __typename\n    }\n    searchSessionId\n    pcursor\n    __typename\n  }\n}\n"
    }
    headers = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '668',
        'Content-Type': 'application/json',
        'Cookie': 'did={}'.format(did),
        'Host': 'www.kuaishou.com',
        'Origin': 'https://www.kuaishou.com',
        # 'Referer': 'https://www.kuaishou.com/search/author?searchKey=%E5%91%A8%E5%A4%A7%E7%88%B7%E4%B8%8D%E6%9C%8D%E8%80%81',
        'Sec-Ch-Ua': '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"macOS"',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': user_agent
    }
    urllib3.disable_warnings()
    s = requests.session()
    # max_retries=3 重试3次
    s.mount("http://", HTTPAdapter(max_retries=3))
    s.mount("https://", HTTPAdapter(max_retries=3))
    response = s.post(
        url="https://www.kuaishou.com/graphql",
        headers=headers,
        data=json.dumps(payload),
        # proxies=Common.tunnel_proxies(),
        verify=False,
        timeout=10,
    )
    response.close()
    # print(response.json())
    return response.json()['data']['url'].split("?")[-1]


def get_config(did, user_agent, captcha_session):
    payload = captcha_session
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '411',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': 'did='.format(did),
        'Host': 'captcha.zt.kuaishou.com',
        'Origin': 'https://captcha.zt.kuaishou.com',
        'Referer': 'https://captcha.zt.kuaishou.com/iframe/index.html?{}'.format(captcha_session),
        'Sec-Ch-Ua': '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"macOS"',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': user_agent
    }
    urllib3.disable_warnings()
    s = requests.session()
    # max_retries=3 重试3次
    s.mount("http://", HTTPAdapter(max_retries=3))
    s.mount("https://", HTTPAdapter(max_retries=3))
    response = s.post(
        url="https://captcha.zt.kuaishou.com/rest/zt/captcha/sliding/config",
        headers=headers,
        data=payload,
        # proxies=Common.tunnel_proxies(),
        verify=False,
        timeout=10,
    )
    response.close()
    print(json.dumps(response.json(), ensure_ascii=False, indent=4))
    return response.json()['captchaSn']


def check(encrypted_param, did, user_agent):
    payload = {
        "verifyParam": encrypted_param
    }
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '9246',
        'Content-Type': 'application/json',
        'Cookie': 'did={}'.format(did),
        'Host': 'captcha.zt.kuaishou.com',
        'Origin': 'https://captcha.zt.kuaishou.com',
        'Sec-Ch-Ua': '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"macOS"',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': user_agent
    }
    urllib3.disable_warnings()
    s = requests.session()
    # max_retries=3 重试3次
    s.mount("http://", HTTPAdapter(max_retries=3))
    s.mount("https://", HTTPAdapter(max_retries=3))
    response = s.post(
        url="https://captcha.zt.kuaishou.com/rest/zt/captcha/sliding/kSecretApiVerify",
        headers=headers,
        data=json.dumps(payload),
        verify=False,
        timeout=10,
    )
    response.close()


if __name__ == "__main__":
    fake_agent = FakeUserAgent().random
    fake_did = get_did(fake_agent)
    print(fake_did)
    captcha_session = get_captchaSession(did=fake_did, user_agent=fake_agent)
    print(captcha_session)
    captchaSn = get_config(did=fake_did, user_agent=fake_agent, captcha_session=captcha_session)
    print(captchaSn)
