import re
from typing import List
from typing import Set

_BLISS_RE = re.compile(r"^(?P<ctrl>[^:]+):spectrum_det(?P<num>\d+)$")
# Example: "fxb:spectrum_det01"

_BLISS_RE_ALT = re.compile(r"^(?P<ctrl>[^:]+):spectrum:det(?P<num>\d+)$")
# Example: "fx_nano:spectrum:det01"

_HDF5_RE = re.compile(r"^(?P<ctrl>.+)_det(?P<num>\d+)$")
# Example: "fxb_det01"


def counter_to_h5_names(xrf_names: List[str]) -> List[str]:
    """
    Convert counter names to HDF5 NXdetector names.

    Examples:
    - "fxb:spectrum_det01"    -> "fxb_det01"
    - "fxb_det01"             -> "fxb_det01"
    - "fx_nano:spectrum:det00 -> "fx_nano_det0"  # no leading zeros ????
    """
    h5_names = []

    for name in xrf_names:
        if m := _BLISS_RE.match(name):
            prefix = m.group("ctrl")
            number = m.group("num")
            h5_names.append(f"{prefix}_det{number}")

        elif m := _BLISS_RE_ALT.match(name):
            prefix = m.group("ctrl")
            number = int(m.group("num"))
            h5_names.append(f"{prefix}_det{number}")

        elif _HDF5_RE.match(name):
            h5_names.append(name)

        else:
            raise ValueError(f"Unrecognized XRF name format: {name}")

    return h5_names


def counter_to_controller_names(xrf_names: List[str]) -> Set[str]:
    """
    Extract controller names from detector names.

    Examples:
    - "fxb:spectrum_det01"    -> "fxb"
    - "fxb_det01"             -> "fxb"
    - "fx_nano:spectrum:det00 -> "fx_nano"
    """
    controllers: Set[str] = set()

    for name in xrf_names:
        if m := _BLISS_RE.match(name):
            controllers.add(m.group("ctrl"))

        elif m := _BLISS_RE_ALT.match(name):
            controllers.add(m.group("ctrl"))

        elif m := _HDF5_RE.match(name):
            controllers.add(m.group("ctrl"))

        else:
            raise ValueError(f"Unrecognized XRF name format: {name}")

    return controllers
