"""Command text parsing — extracts command name, arguments, and optional count."""

from __future__ import annotations


def parse_command(text: str) -> tuple[str, str, int | None]:
    """Parse a command message into (command, args, count).

    Examples:
        "/search sunset"       -> ("search", "sunset", None)
        "/latest Family 5"     -> ("latest", "Family", 5)
        "/events 10"           -> ("events", "", 10)
        "/help@mybot"          -> ("help", "", None)
    """
    text = text[:512].strip()
    if not text.startswith("/"):
        return ("", text, None)

    # Strip @botname suffix: /command@botname args
    parts = text[1:].split(None, 1)
    cmd = parts[0].split("@")[0].lower()
    rest = parts[1] if len(parts) > 1 else ""

    # Try to extract trailing count
    count = None
    rest_parts = rest.rsplit(None, 1)
    if len(rest_parts) == 2:
        try:
            count = int(rest_parts[1])
            rest = rest_parts[0]
        except ValueError:
            pass
    elif rest_parts and rest_parts[0]:
        try:
            count = int(rest_parts[0])
            rest = ""
        except ValueError:
            pass

    return (cmd, rest.strip(), count)
