import random
import time

from curl_cffi import requests

from models.weex import Weex1

headers = {
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9,zh-HK;q=0.8,en;q=0.7',
    'appversion': '2.0.0',
    'bundleid': '',
    'cache-control': 'no-cache',
    'language': 'zh_CN',
    'origin': 'https://www.weex.com',
    'pragma': 'no-cache',
    'priority': 'u=1, i',
    'referer': 'https://www.weex.com/',
    'sec-ch-ua': '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'cross-site',
    'sidecar': '0115665ae5d5a18da1543cd0deabd52588c09f4d3b028876659f0801ca7af5a3ba',
    'terminalcode': '55a01525ddf9e8f4bb158345db69b510',
    'terminaltype': '1',
    'traceid': 'mgotla61s5segrwkkw',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'vs': 'Z567O6188nsWfe9Njo9N7KsAbL0RO6ho',
    'x-sig': 'bb0f194c38f69c38ffbcb361c27c7295',
    'x-timestamp': '1760341017529',
}

klineId = None
klineTime = None
contractId = None

while True:

    for i in range(500):
        print(i)
        params = {
            'languageType': '1',
            'sign': 'SIGN',
            'timeZone': 'string',
            'contractId': '10000002',
            'productCode': 'ethusdt',
            'priceType': 'LAST_PRICE',
            'klineType': 'MINUTE_1',
            'limit': '200',
        }

        if klineId:
            params['nextKey.klineId'] = klineId
            params['nextKey.contractId'] = contractId

        if klineTime:
            params['nextKey.klineTime'] = klineTime

        response = requests.get('https://http-gateway1.janapw.com/api/v1/public/quote/v1/getKlineV2', params=params,
                                headers=headers)

        klineId = response.json()["data"]["nextKey"]["klineId"]
        klineTime = response.json()["data"]["nextKey"]["klineTime"]
        contractId = response.json()["data"]["nextKey"]["contractId"]

        for data in response.json()["data"]["dataList"]:
            # print(data)

            Weex1.get_or_create(
                id=int(data[4]),
                defaults={
                    'open': float(data[3]),
                    'high': float(data[1]),
                    'low': float(data[2]),
                    'close': float(data[0]),
                }
            )

        time.sleep(random.randint(1, 50))

    # time.sleep(3600)
