from typing import Optional
from PIL import ImageColor

class ColorHandle:
    color_name_map = {
        "红": (255, 0, 0),
        "绿": (0, 255, 0),
        "蓝": (0, 0, 255),
        "黄": (255, 255, 0),
        "紫": (128, 0, 128),
        "黑": (0, 0, 0),
        "白": (255, 255, 255),
        "橙": (255, 165, 0),
        "粉": (255, 192, 203),
        "灰": (128, 128, 128),
        "青": (0, 255, 255),
        "靛": (75, 0, 130),
        "棕": (165, 42, 42),
        "浅": (200, 200, 200),
        "深": (50, 50, 50),
        "亮": (255, 255, 224),
        "暗": (47, 79, 79),
    }

    @staticmethod
    def set_or_blend_color(ori_color: Optional[tuple], target_color: tuple) -> tuple:
        # 如果没有指定初始颜色，返回目标颜色
        if ori_color is None:
            return target_color
        # 混合颜色，取平均值
        blended_color = tuple((o + t) // 2 for o, t in zip(ori_color, target_color))
        return blended_color

    @staticmethod
    def parse_color(color_str: str) -> tuple:
        # 如果是纯括号，则加上前缀 rgb
        if color_str.startswith('(') and color_str.endswith(')'):
            color_str = 'rgb' + color_str
        try:
            return ImageColor.getrgb(color_str)
        except ValueError:
            pass
        base_color = None
        color_str = color_str.replace('色', '')
        for name, rgb in ColorHandle.color_name_map.items():
            if name in color_str:
                base_color = ColorHandle.set_or_blend_color(base_color, rgb)
        if base_color is not None:
            return base_color
        return (255, 255, 255)  # 默认白色