"""
跨平台字体工具
支持 Linux、macOS、Windows 系统的中文字体加载
"""
import os
import logging
from typing import Optional
from PIL import ImageFont

logger = logging.getLogger(__name__)

# 跨平台字体路径列表（按优先级排序）
FONT_PATHS = [
    # Linux 常见中文字体
    "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
    "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
    # macOS 字体
    "/System/Library/Fonts/PingFang.ttc",
    "/System/Library/Fonts/STHeiti Medium.ttc",
    "/System/Library/Fonts/STHeiti Light.ttc",
    "/System/Library/Fonts/Helvetica.ttc",
    "/Library/Fonts/Arial Unicode.ttf",
    # Windows 字体
    "C:/Windows/Fonts/msyh.ttc",
    "C:/Windows/Fonts/msyhbd.ttc",
    "C:/Windows/Fonts/simhei.ttf",
    "C:/Windows/Fonts/simsun.ttc",
]

# 缓存已找到的字体路径
_cached_font_path: Optional[str] = None


def find_available_font() -> Optional[str]:
    """
    查找系统中可用的字体文件路径

    Returns:
        找到的字体路径，如果没有找到则返回 None
    """
    global _cached_font_path

    if _cached_font_path is not None:
        return _cached_font_path

    for font_path in FONT_PATHS:
        if os.path.exists(font_path):
            logger.info(f"Found available font: {font_path}")
            _cached_font_path = font_path
            return font_path

    logger.warning("No Chinese font found, will use default fonts")
    return None


def get_font(size: int = 24, encoding: str = "unic") -> ImageFont.FreeTypeFont:
    """
    获取可用的字体，支持跨平台

    Args:
        size: 字体大小
        encoding: 字体编码，默认 "unic" 支持 Unicode

    Returns:
        PIL ImageFont 对象
    """
    font_path = find_available_font()

    if font_path:
        try:
            return ImageFont.truetype(font_path, size, encoding=encoding)
        except Exception as e:
            logger.warning(f"Failed to load font {font_path}: {e}")

    # 回退到默认字体
    logger.warning(f"Using default font for size {size}")
    return ImageFont.load_default()


def get_fonts(large_size: int = 42, small_size: int = 21) -> tuple:
    """
    获取大小两种字体

    Args:
        large_size: 大字体大小
        small_size: 小字体大小

    Returns:
        (large_font, small_font) 元组
    """
    font_path = find_available_font()

    if font_path:
        try:
            large_font = ImageFont.truetype(font_path, large_size, encoding="unic")
            small_font = ImageFont.truetype(font_path, small_size, encoding="unic")
            return large_font, small_font
        except Exception as e:
            logger.warning(f"Failed to load fonts from {font_path}: {e}")

    # 回退到默认字体
    default_font = ImageFont.load_default()
    return default_font, default_font
