import json
import platform
import random
import subprocess
import time
from pathlib import Path
import tempfile
import tls_client
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 = Path().cwd()
# print(work_dir)
log_dir = '/data/log/lcc-y4/'
if platform.platform().startswith('mac'):
    # work_dir = '/Users/wang/Documents/company/lcc-reese84/'
    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)

class Reese84ByPass(object):
    _session = tls_client.Session('chrome_112')

    def __init__(self, target, proxy, thread_name='test'):
        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.log.info(f'proxy:{proxy} target:{target}')

    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-10-28&rd=null&adt=1&chd=0&inf=0"
        response = self._session.get(url, headers={
            "Host": "www.flyscoot.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/115.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):
        t1 = time.time()
        r1 = self._session.get('https://beta.makeabooking.flyscoot.com/Two-discharted-Not-ere-int-when-is-are-Poss-A-Sa')
        self.log.log('REQU', f'JSURL: code:{r1.status_code} cost:{(time.time() - t1):.3f}s')
        a, filename = tempfile.mkstemp()
        envCode = open(work_dir / 'run.js', 'r').read()
        with open(work_dir / 'vm_env.js', 'w') as f:
            f.write(envCode + r1.text)
        t2 = time.time()
        # print(f'{work_dir}/vm_env.js')
        p = subprocess.Popen(['node', f'{work_dir}/vm_env.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 超时")
        print(filename)
        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://beta.makeabooking.flyscoot.com/Two-discharted-Not-ere-int-when-is-are-Poss-A-Sa?d=beta.makeabooking.flyscoot.com"
        response = self._session.post(url, headers={
            "Host": "www.flyscoot.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; 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/115.0.0.0 Safari/537.36",
            "sec-ch-ua-platform": "\"macOS\"",
            "origin": "https://www.flyscoot.com",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "referer": "https://www.flyscoot.com/flight",
            "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()}')
        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 = {
            "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": "",
            "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/115.0.0.0 Safari/537.36",
        }
        url = "https://ibe.api.flyscoot.com/v1/account/anonymous"
        response = self._session.get(url, headers=headers)

        print(response.text)
        print(response)
        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/115.0.0.0 Safari/537.36",
            "sec-ch-ua-platform": "\"macOS\"",
            "Origin": "https://www.flyscoot.com",
            "Sec-Fetch-Site": "same-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://www.flyscoot.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 {
            "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",
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
        }, self._session.cookies.get_dict()

    def _test(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/115.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"
        }
        url = "https://ibe.api.flyscoot.com/v1/booking/flight/availability"
        data = {
            "flightCriteria": [
                {
                    "origin": "HKG",
                    "destination": "SIN",
                    "departureDate": "2023-10-28"
                }
            ],
            "passengerCriteria": {
                "adult": 1,
                "child": 0,
                "infant": 0
            },
            "currencyCode": "HKD",
            "promoCode": None,
            "salesCode": None,
            "flightFare": {
                "fareType": [],
                "classOfService": []
            },
            "cultureCode": "en-SG"
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self._session.post(url, headers=headers, data=data)

        print(response.text)
        print(response)


if __name__ == '__main__':
    # r = Reese84ByPass('https://www.flyscoot.com/', 'http://user-uni002-region-de:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600')
    r = Reese84ByPass('https://www.flyscoot.com/', 'http://127.0.0.1:7890')
    print(r.start())
