"""
String normalization helpers for matching.
"""

from __future__ import annotations

import re
from typing import Iterable, List

# Generic corporate suffixes; keep this short and non-domain-specific.
DEFAULT_SUFFIXES: List[str] = [
    "inc",
    "inc.",
    "llc",
    "l.l.c",
    "corp",
    "corporation",
    "co",
    "co.",
    "company",
    "ltd",
    "limited",
]


def normalize_name(name: str, suffixes: Iterable[str] | None = None) -> str:
    """
    Normalize organization names for comparison.

    - Lowercase
    - Strip punctuation to spaces
    - Remove common corporate suffixes (generic, not domain-specific)
    - Collapse whitespace

    Args:
        name: Raw name string.
        suffixes: Optional override list of suffixes to remove; defaults to DEFAULT_SUFFIXES.
    """
    suffix_list = list(suffixes) if suffixes is not None else DEFAULT_SUFFIXES
    text = name.lower()
    text = re.sub(r"[^a-z0-9\s]", " ", text)
    for suffix in suffix_list:
        pattern = r"(\s|\b)" + re.escape(suffix) + r"$"
        text = re.sub(pattern, " ", text)
    text = re.sub(r"\s+", " ", text).strip()
    return text


def normalize_domain(value: str) -> str:
    """
    Normalize a domain, URL, or email to a bare domain.

    Examples:
        "https://www.acme.com/about" -> "acme.com"
        "contact@acme.com" -> "acme.com"
        "www.acme.com" -> "acme.com"
        "ACME.COM" -> "acme.com"
    """
    text = str(value or "").strip().lower()
    if not text:
        return ""

    if "@" in text:
        text = text.split("@", 1)[1]

    if "://" in text:
        from urllib.parse import urlparse

        parsed = urlparse(text)
        text = parsed.netloc or parsed.path.split("/", 1)[0]

    text = text.split("/", 1)[0]
    if text.startswith("www."):
        text = text[4:]
    if ":" in text:
        text = text.split(":", 1)[0]

    return text
