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/Documents/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_117')

        # self._session = requests.Session()
        self._session.verify = False
        self.__target = target
        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 = {
            "authority": "www.transavia.com",
            "accept": "*/*",
            "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "origin": "https://www.transavia.com",
            "pragma": "no-cache",
            "referer": "https://www.transavia.com/en-UK/book-a-flight/flights/search/",
            "request-context": "appId=cid-v1:942f733a-0e08-45b5-a6e2-53089f65a4b2",
            "request-id": "|3651048e1bbe4dc38890f5cba115b92f.11b030bc635d49f3",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "traceparent": "00-3651048e1bbe4dc38890f5cba115b92f-11b030bc635d49f3-01",
            "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",
            "x-requested-with": "XMLHttpRequest"
        }

    def start(self):
        self._init()
        self._repare_js()
        # self.__auth_token()
        # self._token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzZTc4NDE1Zi03OTc2LTRjNDctYmQwNC0xM2FlMGJhOTRkMTQiLCJpYXQiOjE3MTUyNDEzMzMsInRrbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUp6ZFdJaU9pSlZibXR1YjNkdUlpd2lhblJwSWpvaU1UTmtZek16WXpJdE5HVTJaUzAxWXpJMExUbGhPR010WWpBME9UTTJOV0V5T1RjM0lpd2lhWE56SWpvaVpHOTBVa1ZhSUVGUVNTSjkuRVUtQ1l3eVJmZUVaNDZvLUVHM2pUejNjRkMwYkFXNW1tX2VhZ05CMXE3RSIsImlzcyI6InNjb290LWNtdyIsImF1ZCI6InNjb290LWFwcCJ9.7WSVavUdvOUl4tjv9hpL4jeQTCnYh4bOUg669YERe-s'
        # self._test()
        # time.sleep(random.randint(3,5))
        # self.__get_session_token()

        return self._get_cookie()

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

        headers = {
            "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",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "upgrade-insecure-requests": "1",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "navigate",
            "sec-fetch-user": "?1",
            "sec-fetch-dest": "document",
            "referer": "https://www.transavia.com/home/en-uk",
            "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
        }

        url = "https://www.transavia.com/home/en-uk"
        response = self._session.get(url, headers=headers)

        # print(response.text)
        # print(response)
        try:
            self._js_url = re.findall('scriptElement.src = "(.+?)"', response.text)[0]
        except:
            pass
        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()
        self._js_url = '/rgeonseart-Cawdor-mine-no-our-selfe-Wife-comfort'
        r1 = self._session.get(
            'https://www.transavia.com'+self._js_url, headers={
                "authority": "www.transavia.com",
                "accept": "*/*",
                "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
                "cache-control": "no-cache",
                "pragma": "no-cache",
                "referer": "https://www.transavia.com/",
                "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"macOS\"",
                "sec-fetch-dest": "script",
                "sec-fetch-mode": "no-cors",
                "sec-fetch-site": "same-origin",
                "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"
            })
        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, self._js_url.split('?')[0]], 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()
        url = 'https://www.transavia.com'+self._js_url.split('?')[0] + "?d=www.transavia.comt"
        response = self._session.post(url, headers = {
    "Host": "www.transavia.com",
    "pragma": "no-cache",
    "cache-control": "no-cache",
    "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://www.transavia.com",
    "sec-fetch-site": "same-origin",
    "sec-fetch-mode": "cors",
    "sec-fetch-dest": "empty",
    "referer": "https://www.transavia.com/home/en-uk",
    "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
}, 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提交出错")

        self._session.cookies.update({
            'reese84': response.json()['token']
        })
        self._reese84 = response.json()['token']

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

        headers = {
            "Host": "ibe.api.transavia.com",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua": "\"Google Chrome\";v=\"120\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"120\"",
            "sec-ch-ua-mobile": "?0",
            "authorization": "",
            "x-scoot-client-version": "0.0.0",
            "x-scoot-client-environment": "PROD",
            "content-type": "application/json",
            "accept": "application/json, text/plain, */*",
            "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",
            "x-scoot-appsource": "IBE-WEB",
            "sec-ch-ua-platform": "\"macOS\"",
            "origin": "https://beta.makeabooking.transavia.com",
            "sec-fetch-site": "same-site",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
        }
        url = "https://booking.api.transavia.com/v1/account/anonymous"
        response = self._session.get(url, headers=headers)
        print(response.text)
        self._token = response.json()['data']['accessToken']
        self.log.log('REQU', f'__auth_token: code:{response.status_code} cost:{(time.time() - t1):.3f}s')

    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):

        return self.add_header, self._session.cookies.items()

    def _test(self):
        self._init()
        url = "https://www.transavia.com/en-UK/book-a-flight/flights/search/?r=False&ap=1&cp=0&ip=0&ds=EDI&as=ORY&od=1&om=12&oy=2024&fb=false"
        response = self._session.get(url, headers = {
    "Host": "www.transavia.com",
    "pragma": "no-cache",
    "cache-control": "no-cache",
    "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
    "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": "same-origin",
    "sec-fetch-mode": "navigate",
    "sec-fetch-user": "?1",
    "sec-fetch-dest": "document",
    "referer": "https://www.transavia.com/home/en-uk",
    "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
})
        request_token = re.findall('"__RequestVerificationToken" type="hidden" value="(.+?)"', response.text)[0]





        ## multiday

        response = self._session.post(headers = {
            "Host": "www.transavia.com",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "request-context": "appId=cid-v1:942f733a-0e08-45b5-a6e2-53089f65a4b2",
            "traceparent": "00-d6847a54450e47f9888346aad52b84dd-8d17bbd29e2d45e4-01",
            "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",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "accept": "*/*",
            "x-requested-with": "XMLHttpRequest",
            "request-id": "|d6847a54450e47f9888346aad52b84dd.8d17bbd29e2d45e4",
            "sec-ch-ua-platform": "\"macOS\"",
            "origin": "https://www.transavia.com",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "referer": "https://www.transavia.com/en-UK/book-a-flight/flights/search/",
            "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
        },
        url = "https://www.transavia.com/en-UK/book-a-flight/flights/multidayavailability/",
        data = {
            "selectPassengersCount.AdultCount": "1",
            "selectPassengersCount.ChildCount": "0",
            "selectPassengersCount.InfantCount": "0",
            "routeSelection.DepartureStation": "EDI",
            "routeSelection.ArrivalStation": "ORY",
            "dateSelection.OutboundDate.Day": "1",
            "dateSelection.OutboundDate.Month": "11",
            "dateSelection.OutboundDate.Year": "2024",
            "dateSelection.InboundDate.Day": "",
            "dateSelection.InboundDate.Month": "",
            "dateSelection.InboundDate.Year": "",
            "dateSelection.IsReturnFlight": "false",
            "flyingBlueSearch.FlyingBlueSearch": "false",
            "__RequestVerificationToken": request_token
        })

        print(response.text)


        headers = {
            "Host": "www.transavia.com",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "request-context": "appId=cid-v1:942f733a-0e08-45b5-a6e2-53089f65a4b2",
            "traceparent": "00-d6847a54450e47f9888346aad52b84dd-0a171226e9824924-01",
            "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",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "accept": "*/*",
            "x-requested-with": "XMLHttpRequest",
            "request-id": "|d6847a54450e47f9888346aad52b84dd.0a171226e9824924",
            "sec-ch-ua-platform": "\"macOS\"",
            "origin": "https://www.transavia.com",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "referer": "https://www.transavia.com/en-UK/book-a-flight/flights/search/",
            "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6"
        }
        url = "https://www.transavia.com/en-UK/book-a-flight/flights/SingleDayAvailability/"
        data = {
            "selectSingleDayAvailability.JourneyType": "OutboundFlight",
            "selectSingleDayAvailability.Date.DateToParse": "2024-11-01",
            "selectSingleDayAvailability.AutoSelect": "true",
            "__RequestVerificationToken": request_token
        }
        response = self._session.post(url, headers=headers, data=data)
        print(response.text)
        self.log.debug(f"resp {'Flight Search Results' in response.text}")
        print(self._get_cookie())


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://www.transavia.com/', 'http://127.0.0.1:7890')
    # 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()
