import json
import random
import time
from urllib import parse

import requests

from tools.utils import get_token


def buy_poc(account, passwd, target_url='https://t.livepocket.jp/e/4gbm0'):
    """
    模拟登录
    """
    # 定义请求地址
    login_url = "https://t.livepocket.jp/api/sessions/create?mytimestamp=" + str(int(time.time()))

    # 定义请求header
    headers = {'Content-Type': 'application/x-www-form-urlencoded;',
               'Referer': 'https://t.livepocket.jp/login?acroot=header-new_p_u_nl',
               'Sec-Ch-Ua': 'Chromium',
               'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
               }

    # 通过字典方式定义请求body
    form_data = {"login": account,
                 "password": passwd,
                 "auto_login": "on",
                 "login_password": f"{account}&{passwd}"
                 }

    data = parse.urlencode(form_data)

    # 代理IP池
    proxy_list = [
        '185.199.228.220:7300',
    ]

    # 随机从ip池中选出一个ip
    proxy = random.choice(proxy_list)
    proxies = {
        'http': 'http://' + proxy,
        'https': 'https://' + proxy,
    }

    session = requests.session()
    content = session.post(url=login_url, headers=headers, data=data, proxies=None).text
    cookie = session.cookies
    response_cookie = cookie.get_dict()
    login_resp = json.loads(content)
    print(f"token: {login_resp['result']['token']}, response_cookie:{response_cookie}")
    # print(login_resp)
    token = login_resp['result']['token']
    reserved_session_id = random.randint(100000, 600000)
    ci_session = json.dumps(session.cookies.get_dict())

    # 跳转到抢券
    event_id = 0
    response = requests.get(target_url)
    if response.status_code == 200:
        html_string = response.content.decode('utf8')
        start_index = html_string.find('https://t.livepocket.jp/purchase/verify?event_id=')
        if start_index != -1:
            end_index = html_string.find("'", start_index)
            if end_index != -1:
                event_id = html_string[start_index + len('https://t.livepocket.jp/purchase/verify?event_id='):end_index]
                print(f'event_id: {event_id}')
            else:
                print('End index not found.')
        else:
            print('Substring not found.')
    else:
        print('Failed to fetch the page. Status code:', response.status_code)

    url = 'https://t.livepocket.jp/api/tickets/purchase?mytimestamp=' + str(int(time.time()))
    # reserved_session_id = 125846

    one_token = get_token()
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'sec-ch-ua-mobile': '?0',
        'DNT': '1',
        'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
        'Host': 't.livepocket.jp',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua-platform': '"macOS"',
        'Origin': 'https://t.livepocket.jp',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': f'https://t.livepocket.jp/purchase/confirm?id={event_id}&reserved_session_id={reserved_session_id}&otoken={one_token}',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie': f'ci_session={ci_session}'
    }

    form_data = {
        'utoken': f'{token}',
        'onetime_token_name': 'buy_ticket',
        'onetime_token_value': one_token,
        'url': f'https://t.livepocket.jp/purchase/confirm?id={event_id}&reserved_session_id={reserved_session_id}',
        'reserve_session_id': f'{reserved_session_id}',
        'payment_method': '0',
        'event_id': f'{event_id}',
        'serial_codes': 'null',
        'fan_club': 'null',
        'payment_type': 'credit'
    }

    cookies = {'ci_session': f'{ci_session}'}

    response = requests.post(url, headers=headers, cookies=cookies, data=form_data)
    print(json.loads(response.text))


if __name__ == '__main__':
    buy_poc("nvlu8@huatcn.com", "panyue666", 'https://t.livepocket.jp/e/glimas0504')
