from typing import Any

from ..environment import CHIRPPY_SLACK_WEBHOOK
from ..models import Message
from ..utils.config import resolve_from_env
from .factory import make_provider

PROVIDER_NAME = "slack"
STRING_KEY = "url"


def _resolve_url(url: str | None = None) -> str:
    """Resolve Slack webhook URL from argument or environment variable."""
    return resolve_from_env(url, CHIRPPY_SLACK_WEBHOOK)


def _build_payload(message: Message, title: str | None = None) -> dict[str, Any]:
    """Construct a message payload to send to Slack.

    Args:
        message: Message object.
        title: Optional title to display with the message.

    Returns:
        Message payload as a dictionary.
    """
    text: str = message.text
    title = title or message.title
    if title:
        text = f"*{title}*\n{text}"

    return {"text": text}


send, async_send = make_provider(
    PROVIDER_NAME,
    resolve_url=_resolve_url,
    build_payload=_build_payload,
    string_key=STRING_KEY,
)
