"""Normalize a raw email string from messy sources (TSVs, CSVs, spreadsheets)."""


def clean_email(raw: str) -> str:
    """Strip whitespace, angle brackets, surrounding quotes; lowercase; validate basic shape.

    Args:
        raw: Raw email string that may contain surrounding whitespace, angle brackets
             (Outlook/RFC 5322 display-name form), or surrounding quotes.

    Returns:
        Cleaned, lowercased email address.

    Raises:
        ValueError: If the cleaned result is not a plausible email (must contain
                    exactly one '@', non-empty local part, and at least one '.'
                    in the domain part).
    """
    cleaned = raw.strip()

    # Strip surrounding angle brackets: <foo@bar.com> -> foo@bar.com
    if cleaned.startswith("<") and cleaned.endswith(">"):
        cleaned = cleaned[1:-1].strip()

    # Strip surrounding double quotes: "foo@bar.com" -> foo@bar.com
    if len(cleaned) >= 2 and cleaned[0] == '"' and cleaned[-1] == '"':
        cleaned = cleaned[1:-1].strip()
    # Strip surrounding single quotes: 'foo@bar.com' -> foo@bar.com
    elif len(cleaned) >= 2 and cleaned[0] == "'" and cleaned[-1] == "'":
        cleaned = cleaned[1:-1].strip()

    cleaned = cleaned.lower()

    # Validate basic shape
    at_count = cleaned.count("@")
    if at_count != 1:
        raise ValueError(
            f"invalid email after cleaning: {raw!r} -> {cleaned!r}"
        )

    local, domain = cleaned.split("@", 1)

    if not local:
        raise ValueError(
            f"invalid email after cleaning: {raw!r} -> {cleaned!r}"
        )

    if "." not in domain:
        raise ValueError(
            f"invalid email after cleaning: {raw!r} -> {cleaned!r}"
        )

    return cleaned
