# -*- coding: utf-8 -*-
"""
默认配色方案：从包内 YAML 加载，提供 get_default_color_scheme / list_default_scheme_names
"""

from pathlib import Path
from typing import List, Tuple

import yaml

from lidar_manager.logger import get_module_logger

logger = get_module_logger(__name__)

_CACHE: dict = None


def _load_color_cfg() -> dict:
    """从包内 config/lidar_color_cfg.yaml 加载配置（带缓存）。"""
    global _CACHE
    if _CACHE is not None:
        return _CACHE
    try:
        from importlib.resources import files
        pkg = files("lidar_manager")
        path = pkg / "config" / "lidar_color_cfg.yaml"
        if path.is_file():
            with open(path, "r", encoding="utf-8") as f:
                _CACHE = yaml.safe_load(f) or {}
        else:
            # 兼容：开发时可能从项目根运行，尝试相对路径
            fallback = Path(__file__).resolve().parent.parent / "config" / "lidar_color_cfg.yaml"
            if fallback.is_file():
                with open(fallback, "r", encoding="utf-8") as f:
                    _CACHE = yaml.safe_load(f) or {}
            else:
                _CACHE = {}
                logger.warning("lidar_manager 未找到 config/lidar_color_cfg.yaml，默认配色列表为空")
    except Exception as e:
        logger.warning("加载默认配色 YAML 失败: %s", e)
        _CACHE = {}
    return _CACHE


def get_default_color_scheme(scheme_name: str) -> List[Tuple[int, int, int]]:
    """
    按名称获取内置配色方案（BGR 列表）。

    参数:
        scheme_name: 方案名，如 "jet", "viridis", "rainbow"

    返回:
        BGR 颜色列表，每项为 (B, G, R)。若未找到则返回默认 jet 或空列表。
    """
    cfg = _load_color_cfg()
    schemes = cfg.get("color_schemes") or {}
    one = schemes.get(scheme_name)
    if not one:
        if scheme_name not in schemes and schemes:
            logger.warning("未找到配色方案 '%s'，使用 'jet'", scheme_name)
            one = schemes.get("jet")
        if not one:
            return []
    colors = one.get("colors") or []
    return [tuple(int(c) for c in item) for item in colors]


def list_default_scheme_names() -> List[str]:
    """返回所有内置配色方案名称列表。"""
    cfg = _load_color_cfg()
    schemes = cfg.get("color_schemes") or {}
    return list(schemes.keys())
