import csv
from nonebot import logger
from nonebot_plugin_apscheduler import driver
from konabot.common.path import ASSETS_PATH

FONT_ASSETS_PATH = ASSETS_PATH / "old_font"

class ErFontData:
    data = {}
    temp_featured_fonts = {}

    @classmethod
    def init(cls):
        logger.info("加载二简字体数据...")
        path = FONT_ASSETS_PATH / "symtable.csv"
        if not path.exists():
            return
        with open(path, "r", encoding="utf-8-sig") as f:
            reader = csv.DictReader(f)
            for row in reader:
                if len(row["ss05"]) > 0:
                    cls.data[row["trad"]] = {"char": row["ss05"][0], "type": "ss05", "render": False}
                    if "er" in row["ss05"]:
                        cls.data[row["trad"]]["render"] = True
                elif len(row["ss06"]) > 0:
                    cls.data[row["trad"]] = {"char": row["ss06"][0], "type": "ss06", "render": False}
                    if "er" in row["ss06"]:
                        cls.data[row["trad"]]["render"] = True
        logger.info(f"二简字体数据加载完成，包含 {len(cls.data)} 个字。")
    
    @classmethod
    def get(cls, char: str) -> str:
        if char not in cls.data:
            return char
        if cls.data[char]["render"]:
            return f"<span class={cls.data[char]['type']}>{cls.data[char]['char']}</span>"
        return cls.data[char]["char"]
    
    @classmethod
    def convert_text(cls, text: str) -> str:
        return "".join([cls.get(c) for c in text])
    
@driver.on_startup
async def load_er_font_data():
    ErFontData.init()