# src/extractor/canon/normalizer.py

import hashlib
import re
import unicodedata

ORG_SUFFIXES = re.compile(
    r"\b(Inc\.?|Ltd\.?|LLC\.?|Corp\.?|Co\.?|PLC\.?|GmbH\.?|"
    r"Incorporated|Limited|Corporation|Company|Holdings?|Group|"
    r"Partners?|Associates?|Ventures?|International|Global)\b\.?",
    re.IGNORECASE,
)
PERSON_TITLES = re.compile(
    r"^(Dr\.?|Mr\.?|Mrs\.?|Ms\.?|Prof\.?|Sir|Dame|"
    r"Gen\.?|Col\.?|Sen\.?|Rep\.?|Gov\.?)\s+",
    re.IGNORECASE,
)
TICKER_MAP: dict[str, str] = {
    "AAPL": "Apple",
    "MSFT": "Microsoft",
    "GOOGL": "Alphabet",
    "META": "Meta Platforms",
    "AMZN": "Amazon",
    "TSLA": "Tesla",
    "NVDA": "Nvidia",
    "JPM": "JPMorgan Chase",
    "BAC": "Bank of America",
}


def normalize_surface(text: str, entity_type: str) -> str:
    text = unicodedata.normalize("NFC", text)
    text = " ".join(text.split())
    if entity_type == "organization":
        if text.upper() in TICKER_MAP:
            return TICKER_MAP[text.upper()]
        text = ORG_SUFFIXES.sub("", text).strip()
    elif entity_type == "person":
        text = PERSON_TITLES.sub("", text).strip()
    return text


def make_slug(text: str) -> str:
    text = unicodedata.normalize("NFC", text).lower()
    text = re.sub(r"[^\w\s-]", "", text)
    text = re.sub(r"[\s_]+", "-", text).strip("-")
    return text


def derive_canonical_id(entity_type: str, canonical_text: str) -> str:
    slug = make_slug(normalize_surface(canonical_text, entity_type))
    return f"{entity_type.lower()}:{slug}"


def derive_canonical_id_with_disambiguation(
    entity_type: str, canonical_text: str, existing_text: str
) -> str:
    slug = make_slug(normalize_surface(canonical_text, entity_type))
    suffix = hashlib.sha256(canonical_text.encode()).hexdigest()[:4]
    return f"{entity_type.lower()}:{slug}-{suffix}"
