"""Pure company name normalization using heuristics only.

This module provides company name normalization without any external
dependencies - no LLM, no registry lookup, no FoundryGraph. It uses
only static data and text processing heuristics.

For resolution (finding canonical company names via registry/LLM),
use the resolution module instead.
"""

from __future__ import annotations

import re
from typing import List

from .text import normalize_text
from ..heuristics import LEGAL_SUFFIXES, ABBREV_EXPANSIONS, COMPANY_STOPWORDS


# Match non-word characters except &, +
# \w includes Unicode letters/digits, so this preserves international company names
_TOKEN_SPLIT = re.compile(r"[^\w&+]+", re.UNICODE)


def title_case_tokens(tokens: List[str]) -> str:
    """Convert tokens to title case, preserving common lowercase words.

    Lowercase words like 'and', 'of', 'the' are kept lowercase
    unless they are the first word.

    Args:
        tokens: List of lowercase tokens to convert

    Returns:
        Title-cased string with tokens joined by spaces
    """
    if not tokens:
        return ""

    lowercase_words = {"and", "of", "the", "for", "in"}
    out = []
    for i, t in enumerate(tokens):
        if i > 0 and t in lowercase_words:
            out.append(t)
        else:
            out.append(t[:1].upper() + t[1:])
    return " ".join(out)


def normalize_company_text(name: str) -> str:
    """Normalize company name using pure heuristics.

    This function applies text normalization without any external lookups:
    1. Unicode NFKC normalization
    2. Expand common abbreviations (intl → international, etc.)
    3. Remove legal suffixes (Inc, LLC, Ltd, etc.)
    4. Remove stopwords (the, and, of, etc.)
    5. Title case the result

    Supports company names in all scripts:
    - Latin: "Société Générale Inc" → "Société Générale"
    - Japanese: "日本電信電話株式会社" → "日本電信電話"
    - Russian: "Яндекс ООО" → "Яндекс"
    - Chinese: "阿里巴巴集團" → "阿里巴巴集團"

    Args:
        name: Company name to normalize

    Returns:
        Normalized company name, or empty string if input is empty

    Note:
        This function does NOT resolve company names to canonical forms.
        For that, use resolve_company() from the resolution module.
    """
    s = normalize_text(name).strip().lower()
    if not s:
        return ""

    # Replace & with 'and' for consistent tokenization
    s = s.replace("&", " and ")

    # Tokenize, preserving unicode letters/digits
    tokens = [t for t in _TOKEN_SPLIT.split(s) if t]

    # Expand common abbreviations
    expanded = [ABBREV_EXPANSIONS.get(t, t) for t in tokens]

    # Drop legal suffix at end
    if expanded and expanded[-1] in LEGAL_SUFFIXES:
        expanded = expanded[:-1]

    # Remove stopwords
    trimmed = [t for t in expanded if t not in COMPANY_STOPWORDS]

    # Remove pure numeric tokens
    trimmed = [t for t in trimmed if not all(ch.isdigit() for ch in t)]

    if not trimmed:
        return ""

    return title_case_tokens(trimmed)
