import re
from pathlib import Path


def extract_number(file_path: str) -> str:
    name = Path(file_path).name
    stem = re.sub(r"\.[A-Za-z0-9]+$", "", name)
    normalized = stem.lower()
    compact = re.sub(r"[\s._-]+", "", normalized)

    # Handle compact forms like ABC123C / ABC123CHS and normalize to abc-123.
    compact_match = re.search(r"([a-z]{2,10})(\d{2,6})(?:cd\d+|c|ch|chs|cht)?$", compact)
    if compact_match:
        prefix = compact_match.group(1)
        digits = _normalize_digits(compact_match.group(2))
        return f"{prefix}-{digits}"

    normalized = normalized.replace("_", "-")
    normalized = re.sub(r"-(?:c|cd\d+)$", "", normalized)
    match = re.search(r"([a-z]{2,10})-(\d{2,6})", normalized)
    if match:
        prefix = match.group(1)
        digits = _normalize_digits(match.group(2))
        return f"{prefix}-{digits}"

    raise ValueError(f"Cannot extract number from file name: {name}")


def _normalize_digits(digits: str) -> str:
    # If extra width beyond 3 digits is only leading zero padding, fold back to 3-digit form.
    if len(digits) > 3:
        leading = digits[: len(digits) - 3]
        if set(leading) == {"0"}:
            return str(int(digits)).zfill(3)
    return digits
