"""Enum helpers for corridors, horizons, and reasons."""

from __future__ import annotations

from enum import Enum
import re
from typing import Iterable, Type


def _sanitize_enum_key(value: str) -> str:
    key = re.sub(r"[^0-9a-zA-Z]+", "_", value).strip("_").upper()
    if not key:
        key = "VALUE"
    if key[0].isdigit():
        key = f"V_{key}"
    return key


def make_enum(name: str, values: Iterable[str]) -> Type[Enum]:
    """Create a string-valued Enum from an iterable of values."""
    members = {}
    for raw in values:
        if raw is None:
            continue
        value = str(raw)
        key = _sanitize_enum_key(value)
        if key in members:
            suffix = 2
            while f"{key}_{suffix}" in members:
                suffix += 1
            key = f"{key}_{suffix}"
        members[key] = value
    return Enum(name, members, type=str)


def corridor_enum(corridors: Iterable[str]) -> Type[Enum]:
    """Build a Corridor Enum from corridor codes."""
    return make_enum("Corridor", corridors)


def horizon_enum(horizons: Iterable[str]) -> Type[Enum]:
    """Build a Horizon Enum from horizon codes."""
    return make_enum("Horizon", horizons)


def curtailment_reason_enum(reasons: Iterable[str]) -> Type[Enum]:
    """Build a CurtailmentReason Enum from reason strings."""
    return make_enum("CurtailmentReason", reasons)
