import hashlib
import json
import platform
import random
import subprocess
import tempfile
import time
from pathlib import Path
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-y4/'
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='test'):
        # 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 = ''

    def start(self):
        # self._init()
        self._repare_js()
        # self.__auth_token()
        # self._test()
        # time.sleep(random.randint(3,5))
        # self.__get_session_token()

        return self._get_cookie()

    def _init(self):
        t1 = time.time()
        url = "https://beta.makeabooking.flyscoot.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": "book.philippineairlines.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://book.philippineairlines.com/aze-vertaine-Bird-wroue-that-Macbeth-of-Naugures')
        self.log.log('REQU', f'jsURL: {"https://book.philippineairlines.com/aze-vertaine-Bird-wroue-that-Macbeth-of-Naugures"}')
        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()
        url = "https://book.philippineairlines.com/aze-vertaine-Bird-wroue-that-Macbeth-of-Naugures?d=book.philippineairlines.com"
        response = self._session.post(url, headers={
            "Host": "book.philippineairlines.com",
            "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
            "Accept": "application/json; charset=utf-8",
            "sec-ch-ua-platform": "\"macOS\"",
            "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",
            "Origin": "https://book.philippineairlines.com",
            "Sec-Fetch-Site": "same-origin",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://book.philippineairlines.com/en/",
            "Accept-Language": "en-US,en;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']
        })

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

        headers = {
            "Host": "ibe.api.flyscoot.com",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
            "sec-ch-ua-mobile": "?0",
            "x-scoot-client-session": "6a8f7c3d-9735-4254-a37c-dc79a87feead",
            "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.flyscoot.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://ibe.api.flyscoot.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=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
            "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://book.philippineairlines.com",
            "Sec-Fetch-Site": "same-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://book.philippineairlines.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):
        # headers = {
        #     "authority": "ibe.api.flyscoot.com",
        #     "accept": "application/json, text/plain, */*",
        #     "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
        #     # "authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0MzJhM2RmNi1iZmRmLTQ5NmMtOTJiMS1iN2EwMzBlNGJmNTgiLCJpYXQiOjE2OTc2ODE0MjEsInRrbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUp6ZFdJaU9pSlZibXR1YjNkdUlpd2lhblJwSWpvaU5Ea3hOVFV4TldJdE5UY3dOaTA1WVRBNExXVXdNbVF0TlRrek1tVXdOakZoTXpOa0lpd2lhWE56SWpvaVpHOTBVa1ZhSUVGUVNTSjkuMFA1T0xkSzF2V0p4VlFMblI2SHRaT2YtcExQZTNPT0pEdmR5aVVacW9zbyIsImlzcyI6InNjb290LWNtdyIsImF1ZCI6InNjb290LWFwcCJ9.byiajmbVNj87-eVT64Dfr-u-30YxdqGEHyPqDI07qsM",
        #     # "authorization": self._token,
        #     "cache-control": "no-cache",
        #     "content-type": "application/json",
        #     "origin": "https://beta.makeabooking.flyscoot.com",
        #     "pragma": "no-cache",
        #     "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
        #     "sec-ch-ua-mobile": "?0",
        #     "sec-ch-ua-platform": "\"macOS\"",
        #     "sec-fetch-dest": "empty",
        #     "sec-fetch-mode": "cors",
        #     "sec-fetch-site": "same-site",
        #     "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",
        #     "x-scoot-client-environment": "PROD",
        #     "x-scoot-client-session": "4ddf4d27-d6a1-4b50-b533-04558f7ab4b8",
        #     "x-scoot-client-version": "0.0.0"
        # }
        headers = {
            "Host": "book.philippineairlines.com",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "sec-ch-ua-platform": "\"macOS\"",
            "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": "*/*",
            "origin": "https://book.philippineairlines.com",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "accept-language": "en"
        }
        return headers, self._session.cookies.items()

    def _test(self):
        headers = {
            "Host": "book.philippineairlines.com",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "sec-ch-ua-platform": "\"macOS\"",
            "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": "*/*",
            "origin": "https://book.philippineairlines.com",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "accept-language": "en"
        }
        url = "https://book.philippineairlines.com/plnext/paldx/FlexPricerAvailabilityDispatcherPui.action;jsessionid=WNYqpe3FIlYkthwdRJU79KStnPJrMSNvWPAjiK9R!1706082022256"
        data = {
            "COUNTRY_SITE": "GB",
            "DATE_RANGE_QUALIFIER_2": "C",
            "BOOKING_FLOW": "REVENUE",
            "X-Accept-Charset": "iso-8859-1",
            "INITIAL_TRIP_TYPE": "R",
            "DATE_RANGE_QUALIFIER_1": "C",
            "PAGE_TICKET": "0",
            "B_ANY_TIME_1": "TRUE",
            "B_ANY_TIME_2": "TRUE",
            "TRIP_FLOW": "YES",
            "EXTERNAL_ID": "BOOKING",
            "context": "true",
            "DISPLAY_TYPE": "2",
            "LANGUAGE": "GB",
            "ARRANGE_BY": "R",
            "COMMERCIAL_FARE_FAMILY_1": "PRECO",
            "SITE": "O01DO01D",
            "COMMERCIAL_FARE_FAMILY_2": "PRECO",
            "isOverrideAction": "false",
            "CONFIG_CUSTOM_PHTAX_ACTIVATED": "true",
            "PAGE_ID": "FDCT",
            "PLTG_IS_UPSELL": "true",
            "E_LOCATION_1": "AOR",
            "E_LOCATION_2": "LAX",
            "_t": "1706082524",
            "TRIP_TYPE": "R",
            "SKNEEDED": "NO",
            "PRICING_TYPE": "O",
            "OFFICE_ID": "MNLPR08WB",
            "HAS_INFANT_1": "FALSE",
            "FORCE_CALENDAR": "FALSE",
            "DATE_RANGE_VALUE_1": "3",
            "ENCT": "1",
            "DIGITAL_DATA": "{\"event\":[{\"eventInfo\":{\"key\":\"PageView\",\"eventName\":\"PageView\",\"pageID\":\"FDCT\",\"componentID\":\"\",\"timestamp\":\"2024-01-24T07:40:38.339Z\"},\"category\":{\"primaryCategory\":\"PageView\"}},{\"eventInfo\":{\"key\":\"PageLoad\",\"eventName\":\"PageLoad\",\"pageID\":\"FDCT\",\"componentID\":\"\",\"timestamp\":\"2024-01-24T07:40:38.340Z\"},\"category\":{\"primaryCategory\":\"Display\"}},{\"eventInfo\":{\"key\":\"ErrorRaised\",\"eventName\":\"Error\",\"pageID\":\"FDCT\",\"componentID\":\"\",\"timestamp\":\"2024-01-24T07:40:38.342Z\"},\"category\":{\"primaryCategory\":\"Error\"}},{\"eventInfo\":{\"key\":\"ErrorRaised\",\"eventName\":\"Error\",\"pageID\":\"FDCT\",\"componentID\":\"\",\"timestamp\":\"2024-01-24T07:40:38.343Z\"},\"category\":{\"primaryCategory\":\"Error\"}},{\"eventInfo\":{\"key\":\"ClickDay\",\"eventName\":\"SelectFlight\",\"pageID\":\"FDCT\",\"componentID\":\"Page\",\"timestamp\":\"2024-01-24T07:48:39.874Z\"},\"category\":{\"primaryCategory\":\"UserEvent\"}}],\"service\":{\"serviceInfo\":{\"sessionIDServer\":\"xC1caA1wLb5Vf7Oc4ueqf8hkfquvwXbyIdRoVbNx\"}},\"version\":\"2.2.0\",\"pageInstanceID\":\"FDCT\"}",
            "DATE_RANGE_VALUE_2": "3",
            "B_DATE_2": "202402020000",
            "B_LOCATION_2": "AOR",
            "TRAVELLER_TYPE_1": "ADT",
            "B_DATE_1": "202401270141",
            "B_LOCATION_1": "LAX",
            "DATA_TYPE": "json"
        }

        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://book.philippineairlines.com/', 'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000')
    # r = Reese84ByPass('https://book.philippineairlines.com/', 'http://user-uni007-region-us:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600')
    r = Reese84ByPass('https://book.philippineairlines.com/plnext/paldx/Override.action;jsessionid=n6YrVmbx3EwcM5Jie7XnAz-esoQV25sPoRjirj-Z!1706081876056?BOOKING_FLOW=REVENUE&COUNTRY_SITE=GB&EMBEDDED_TRANSACTION=FlexPricerAvailability&ENC=0FBFA38B296A737C8F0EADFF17E094BD6790BAA37DE41FDC0EC4BC81AA6746E4E4D14DB117CBA73BA1879DB46C0BBB110992DA9F4BBB5C8904F10B533C05A2369471290FA22873719B4ED9EEDD95049F7F8FBE19EF98D3650173B96A6663DECC2B9A3AC903FD90794EC0D102A98AF88339038713DD29BA92CA5A5B0035E5399CE75A635754AC9FDEF661AEDFD86B80C092419E615043FC129FF0116B21059CA29C3515377F6303DD23B329E1DE6AAA85922B27DD33D7C3A8CCF9210CF43E830D2A9514607FD86680FAA4D40D05EFE2FA9168F57D0EF5F64DD3E8ECA949B4AF13687D92951BF231AC137B746E3C4D9F740A3B02283E97F9E5005750C38262AD9EFF4F1EC159089125D70038BD8264E730AC8A14A102C06A2EE2C71649502667B42F75BA8CBBA9C0D417725D3A9ED2498AE9645F757A10C1692696E724DA6D9BD194EA6544169AC5B1C6F483A44809904359241755918E74F56AB0F289A94E7161AF10B16EDCBAC8914DC9C1D71EE0AFDDE277126C0E9AA01E2473409664231161303303F0DC3819B87B646240CEB3596FEF02D0DF7EAD50EBD8425C256867167BB00FE5EBAB71D1426693CC133BA723587E415CAE7262B10A50B6037A8FACF7E630C3E02EFA59D0A0F4AEFC3191250209223DD2A6240B9A55D4EC22182F348CA4D4A1F26CF23E1E09DB1F0B7D2D42D84E9F73DAE511D01514E3EF0B78E685423CE3C22CD1B3BB26D569120CB897D28A26FD233466D0308DD6A024FF4573AEF705DB97E343D89E730764CFB5A8A79418DD25F599861A96F67B785B8C7E3F76AD92B2CA6766ABB34FC30A787614118F25638FA4ACADC164E0F7E033C568F03A9961A5B41CAD6A33961EB3EA3F7B052B8D87AE0C20E23794384B6B7807A50CB9C675803121D5B20CF41E1DF0984B65EB667F612063981AFF06BD32DFCEA9E9B627E0E162957981E51B008069C135D12E8BAA43993483854E459DAE6744B8E1DCB8950E905A51376D178EE7D96D326FDAD3498D1EEEA96316B334948FE5BA1497FE151E25AF950D9BFA01746559166620701409C3586D55968B48CD863F15899D49E6ED4B4EBA119D9D8CEAE7BF9F70F5234327390E7D1AA8660D907F7E5EFD46618AEC39BA6BA4B4E6BDA86546285EB51B65077F2F81F82C18480F6B515252E5ED78BC250E3B6EE7640AE8342A3566E550825407E2CE8E77D3284B42F732ACC56C9428C1E36B86C3E5F268D798E08E3C981C05793FFABABB7210D7ECEFB799BD8146CFD41087FB75D010155CFFF92984609C665DF06989433A3BC7B4C1D396CA99A565F48070C106F33999A505BB6A0A6AF0B57F01F8E5210BF9B275B052821144B8&ENCT=1&EXTERNAL_ID=BOOKING&LANGUAGE=GB&OFFICE_ID=SFOPR08WB&PAGE_ID=FDCT&SITE=O01DO01D&TRIP_FLOW=YES&_t=1706081887', 'http://127.0.0.1:8890')
    # r = Reese84ByPass('https://book.philippineairlines.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()
