from curl_cffi import requests
from lxml import etree


def get_code(url):
    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'no-cache',
        'dnt': '1',
        'pragma': 'no-cache',
        'priority': 'u=0, i',
        'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Microsoft Edge";v="132"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'none',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0',
    }

    response = requests.get(url=url, headers=headers)

    # 解析 HTML
    tree = etree.HTML(response.content)

    # 使用 XPath 提取 value 属性
    code = tree.xpath('//*[@id="code"]/@value')[0]

    # 使用 XPath 提取 value 属性
    code1 = tree.xpath('//*[@id="pass2fa"]/@value')[0]

    return code, code1


# 定义一个字典，保存已知的国家代码和对应的区域代码
country_code_map = {
    "1": "US",  # 美国
    "44": "GB",  # 英国
    "27": "ZA",  # 南非
    "234": "NG",  # 尼日利亚
    "86": "CN",  # 中国
    "63": "PH",  # 菲律宾
}


def split_phone_number(phone_number):
    # 去掉可能的 '+' 符号
    if phone_number.startswith('+'):
        phone_number = phone_number[1:]

    # 遍历国家代码前缀，尝试匹配
    for prefix in country_code_map:
        if phone_number.startswith(prefix):
            country_code = prefix
            national_number = phone_number[len(prefix):]  # 去掉国家码
            return country_code, national_number

    # 如果没有匹配的国家代码，返回 None
    return None, None
