"""Name data loaded from nicknames.json.

Two kinds of entries:
- Nickname mappings: canonical is set (e.g. bob→robert)
  Categories: 'common', 'archaic', 'international'
- Standalone canonical names: canonical is null (e.g. mark, laura)
  Categories: 'canonical', 'cjk', 'japanese', 'korean', 'arabic', 'french_compound'
"""

import json
from importlib.resources import files

_data_dir = files("corp_names.data")

# Full data with category metadata
_names_data: dict[str, dict] = json.loads(
    (_data_dir / "nicknames.json").read_text(encoding="utf-8")
)

# Simple nickname → canonical lookup (used by normalizer)
# Only includes entries that have a mapping (canonical is not None)
NICKNAME_TO_CANONICAL: dict[str, str] = {
    nick: entry["canonical"]
    for nick, entry in _names_data.items()
    if entry["canonical"] is not None
}

# Set of all known canonical names (targets of nickname mappings + standalone canonicals)
CANONICAL_NAMES: set[str] = (
    {entry["canonical"] for entry in _names_data.values() if entry["canonical"] is not None}
    | {name for name, entry in _names_data.items() if entry["canonical"] is None}
)

# Set of all known names (nicknames + canonicals)
ALL_KNOWN_NAMES: set[str] = set(_names_data.keys()) | CANONICAL_NAMES


def is_known_name(name: str) -> bool:
    """Return True if the name is known (either as a nickname or canonical)."""
    return name.lower() in ALL_KNOWN_NAMES


def get_name_category(name: str) -> str | None:
    """Return the category of a name, or None if not found."""
    entry = _names_data.get(name.lower())
    return entry["category"] if entry else None


def get_nicknames_by_category(category: str) -> dict[str, str]:
    """Return all nickname→canonical mappings for a given category."""
    return {
        nick: entry["canonical"]
        for nick, entry in _names_data.items()
        if entry["category"] == category and entry["canonical"] is not None
    }
