"""Shared helper for splitting a free-text "employee_name" extraction into
individual names, used wherever a query can name several employees at once
(attendance, shift). Kept separate from any one node so both can import the
exact same splitting rules without coupling to each other."""
import re
from typing import Optional

_EMPLOYEE_NAME_SPLIT_RE = re.compile(r",|\band\b|&", re.IGNORECASE)
_TRAILING_POSSESSIVE_RE = re.compile(r"'s$", re.IGNORECASE)


def split_employee_names(raw: Optional[str]) -> list[str]:
    """Splits a comma/'and'/'&'-separated employee_name extraction into
    individual names ("geo3, geo5 and geo9" -> ["geo3","geo5","geo9"]), so a
    single query naming several employees fans out into one lookup per name
    instead of being forwarded as one garbled search term erp-api would
    never match as a single employee. Trailing possessives ("geo3's") are
    stripped since the LLM sometimes copies them verbatim from the query.
    Case-insensitive de-duplication preserves the first-seen casing."""
    if not raw:
        return []
    names: list[str] = []
    seen: set[str] = set()
    for part in _EMPLOYEE_NAME_SPLIT_RE.split(raw):
        name = _TRAILING_POSSESSIVE_RE.sub("", part.strip())
        if name and name.lower() not in seen:
            seen.add(name.lower())
            names.append(name)
    return names