import csv
import os
import sys

from loguru import logger

# 获取当前文件所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 向上两级到 konabot 目录
konabot_dir = os.path.abspath(os.path.join(current_dir, '../../../'))

if konabot_dir not in sys.path:
    sys.path.insert(0, konabot_dir)

from konabot.common.path import ASSETS_PATH


ORACLE_PATH = ASSETS_PATH / "oracle"

final_zi_dict = {}
with open(ORACLE_PATH / "zi_dict.csv", "r", encoding="utf-8-sig") as f:
    reader = csv.DictReader(f)
    for row in reader:
        logger.info(f"Progress: {reader.line_num}")
        # 找到子字头字段，并找到对应的图像路径
        char = row["子字头"].strip()
        # 寻找路径
        image_path = ORACLE_PATH / "image"
        # 遍历所有子目录，寻找对应的图片文件
        found_image = None
        for subdir in image_path.iterdir():
            if subdir.is_dir():
                candidate = subdir / char
                if candidate.exists():
                    # 寻找该目录下有没有以 char 命名的图片文件，没有就选第一个图片文件
                    if (candidate / f"{char}.png").exists():
                        found_image = candidate / f"{char}.png"
                        break
                    else:
                        for file in candidate.iterdir():
                            if file.suffix.lower() in [".png", ".jpg", ".jpeg", ".gif", ".bmp"]:
                                found_image = file
                                break
        if found_image is not None:
            # 提取相对路径
            found_image = found_image.relative_to(ORACLE_PATH / "image")
            # 反斜杠改正为斜杠
            found_image = found_image.as_posix()
            # 更新行数据
            row.update({"路径": str(found_image)})
        final_zi_dict[char] = row

# 将最终的字典写入新的 CSV 文件
with open(ORACLE_PATH / "zi_dict_with_images.csv", "w", encoding="utf-8-sig", newline="") as f:
    fieldnames = list(final_zi_dict[next(iter(final_zi_dict))].keys())
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for char, data in final_zi_dict.items():
        writer.writerow(data)