# -*- coding: utf-8 -*-
"""
颜色映射器（纯 Python，无 Qt 依赖）
- 接受 BGR 列表（List[Tuple[int,int,int]] 或 list of [B,G,R]）
- 线性插值返回 BGR tuple
"""

import numpy as np
from typing import Tuple, Callable, List, Union


def _to_bgr(item: Union[list, tuple]) -> Tuple[int, int, int]:
    """将配置中的颜色项转为 (B, G, R) 元组。"""
    if isinstance(item, (list, tuple)) and len(item) == 3:
        return (int(item[0]), int(item[1]), int(item[2]))
    raise ValueError(f"颜色项须为长度为3的 list/tuple，得到: {item}")


class ColorMapper:
    """颜色映射器（供 ColorManager 使用），纯 Python BGR 插值"""

    @staticmethod
    def get_color_from_list(ratio: float, color_list: List) -> Tuple[int, int, int]:
        """
        ratio: [0, 1]
        color_list: BGR 列表，每项为 [B, G, R] 或 (B, G, R)
        返回: (B, G, R)
        """
        ratio = float(np.clip(ratio, 0, 1))
        if not color_list or len(color_list) < 2:
            return (0, 255, 0)

        idx = ratio * (len(color_list) - 1)
        idx_lower = int(idx)
        idx_upper = min(idx_lower + 1, len(color_list) - 1)
        blend = idx - idx_lower

        c1 = _to_bgr(color_list[idx_lower])
        c2 = _to_bgr(color_list[idx_upper])

        b = int(c1[0] * (1 - blend) + c2[0] * blend)
        g = int(c1[1] * (1 - blend) + c2[1] * blend)
        r = int(c1[2] * (1 - blend) + c2[2] * blend)
        return (b, g, r)

    @staticmethod
    def create_color_map_function(color_list) -> Callable[[float], Tuple[int, int, int]]:
        """创建 ratio -> (B,G,R) 的映射函数。"""
        if color_list is None:
            return lambda _: (0, 255, 0)

        def mapper(ratio: float) -> Tuple[int, int, int]:
            return ColorMapper.get_color_from_list(ratio, color_list)

        return mapper
