from __future__ import annotations

import re
import unicodedata
from typing import Iterable, List

from .util import collapse_whitespace, unique_ordered


LATEX_COMMAND_WITH_ARG = re.compile(r"\\[a-zA-Z]+\*?\{([^}]*)\}")
LATEX_COMMAND = re.compile(r"\\[a-zA-Z]+\*?(?:\[[^\]]*\])?")
NON_WORD = re.compile(r"[^a-z0-9\s]")


def normalize_title(title: str) -> str:
    if not title:
        return ""
    title = LATEX_COMMAND_WITH_ARG.sub(r"\1", title)
    title = title.replace("{", "").replace("}", "")
    title = LATEX_COMMAND.sub(" ", title)
    title = unicodedata.normalize("NFKC", title)
    title = title.lower()
    title = NON_WORD.sub(" ", title)
    return collapse_whitespace(title)


def normalize_venue(venue: str) -> str:
    if not venue:
        return ""
    venue = unicodedata.normalize("NFKC", venue)
    venue = venue.lower()
    venue = NON_WORD.sub(" ", venue)
    return collapse_whitespace(venue)


def normalize_author_name(name: str) -> str:
    if not name:
        return ""
    name = unicodedata.normalize("NFKC", name)
    name = name.replace("{", "").replace("}", "")
    name = name.lower()
    name = NON_WORD.sub(" ", name)
    return collapse_whitespace(name)


def author_family_names(authors: Iterable[str]) -> List[str]:
    families = []
    for author in authors:
        normalized = normalize_author_name(author)
        if not normalized:
            continue
        parts = normalized.split()
        families.append(parts[-1])
    return unique_ordered(families)
