import re


_NON_ALNUM_PATTERN = re.compile(r"[^a-z0-9]+")


def _normalize_widget_segment(value) -> str:
    cleaned = _NON_ALNUM_PATTERN.sub("-", str(value or "").strip().lower()).strip("-")
    return cleaned or "none"


def compose_widget_unique(service, identifier, person_id=None) -> str:
    service_key = str(service or "").strip().lower() or "signal"
    identifier_value = str(identifier or "").strip()
    if service_key == "whatsapp" and "@" in identifier_value:
        identifier_value = identifier_value.split("@", 1)[0].strip()
    return "-".join(
        [
            "compose-widget",
            _normalize_widget_segment(service_key),
            _normalize_widget_segment(identifier_value),
            _normalize_widget_segment(person_id or "none"),
        ]
    )


def compose_widget_dom_id(service, identifier, person_id=None) -> str:
    return f"widget-{compose_widget_unique(service, identifier, person_id)}"
