import hashlib
import json
import platform
import re
import subprocess
import tempfile
import time
from pathlib import Path

import requests
import tls_client
# import tls_client
# from curl_cffi import requests
import urllib3

urllib3.disable_warnings()
from loguru import logger

req_level = logger.level('REQU', no=100, color='<fg 34>')
js_level = logger.level('VMJS', no=100, color='<fg 185>')
work_dir = '/home/opt/lcc-reese84/'
if platform.platform().startswith('mac'):
    work_dir = '/Users/wang/Documents/company/lcc-reese84/'
log_dir = '/data/log/lcc-hv/'
if platform.platform().startswith('mac'):
    log_dir = '/Users/wang/company/lcc-reese84/'
Path(log_dir).mkdir(exist_ok=True, parents=True)
Path(work_dir).mkdir(exist_ok=True, parents=True)


def md5(text):
    m = hashlib.md5()
    m.update(text.encode())
    return m.hexdigest()


class Reese84ByPass(object):

    def __init__(self, target, proxy, thread_name='111'):
        self._session = tls_client.Session('chrome_120')

        # self._session = requests.Session()
        self._session.verify = False
        self.__target = target
        self.proxy = proxy
        if proxy != '':
            self._session.proxies = {
                'http': proxy,
                'https': proxy,
            }
        Path(log_dir).joinpath(thread_name).mkdir(exist_ok=True, parents=True)
        self.log = logger.bind(module_name=thread_name)
        self.thread_name = thread_name
        self.log.info(f'proxy:{proxy} target:{target}')
        self._cache_md5 = ''

        self.add_header = {
    "Host": "api-des.vietnamairlines.com",
    "cache-control": "max-age=0",
    "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
    # "x-d-token": "3:iwCNmAwBODyiGij2k1TbNg==:RQ4HPbCf1dy8mGVBSi22Mg5R3jAtX2F6K3rf8A2DcsuYhMo6ojRBMh5sl555dWza9osvqAfaholJRMIy8/BOtnpF4V3XNEMu2+fy8PxAA1nWYk0enzjEZppJTXa9ERyu7oK2MynGmsnMtAuiukjTB5vVO4rNUqYBc9QVTAe14lxt2b5kIaFNb9TTEfyzgRi0waAgMYZm7DWan4oLWhTt9ckXDVccXCaRNsUj0ls18l0AABUsZOm583OncXDayXbEpunzlaZtBA1dVpHwuTZdJEBdWfYRo/TC/7lgRzXGXosT6KVXigM6UVYL6ewl6eyHUEjkQQqiS+Kodf6LasO64HUz8Qr2fPtq0/lwxBKUrMGTpcaYHdhlhEWyh0zTwdenLGIaReBRlguDhIIKtgkVpFe36dz9euz9B5FDqzPTUUjovd7mf6U4Wzv8HIt6Agqt2C6B7y6hFRuAMzO4T+QGmiiA4QLQdVbl4kMAmZofdMGycVi4lXb6oB83B6eJwCXBsd2AaGo1SHe4f7wLBp+v4+vxuMTu5+2Gi1lUCU/uQjUBMnCiKEyAQ9j/h3BtnXxXWyIYmBR39qutG9wIGI54eoRSCYMmP8iJGoJgloYCiVkqgXvSPitQL2c2f66yX74T9v+TRXq88jQr8nvUcaCD07GPC5tRgDnoN3zP9YGh6PlOhtHxFdFdONEczW9U5SIVIkkhC8l5hErEoUxeXTutQlnLe7UEr0l15Yrwt+6eio6NUTSAlmOAtZfmcvFCAuFiRZMvwNWkdzax9G4ENuzlX8xA3V8Md6T2EhPlLNmTvjLGcpSu8UZc/Iyf3yeGf6k20nmYmkRouYa4FfWBVptS9g==:YgXEz38+yiN5A4fw0wIVgH2hQ2EHro9U+mhFyCBSq7w=",
    "sec-ch-ua-mobile": "?0",
    # "authorization": "Bearer l9ztxAZYQcWET8DK6WUKwX9cicMC",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "content-type": "application/json",
    "accept": "application/json",
    # "ama-client-facts": "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJmYWN0IiwiY291bnRyeUNvZGUiOiJDTiIsImxhbmd1YWdlIjoiZW4tR0IifQ.",
    # "ama-client-ref": "fba7f836-5c92-46f5-af00-8d10e6ae6799:0",
    "sec-ch-ua-platform": "\"macOS\"",
    "origin": "https://booking.vietnamairlines.com",
    "sec-fetch-site": "same-site",
    "sec-fetch-mode": "cors",
    "sec-fetch-dest": "empty",
    "referer": "https://booking.vietnamairlines.com/",
    "accept-language": "en"
}

    def start(self):
        # 准备JS代码
        self._repare_js()
        # 部分网站会获取一个token
        self.__auth_token()
        # 获取cookie和header
        return self._get_cookie()

    def _init(self):
        t1 = time.time()
        url = "https://beta.makeabooking.transavia.com/Book/Flight?culture=en-SG&type=oneway&dst1=HKG&ast1=SIN&dst2=SIN&ast2=HKG&dd=2023-11-10&rd=null&adt=1&chd=0&inf=0"
        response = self._session.get(url, headers={
            "Host": "www.transavia.com",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "upgrade-insecure-requests": "1",
            "user-agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            "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",
            "sec-fetch-site": "none",
            "sec-fetch-mode": "navigate",
            "sec-fetch-user": "?1",
            "sec-fetch-dest": "document",
            "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
        })
        self.log.log('REQU', f'initUrl: code:{response.status_code} cost:{(time.time() - t1):.3f}s')

    def _repare_js(self):
        self._session.cookies.clear()
        t1 = time.time()
        # 该地址基本不会变化
        r1 = self._session.get(
            'https://booking.vietnamairlines.com/ead-Banquo-alme-I-amaze-a-Rebele-hithing-the-his', headers = {
    "Host": "booking.vietnamairlines.com",
    "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
    "sec-ch-ua-mobile": "?0",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "sec-ch-ua-platform": "\"macOS\"",
    "accept": "*/*",
    "sec-fetch-site": "same-origin",
    "sec-fetch-mode": "no-cors",
    "sec-fetch-dest": "script",
    "referer": "https://booking.vietnamairlines.com/booking?lang=en-GB",
    "accept-language": "en"
})
        self.log.log('REQU', f'jsURL: {r1.url}')
        self.log.log('REQU', f'JSURL: code:{r1.status_code} cost:{(time.time() - t1):.3f}s')
        cache_md5 = md5(r1.text)
        if self._cache_md5 != cache_md5:
            self._cache_md5 = cache_md5
            self.log.log('VMJS', f'JS变化')
            envCode = open(work_dir + 'src/run.js', 'r').read()
            with open(work_dir + f'src/vm_env_{self.thread_name}.js', 'w') as f:
                f.write(envCode + r1.text)

        a, filename = tempfile.mkstemp()
        t2 = time.time()
        p = subprocess.Popen(['node', f'{work_dir}src/vm_env_{self.thread_name}.js', filename], stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        output, err = p.communicate(timeout=10)
        if p.returncode == 0:
            datas = output.decode().split('\n')
        else:
            raise Exception("执行 JS 超时")
        self.log.log('VMJS', f'执行JS:  cost:{(time.time() - t2):.3f}s')
        data = json.loads(open(filename, 'r').read())

        # print(len(data['solution']['interrogation']['p']))
        t3 = time.time()
        # 这个地址就是上面的地址加?d=当前网站的域名
        url = "https://booking.vietnamairlines.com/ead-Banquo-alme-I-amaze-a-Rebele-hithing-the-his?d=booking.vietnamairlines.com"
        response = self._session.post(url, headers = {
    "Host": "booking.vietnamairlines.com",
    "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
    "accept": "application/json; charset=utf-8",
    "content-type": "text/plain; charset=utf-8",
    "sec-ch-ua-mobile": "?0",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "sec-ch-ua-platform": "\"macOS\"",
    "origin": "https://booking.vietnamairlines.com",
    "sec-fetch-site": "same-origin",
    "sec-fetch-mode": "cors",
    "sec-fetch-dest": "empty",
    "referer": "https://booking.vietnamairlines.com/booking?lang=en-GB",
    "accept-language": "en"
}, json=data)
        self.log.log('REQU', f'JSURL: code:{response.status_code} cost:{(time.time() - t3):.3f}s')
        # self.log.info(f'{response.json().keys()}')
        self.log.info(response.text)
        assert response.json().get('return', False) != True, BaseException("js提交出错")
        # 返回的值 需要看网站具体分析 怎么用 有的在cookie 有的在请求头
        self._session.cookies.update({
            'reese84': response.json()['token']
        })
        self.reese84 = response.json()['token']

    def __auth_token(self):
        t1 = time.time()

        headers = {
            "Host": "api-des.vietnamairlines.com",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "accept": "application/json",
            "content-type": "application/x-www-form-urlencoded",
            "x-d-token": self.reese84,
            "sec-ch-ua-mobile": "?0",
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "sec-ch-ua-platform": "\"macOS\"",
            "origin": "https://booking.vietnamairlines.com",
            "sec-fetch-site": "same-site",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "referer": "https://booking.vietnamairlines.com/",
            "accept-language": "en"
        }
        url = "https://api-des.vietnamairlines.com/v1/security/oauth2/token/initialization"
        data = {
            "client_id": "7yA9XUB34tvB8vahz5O3CFVdGmdKT9au",
            "client_secret": "vlaA0atz4fjdyEQZ",
            "fact": "{\"keyValuePairs\":[{\"key\":\"originLocationCode1\",\"value\":\"SGN\"},{\"key\":\"destinationLocationCode1\",\"value\":\"PEK\"},{\"key\":\"departureDateTime1\",\"value\":\"2024-10-18\"},{\"key\":\"countryCode\",\"value\":\"VN\"},{\"key\":\"language\",\"value\":\"en-GB\"}]}",
            "grant_type": "client_credentials"
        }
        response = self._session.post(url, headers=headers, data=data)
        print(response.text)
        self._token = response.json()['access_token']
        self.log.log('REQU', f'__auth_token: code:{response.status_code} cost:{(time.time() - t1):.3f}s')
        self.add_header.update({
            "x-d-token": self.reese84,
            "authorization": "Bearer " + self._token,
        })

    def __get_session_token(self):
        t1 = time.time()
        headers = {
            "Host": "apigw.volaris.com",
            "Pragma": "no-cache",
            "Cache-Control": "no-cache",
            "sec-ch-ua": "\"Not/A)Brand\";v=\"120\", \"Google Chrome\";v=\"120\", \"Chromium\";v=\"120\"",
            "Accept": "application/json",
            "cookies": f"Bearer {self._token}",
            "Content-Type": "application/json",
            "sec-ch-ua-mobile": "?0",
            "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            "sec-ch-ua-platform": "\"macOS\"",
            "Origin": "https://www.transavia.com",
            "Sec-Fetch-Site": "same-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://www.transavia.com/",
            "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
        }
        url = "https://apigw.volaris.com/prod/api/session"
        response = self._session.get(url, headers=headers)
        self.token = response.json()['token']


    def _get_cookie(self):
        # r = requests.post('http://aws-lcc.unififi.com/akamai/gen', json={
        #     'type': "VA",
        #     # 'proxy': 'http://uni00002_custom_zone_US2_sid_85468327_time_5:FdkiGHty9a@us.ipwo.net:7878'
        #     # 'proxy': 'http://user-uni001-region-us-sessid-ussjSyPZaN-sesstime-1-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
        #     'proxy': self.proxy,
        # }, timeout=600)
        # print(r.text)
        # self._session.cookies.update(r.json()['cookies'])
        return self.add_header, self._session.cookies.items()

    def _test(self):

        # cookies = 'reese84=3:vs8ZjVWcIGtZD+9TCYb/Jw==:VHifzfotr0r4up0ZQHwSUsyhP4c3bYxNuv9n3fYs89svfdYVECecv39p62Zx0EUGElva6XDuaO91rfWTaMGCBHm0hWrzvQaId7f4WuI0as2N3yWBSerOWYFd74tFsfmDsqxuQdqid8/TZPZyAWbIV4ycr6Up91xLv7nLaPq74ZY1VD3jbrni/1FSgUXZXsfQb7BW3C6L73n9Gdmx06Wz20XkFG1fnUkiZ//RjUScrqKmMfwCGYPi2NVR60FNjQjU2lblF+1ouMAv0HH4yIK5tv2s0pLKn1z1bZXGlLgBE5CXsfr17ETlwST2CalisPaAwkwAdjRt4Jl7OvLQvrQq1BxZwveFoeDa+q3jeXGNX+30VWj2ubIysXi0BTZBC+fGXkqJP8lnUzNCWyFgHJ8uwc/OJ7bnoLaM5bqFm/Wy0Lxvb/MSB+DIgtq43jOsXTB4h2vOktnLGIbYw2JJQH1YV3FyqQgNEoct5G06k06d48lmtIIn2JXd8dPVVFVDWdt7Qu9eaa5gLvb87lPi9tKZJA==:9i7IbJFkyOdDql3PuwWdvgrgE1ZO2fZ1/RKie/RueBA=; incap_ses_1615_2445686=/DplEuQQm0UZ/FEnGaJpFjHu5GYAAAAATi2u+f4pUAV4EqqHup4RsA==; nlbi_2445686_2147483392=nmliURrJJgFi0GjfUVmepAAAAACh8NYnbZZ2n0a+ydgU9T8F; visid_incap_2445686=DbGuraaUQiyBCC2iLsFjijHu5GYAAAAAQUIPAAAAAAACVN9OkCRl8kxkppg5/30B'
        # cks = {}
        # for i in cookies.split('; '):
        #     t = i.index('=')
        #     cks[i[:t]] = i[t+1:]
        # self._session.cookies.update(cks)
        url = "https://api-des.vietnamairlines.com/v2/search/air-bounds"
        data = {"commercialFareFamilies":["WEB"],"itineraries":[{"departureDateTime":"2024-10-19T00:00:00.000","originLocationCode":"PEK","destinationLocationCode":"HAN","isRequestedBound":True}],"travelers":[{"passengerTypeCode":"ADT"}],"searchPreferences":{"showMilesPrice":False}}
        response = self._session.post(url, headers=self.add_header, json=data)
        # _token = re.findall('ionToken" type="hidden" value="(.+?)"', response.text)[0]
        print(response.text)



if __name__ == '__main__':
    # session.proxies = {
    #     'http': "http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000",
    #     'https': "http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000",
    # }
    r = Reese84ByPass('https://www.transavia.com/',
                      'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000')
    # r = Reese84ByPass('https://www.transavia.com/', 'http://user-uni007-region-us:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600')
    r = Reese84ByPass('https://booking.vietnamairlines.com/', 'http://127.0.0.1:8890')
    # r = Reese84ByPass('https://www.transavia.com/', f'http://uni00001_custom_zone_US_sid_{random.randint(67336718, 67336728)}_time_5:q39CEBTs5A@us.foxyip.com:7778')
    # while True:
    # 刷值主要逻辑
    r.start()
    # 测试几次 看看值能不能用
    for i in range(10):
        r._test()
        input('....')
