from __future__ import annotations

import re

from src.errors import UserError

_WHITESPACE_RE = re.compile(r"\s+")

_INVALID_CHARS = '<>:"/\\|?*'
_RESERVED = {
    "CON",
    "PRN",
    "AUX",
    "NUL",
    "COM1",
    "COM2",
    "COM3",
    "COM4",
    "COM5",
    "COM6",
    "COM7",
    "COM8",
    "COM9",
    "LPT1",
    "LPT2",
    "LPT3",
    "LPT4",
    "LPT5",
    "LPT6",
    "LPT7",
    "LPT8",
    "LPT9",
}


def normalize_folder_component(value: str, *, label: str) -> str:
    text = _WHITESPACE_RE.sub(" ", str(value).strip()).strip(",").strip()
    if not text:
        raise UserError(f"Missing {label}.")
    for ch in _INVALID_CHARS:
        text = text.replace(ch, "-")
    text = text.rstrip(" .")
    if not text:
        raise UserError(f"{label} becomes empty after normalization.")
    if text.upper() in _RESERVED:
        text = f"{text}_"
    return text
