from __future__ import annotations

import re


LANGUAGE_TOKEN_RE = re.compile(r"^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$")


def normalize_language_tag(value: str) -> str:
    tag = value.strip().replace("_", "-")
    if not LANGUAGE_TOKEN_RE.fullmatch(tag):
        raise ValueError(f"Invalid language tag: {value!r}")
    parts = tag.split("-")
    normalized = [parts[0].lower()]
    for part in parts[1:]:
        normalized.append(part.upper() if len(part) == 2 and part.isalpha() else part.title())
    return "-".join(normalized)
