import re

from .backend import InputBackend

KEY_COMMANDS: dict[str, list[str]] = {
    "new line": ["Return"],
    "newline": ["Return"],
    "enter": ["Return"],
    "press enter": ["Return"],
    "new paragraph": ["Return", "Return"],
    "tab": ["Tab"],
    "backspace": ["BackSpace"],
}

PUNCTUATION: dict[str, str] = {
    "question mark": "?",
    "exclamation mark": "!",
    "exclamation point": "!",
    "period": ".",
    "full stop": ".",
    "comma": ",",
    "colon": ":",
    "semicolon": ";",
    "open quote": '"',
    "close quote": '"',
    "open paren": "(",
    "close paren": ")",
}


def _build_pattern(commands: dict) -> re.Pattern:
    sorted_keys = sorted(commands.keys(), key=len, reverse=True)
    escaped = [re.escape(k) for k in sorted_keys]
    return re.compile(r"\b(" + "|".join(escaped) + r")\b", re.IGNORECASE)


_KEY_PATTERN = _build_pattern(KEY_COMMANDS)
_PUNCT_PATTERN = _build_pattern(PUNCTUATION)


def process_and_output(text: str, backend: InputBackend) -> None:
    text = _PUNCT_PATTERN.sub(lambda m: PUNCTUATION[m.group(1).lower()], text)
    text = re.sub(r"\s+([?.!,;:)\"])", r"\1", text)

    parts = _KEY_PATTERN.split(text)

    for part in parts:
        cmd = part.strip().lower()
        if cmd in KEY_COMMANDS:
            for key in KEY_COMMANDS[cmd]:
                backend.send_key(key)
        else:
            cleaned = part.strip()
            if cleaned:
                backend.type_text(cleaned + " ")
