from typing import Any

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

PROVIDER_NAME = "custom"
STRING_KEY = "url"


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


def _build_payload(
    message: Message,
    title: str | None = None,
    context: dict | None = None,
    message_key: str = "text",
) -> dict[str, Any]:
    """Construct a message payload to send to the custom endpoint.

    Args:
        message: Message object.
        title: Optional title to display with the message.
        context: Optional partial message payload. Message contents will be added.
        message_key: Key which marks the main message body on the target endpoint.

    Returns:
        Message payload as a dictionary.
    """
    title = title or message.title
    text: str = message.text

    if title:
        text = f"{title}\n{text}"

    payload = dict(context or {})
    payload.setdefault(message_key, text)
    return payload


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