from __future__ import annotations

from typing import Any, Dict, List
import re
import unicodedata

_SUFFIXES = {"jr", "sr", "ii", "iii", "iv", "v", "phd", "md", "esq"}


def _norm(s: str) -> str:
    """
    Normalize name while preserving international characters.

    Supports CJK, Cyrillic, Arabic, Hebrew, and all Unicode scripts.
    Uses NFKC normalization for canonical form without stripping non-ASCII.
    """
    # Normalize to canonical Unicode form
    s = unicodedata.normalize("NFKC", s or "").strip()
    # Collapse multiple spaces
    s = re.sub(r"\s+", " ", s)
    return s


def split_fullname(value: str) -> Dict[str, Any]:
    """
    Split full name into first and last name, preserving international characters.

    Supports names in all scripts:
    - Latin: "John Smith" -> ["John", "Smith"]
    - Chinese: "李明" -> ["李", "明"] (if space-separated) or ["李明", ""]
    - Russian: "Владимир Петров" -> ["Владимир", "Петров"]
    - Arabic: "محمد علي" -> ["محمد", "علي"]

    Handles formats:
    - "First Last" -> ["First", "Last"]
    - "Last, First" -> ["First", "Last"]
    - Removes trailing suffixes (Jr, Sr, PhD, etc.)
    """
    s = _norm(value)
    if not s:
        return {"value": ["", ""]}
    # Last, First
    if "," in s:
        last, first = [p.strip() for p in s.split(",", 1)]
        return {"value": [first.title(), last.title()]}
    parts: List[str] = s.split(" ")
    # drop trailing suffix
    if parts and parts[-1].lower().strip(".") in _SUFFIXES:
        parts = parts[:-1]
    if len(parts) == 1:
        return {"value": [parts[0].title(), ""]}
    return {"value": [parts[0].title(), parts[-1].title()]}
