import json
from nonebot import logger
import os

from cffi.model import voidp_type
from jinja2 import Environment, FileSystemLoader
from playwright.async_api import async_playwright, ViewportSize
import asyncio

from Core.Utils import get_root_path
from Core.BrowserCore import BrowserTab
from curl_cffi import requests, AsyncSession, CurlError
import base64

b = BrowserTab("https://battlefieldtracker.com/bf2042/profile/origin/Sansorano_Yume/overview")

url_zy = "https://battlefieldtracker.com/bf2042/profile/origin/{name}/overview"
url_over = "https://api.tracker.gg/api/v2/bf2042/standard/profile/origin/{name}"
url_weapon = "https://api.tracker.gg/api/v2/bf2042/standard/profile/origin/{name}/segments/weapon"
url_vehicle = "https://api.tracker.gg/api/v2/bf2042/standard/profile/origin/{name}/segments/vehicle"
url_soldier = "https://api.tracker.gg/api/v2/bf2042/standard/profile/origin/{name}/segments/soldier"
url_history = "https://api.tracker.gg/api/v2/bf2042/standard/profile/origin/{name}/history"
url_ban = "https://api.gametools.network/bfban/checkban/?names={name}"

url_dict = {
    "overview": url_over,
    "weapons": url_weapon,
    "vehicle": url_vehicle,
    "soldier": url_soldier,
    "ban": url_ban,
}
headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5",
    "priority": "u=1, i",
    "sec-ch-ua": '"Not;A=Brand";v="99", "Microsoft Edge";v="139", "Chromium";v="139"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "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 Edg/139.0.0.0"
}
classesList = {
    "Mackay": "   麦凯",
    "Angel": "   天使",
    "Falck": "  法尔克",
    "Paik": "  白智秀",
    "Sundance": "   日舞",
    "Dozer": "  推土机",
    "Rao": "   拉奥",
    "Lis": "   莉丝",
    "Irish": "爱尔兰佬",
    "Crawford": "克劳福德",
    "Boris": "  鲍里斯",
    "Zain": "   扎因",
    "Casper": "  卡斯帕",
    "Blasco": "布拉斯科",
    "BF3 Recon": "BF3 侦察",
    "BF3 Support": "BF3 支援",
    "BF3 Assault": "BF3 突击",
    "BF3 Engineer": "BF3 工程",
    "BC2 Recon": "BC2 侦察",
    "BC2 Medic": "BC2 医疗",
    "BC2 Assault": "BC2 突击",
    "BC2 Engineer": "BC2 工程",
    "1942 Anti-tank": "1942 反坦克",
    "1942 Assault": "1942 突击",
    "1942 Medic": "1942 医疗",
    "1942 Engineer": "1942 工程",
    "1942 Scout": "1942 侦察",
}


def get_base64(img_path: str, deafult: str = None):
    path = f"{get_root_path()}/{img_path}"
    if not os.path.exists(path):
        if deafult is None:
            return False, None
        return get_base64(deafult)
    with open(path, "rb") as f:
        return True, base64.b64encode(f.read()).decode()


async def fetch_url(url: str, name: str, browser: str = "chrome110"):
    async with AsyncSession() as session:
        try:
            response = await session.get(url, impersonate=browser)
            return {
                "name": name,
                "status": response.status_code,
                "content": response.json(),
            }
        except TimeoutError:
            return {"name": name, "status": 0, "error": "请求超时"}
        except ConnectionError:
            return {"name": name, "status": 0, "error": "连接失败"}
        except CurlError as e:
            return {"name": name, "status": 0, "error": f"底层 cURL 错误: {str(e)}"}
        except Exception as e:
            return {"name": name, "status": 0, "error": f"未知错误: {str(e)}"}


