import json
import asyncio
import os
from curl_cffi import requests, AsyncSession, CurlError
from nonebot import logger

url_search = "https://api.tracker.gg/api/v2/bf6/standard/search?platform=origin&query={name}&autocomplete=true"
url_overview = "https://api.tracker.gg/api/v2/bf6/standard/profile/ign/{user_id}?"

filepath = os.path.dirname(__file__).replace("\\", "/")


def load_cookies_from_txt(path: str):
    cookies = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            if line.startswith("#") or not line.strip():
                continue
            parts = line.strip().split("\t")
            if len(parts) >= 7:
                cookies.append({"name": parts[5], "value": parts[6]})
    return cookies


def build_cookie_header(cookies):
    return "; ".join([f"{c['name']}={c['value']}" for c in cookies])


async def fetch_url(url: str, headers: dict):
    async with AsyncSession() as session:
        try:
            response = await session.get(url, headers=headers, impersonate="chrome110")
            return response
        except CurlError as e:
            logger.warning("cURL 错误:", e)
            return None


async def search_user(name: str):
    cookies = load_cookies_from_txt(f"{filepath}/cookies/tracker.txt")
    cookie_header = build_cookie_header(cookies)
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "user-agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/139.0.0.0 Safari/537.36"
        ),
        "cookie": cookie_header,
        "referer": "https://tracker.gg/",
    }

    search_url = url_search.format(name=name)
    response = await fetch_url(search_url, headers=headers)
    if not response:
        logger.warning("请求失败")
        return

    if response.status_code == 200:
        logger.info("搜索成功")
        json_data = response.json()
        title_id_list = []
        for res in json_data['data']:
            title_id_list.append(res['titleUserId'])
        for title_id in title_id_list:
            flag, info = await get_data(title_id)
            if flag:
                return info
            else:
                continue
    else:
        logger.warning(f"请求失败，状态码: {response.status_code}")
        logger.warning(response.text)


async def get_data(user_id: str):
    cookies = load_cookies_from_txt(f"{filepath}/cookies/tracker.txt")
    cookie_header = build_cookie_header(cookies)
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "user-agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/139.0.0.0 Safari/537.36"
        ),
        "cookie": cookie_header,
        "referer": "https://tracker.gg/",
    }

    get_url = url_overview.format(user_id=user_id)
    response = await fetch_url(get_url, headers=headers)
    if not response:
        logger.warning("获取失败")
        return False

    if response.status_code == 200:
        logger.info("获取成功")
        platform_info = response.json()['data']['platformInfo']
        segments = response.json()['data']['segments']

        overview = ""
        weapons = []
        vehicles = []
        gamemodes = []
        gadgets = []
        kits = []
        maps = []

        for segment in segments:
            if segment['type'] == 'overview':
                overview = segment
            elif segment['type'] == 'weapon':
                weapons.append(segment)
            elif segment['type'] == 'vehicle':
                vehicles.append(segment)
            elif segment['type'] == 'gamemode':
                gamemodes.append(segment)
            elif segment['type'] == 'gadget':
                gadgets.append(segment)
            elif segment['type'] == 'kit':
                kits.append(segment)
            elif segment['type'] == 'level':
                maps.append(segment)

        top_kill_weapon = sorted(weapons, key=lambda k: k['stats']['kills']['value'], reverse=True)[0]
        best_weapon = {
            "名称": top_kill_weapon['metadata']['name'],
            "击杀": top_kill_weapon['stats']['kills']['value'],
            "KPM": top_kill_weapon['stats']['killsPerMinute']['value'],
            "时长": top_kill_weapon['stats']['timePlayed']['displayValue'],
            "爆头率": top_kill_weapon['stats']['headshotPercentage']['displayValue'],
            "命中率": top_kill_weapon['stats']['shotsAccuracy']['displayValue']
        }
        top_kill_vehicle = sorted(vehicles, key=lambda k: k['stats']['kills']['value'], reverse=True)[0]
        best_vehicle = {
            "名称": top_kill_vehicle['metadata']['name'],
            "击杀": top_kill_vehicle['stats']['kills']['value'],
            "KPM": top_kill_vehicle['stats']['killsPerMinute']['value'],
            "时长": top_kill_vehicle['stats']['timePlayed']['displayValue'],
            "碾压": top_kill_vehicle['stats']['roadKills']['value'],

        }

        player_info = {
            '玩家': platform_info['platformUserHandle'],
            '平台': platform_info['platformSlug'],
            '等级': overview['stats']['careerPlayerRank']['displayValue'],
            '时长': overview['stats']['timePlayed']['displayValue'],
            '场次': overview['stats']['matchesPlayed']['displayValue'],
            '胜率': overview['stats']['wlPercentage']['displayValue'],
            '总得分': overview['stats']['score']['displayValue'],
            'K/D': overview['stats']['kdRatio']['value'],
            'KPM': overview['stats']['killsPerMinute']['value'],
            'SPM': overview['stats']['scorePerMinute']['value'],
            '击杀': overview['stats']['kills']['displayValue'],
            '助攻': overview['stats']['assists']['displayValue'],
            '救援': overview['stats']['revives']['displayValue'],
            '命中率': f"{round(overview['stats']['shotsFired']['value'] / overview['stats']['shotsHit']['value'])}%",
            '爆头率': overview['stats']['headshotPercentage']['displayValue'],
            '最佳武器': best_weapon,
            '最佳载具': best_vehicle,
        }
        return True, player_info
    else:
        logger.warning(f"请求失败，状态码: {response.status_code}")
        logger.warning(response.text)


if __name__ == "__main__":
    name = "HEIZI-HARUSAME"
    asyncio.run(search_user(name))
