import os

_ENV_PATTERNS_DIR = "LED_CONTROLLER_PATTERNS_DIR"

def driver_patterns_dir():
    """Absolute path to driver pattern ``.py`` modules.

    If ``LED_CONTROLLER_PATTERNS_DIR`` is set to an existing directory, that wins
    (for installs where ``led-driver`` is not next to this repo). Otherwise uses
    ``<project-root>/led-driver/src/patterns``.
    """
    env = (os.environ.get(_ENV_PATTERNS_DIR) or "").strip()
    if env and os.path.isdir(env):
        return os.path.abspath(env)
    here = os.path.dirname(os.path.abspath(__file__))
    root = os.path.abspath(os.path.join(here, "..", ".."))
    return os.path.join(root, "led-driver", "src", "patterns")


def normalize_pattern_py_filename(name):
    """Return a single ``*.py`` basename (no paths), or ``\"\"`` if invalid.

    Strips repeated ``.py`` suffixes so ``blink.py.py`` becomes ``blink.py``.
    """
    if not isinstance(name, str):
        return ""
    s = name.strip()
    if not s:
        return ""
    lower = s.lower()
    while lower.endswith(".py"):
        s = s[:-3]
        s = s.strip()
        lower = s.lower()
    if not s:
        return ""
    if "/" in s or "\\" in s or ".." in s:
        return ""
    return s + ".py"


# Implemented in led-driver ``presets.py`` only — no separate ``patterns/*.py``.
FIRMWARE_BUILTIN_PATTERN_IDS = frozenset({"on", "off"})


def is_firmware_builtin_pattern_module(name):
    """True for ``on`` / ``off``, with or without a ``.py`` suffix."""
    if not isinstance(name, str):
        return False
    s = name.strip().lower()
    while s.endswith(".py"):
        s = s[:-3].strip()
    return s in FIRMWARE_BUILTIN_PATTERN_IDS