async def bf2042_state(cmd):
    name = cmd
    raw = {}
    logger.info("开始get数据")
    task = [fetch_url(v.format(name=name), k) for k, v in url_dict.items()]
    res = await asyncio.gather(*task)
    logger.info("开始解析数据")
    if raw is None or isinstance(raw, str):
        await event.send("没有找到该玩家或者服务器请求失败，请等待")
        return
    flag_cf = False
    has_player = False
    for i in res:
        if i["status"] == 404:
            try:
                json.loads(i["content"])
                has_player = True
            except json.JSONDecodeError:
                flag_cf = True
            return
        if i["status"] == 0 or i["status"] == 400:
            has_player = True
    if flag_cf:
        await event.send("当前数据获取失败，正在过盾，请等待响应")
        await b.cf_bypasser.bypass_turnstile()
        b.page.get_screenshot("img/hc.png")
        if b.cf_bypasser.is_bypassed() or b.cf_bypasser.is_turnstile():
            await event.send("已获取认证，请重新查询")
        else:
            await event.send(Message(TextSegment("获取失败已返回结果图")).append(ImgSegment("img/hc.png")))
        return
    if has_player:
        await event.send("没有找到该玩家,，该文件的名字可能出错或者该玩家并未开启隐私设置")
        return
    logging.info(1)
    overview = res[0]["content"]["data"]["segments"][0]["stats"]
    logging.info(2)
    res[1]["content"]["data"].sort(key=lambda x: x["stats"]["kills"]["value"], reverse=True)
    weapons = res[1]["content"]["data"][:6]
    # logging.info(weapons)
    logging.info(3)
    res[2]["content"]["data"].sort(key=lambda x: x["stats"]["kills"]["value"], reverse=True)
    veh = res[2]["content"]["data"][:6]
    logging.info(veh)
    logging.info(4)
    res[3]["content"]["data"].sort(key=lambda x: x["stats"]["kills"]["value"], reverse=True)
    class_data = res[3]["content"]["data"][0]
    # logging.info(class_data)
    logging.info(5)
    cheat_hack = res[4]["content"]["names"][name.lower()]["hacker"]
    logging.info(6)

    percentile_kills = overview["kills"]["percentile"]
    kills_t = f"Top {round(100 - percentile_kills, 2)}" if percentile > 50 else f"Bottom {percentile}"
    kills_t = f"{kills_t}%"

    percentile_deaths = overview["deaths"]["percentile"]
    death_t = f"Top {round(100 - percentile_deaths, 2)}" if percentile > 50 else f"Bottom {percentile}"
    death_t = f"{death_t}%"

    percentile_assists = overview["assists"]["percentile"]
    zg_t = f"Top {round(100 - percentile_assists, 2)}" if percentile > 50 else f"Bottom {percentile}"
    zg_t = f"{zg_t}%"

    percentile_wins = overview["wins"]["percentile"]
    slcs_t = f"Top {round(100 - percentile_wins, 2)}" if percentile > 50 else f"Bottom {percentile}"
    slcs_t = f"{slcs_t}%"

    percentile_losses = overview["losses"]["percentile"]
    sbcs_t = f"Top {round(100 - percentile_losses, 2)}" if percentile > 50 else f"Bottom {percentile}"
    sbcs_t = f"{sbcs_t}%"

    percentile_revives = overview["revives"]["percentile"]
    fhcs_t = f"Top {round(100 - percentile_revives, 2)}" if percentile > 50 else f"Bottom {percentile}"
    fhcs_t = f"{fhcs_t}%"

    data = {
        "playerName": name,
        "level": overview["level"]["displayValue"],
        "time": overview["timePlayed"]["displayValue"],
        "kd": overview["kdRatio"]["displayValue"],
        "kd_real": overview["humanKdRatio"]["displayValue"],
        "kpm": overview["killsPerMinute"]["displayValue"],
        "win_acc": overview["wlPercentage"]["displayValue"],
        "kills": overview["kills"]["displayValue"],
        "kills_p": overview["kills"]["percentile"],
        "kills_t": kills_t,
        "death": overview["deaths"]["displayValue"],
        "death_p": overview["deaths"]["percentile"],
        "death_t": death_t,
        "ai_kills": overview["aiKills"]["displayValue"],
        "zr_kills": overview["humanKills"]["displayValue"],
        "zk_kills": overview["vehicleKills"]["displayValue"],
        "dc_kills": overview["multiKills"]["displayValue"],
        "jz_kills": overview["meleeKills"]["displayValue"],
        "zj_kills": overview["roadKills"]["displayValue"],
        "zg": overview["assists"]["displayValue"],
        "zg_p": overview["assists"]["percentile"],
        "zg_t": zg_t,
        "slcs": overview["wins"]["displayValue"],
        "slcs_p": overview["wins"]["percentile"],
        "slcs_t": slcs_t,
        "sbcs": overview["losses"]["displayValue"],
        "sbcs_p": overview["losses"]["percentile"],
        "sbcs_t": sbcs_t,
        "fhcs": overview["revives"]["displayValue"],
        "fhcs_p": overview["revives"]["percentile"],
        "fhcs_t": fhcs_t,
        "zsh": overview["damageDealt"]["displayValue"],
        "mfzsh": round(overview["damageDealt"]["value"] / (overview["timePlayed"]["value"] / 60), 2),
        "chzj": overview["vehiclesDestroyed"]["displayValue"],
        "kjjs": overview["scopedKills"]["displayValue"],
        "mbzlsj": overview["objectiveTime"]["displayValue"],
        "zlmb": overview["objectivesCaptured"]["displayValue"],
        "fsmb": overview["defendedObjectives"]["displayValue"],
        "a_c_c": f"{overview['objectivesArmed']['displayValue']}/{overview['objectivesDisarmed']['displayValue']}/{overview['objectivesDestroyed']['displayValue']}",
        "fsqy": overview["defendedSectors"]["displayValue"],
        "sqqb": overview["intelPickedUp"]["displayValue"],
        "tqqb": overview["intelExtracted"]["displayValue"],
        "btl": overview["headshotPercentage"]["displayValue"],
        "bts": overview["headshotKills"]["displayValue"],
        "w_data": weapons,
        "v_data": veh,
        "zjmz": classesList[class_data["metadata"]["name"].strip()] if class_data["metadata"][
                                                                           "name"].strip() in classesList else
        class_data["metadata"]["name"],
        "zj_kd": class_data["stats"]["kdRatio"]["displayValue"],
        "zj_kpm": class_data["stats"]["killsPerMinute"]["displayValue"],
        "zjia_kills": class_data["stats"]["kills"]["displayValue"],
        "zj_time": class_data["stats"]["timePlayed"]["displayValue"],
    }
    logger.info("解析数据完成")
    return data
