import functools

import httpx
from bs4 import BeautifulSoup

STATION_LINKS = {
    "全国": "https://www.nmc.cn/publish/radar/chinaall.html",
    "华北": "https://www.nmc.cn/publish/radar/huabei.html",
    "东北": "https://www.nmc.cn/publish/radar/dongbei.html",
    "华东": "https://www.nmc.cn/publish/radar/huadong.html",
    "华中": "https://www.nmc.cn/publish/radar/huazhong.html",
    "华南": "https://www.nmc.cn/publish/radar/huanan.html",
    "西南": "https://www.nmc.cn/publish/radar/xinan.html",
    "西北": "https://www.nmc.cn/publish/radar/xibei.html",
}

async def fetch_radar(station: str) -> tuple[bytes, None] | tuple[None, str]:
    if station not in STATION_LINKS.keys():
        return None, f"获取失败：站点不存在。可用的站点：{','.join(STATION_LINKS.keys())}"

    async with httpx.AsyncClient() as client:
        response = await client.get(STATION_LINKS[station])
        if response.status_code != 200:
            return None, "获取失败：可能存在网络错误"

        soup = BeautifulSoup(response.text, "lxml")
        links = functools.reduce(lambda x, y: x + y, [
            img.get_attribute_list("src") for img in soup.select("div.imgblock>img#imgpath")
        ])
        if len(links) != 1:
            return None, "获取失败：链接获取失败"

        response2 = await client.get(links[0])
        if response2.status_code != 200:
            return None, "获取失败：图片下载失败"

        return response2.content, None
