"""Helpers for Bitrix24 chat messaging."""

import re
from typing import Any

from .rest import request24

CHAT_ID_PATTERN = re.compile(r"^chat\d+$")


def to_chat(
        text: str,
        chat_id: str,
        webhook_url: str | None = None,
        ) -> dict[str, Any]:
    """Send a plain message to a Bitrix24 chat via im.message.add."""

    resolved_text = str(text).strip()
    resolved_chat_id = (chat_id or "").strip()

    if not resolved_text:
        raise ValueError("text is required.")

    if not resolved_chat_id:
        raise ValueError("chat_id is required.")
    if not CHAT_ID_PATTERN.fullmatch(resolved_chat_id):
        raise ValueError("chat_id must match format chat123.")

    params = {
        "DIALOG_ID": resolved_chat_id,
        "MESSAGE": resolved_text,
        "SYSTEM": "N",
        }

    return request24(
        method="im.message.add",
        parameters=params,
        webhook_url=webhook_url,
        )
