import json
import os
import time
import uuid
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
import tls_client
import logging
import traceback
from threading import Thread
import requests
from reese84_bypass import Reese84ByPass
import pathlib


root_logger = logging.getLogger()

root_logger.setLevel(logging.WARNING)
root_logger.handlers = []
if not pathlib.Path('nacos-data/snapshot/').exists():
    pathlib.Path('nacos-data/snapshot/').mkdir(parents=True)


def check_pull():
    get_url = 'http://ymx-lcc.unififi.com/header/task/pull/cookieY4?brush_name=test'
    r = requests.get(get_url)
    return r.json()
def get_proxy():
    get_proxy_url = 'http://ymx-lcc.unififi.com/proxy/get-proxy'
    r = requests.post(get_proxy_url, json={
        'name': 'Y4',
        'type':'shopping'
    })
    return r.json()

def add_header(headers:dict, cookies: dict, px: str, thread_id=0):
    cks = []
    for k, v in cookies.items():
        cks.append(f'{k}={v}')
    headers['cookie'] = '; '.join(cks)
    data = {
        "brush_fromdate": "2023-06-19",
        "brush_fromto": "BOS-JFK",
        "brush_header": headers,
        "brush_name": f"rever_{thread_id}",
        "brush_proxy": px,
        "brush_type": "cookieY4"
    }
    r = requests.post("http://ymx-lcc.unififi.com/header/add", json=data)
    print(r.json())
def exec(thread_id):
    id_ = uuid.uuid4().hex
    try:
        px = get_proxy()['url']
        cf = Reese84ByPass(target="https://www.volaris.com/", proxy=px, thread_name=f'{thread_id}')
        headers, cookies = cf.start()
        # cf.test()
        add_header(headers, cookies, px, thread_id)
    # except json.decoder.JSONDecodeError:
    #     print('json huoqu shibai ')
    except Exception as e:
        print(e)
        traceback.print_exc()

def run():
    brush_thread = 1
    while True:

        print(f'本次并发数 {brush_thread}')
        pull = check_pull()
        try:
            if pull.get('status') == 1:
                time.sleep(10)
                continue
        except:
            pass
        # pool = ThreadPoolExecutor(max_workers=brush_thread)
        # all_task = [pool.submit(exec, (i)) for i in range(brush_group)]
        # brush_check = CONFIG['internal']['reverse']['making']['brush_check']
        # wait(all_task, return_when=ALL_COMPLETED)
        # print(f'休息 {brush_check} 秒')
        # time.sleep(brush_check)

        with ThreadPoolExecutor(max_workers=brush_thread) as executor:
            objs = []
            for t in range(1, brush_thread + 1):
                task = executor.submit(exec, t)
                objs.append(task)
            while 1:
                time.sleep(1)
                for n, o in enumerate(objs):
                    if o.done():
                        task = executor.submit(exec, n + 1)
                        objs[n] = task



if __name__ == '__main__':

    run()









