"""Slack Socket Mode transport (optional)."""

from __future__ import annotations

from threading import Event
from typing import Any, Callable

try:  # Optional dependency in some environments.
    from slack_sdk import WebClient
    from slack_sdk.socket_mode import SocketModeClient
except Exception as exc:  # pragma: no cover
    WebClient = None  # type: ignore
    SocketModeClient = None  # type: ignore
    _slack_import_error = exc
else:  # pragma: no cover - no error path when dependency present
    _slack_import_error = None


class SlackSocketModeRunner:
    def __init__(self, app_token: str, bot_token: str, handler: Callable[[dict[str, Any]], None]):
        if SocketModeClient is None or WebClient is None:  # pragma: no cover
            raise RuntimeError("slack-sdk is required for Socket Mode.") from _slack_import_error
        self._handler = handler
        self._client = SocketModeClient(
            app_token=app_token,
            web_client=WebClient(token=bot_token),
        )
        self._client.socket_mode_request_listeners.append(self._on_request)

    def _on_request(self, _client: Any, req: Any) -> None:
        if req.type == "interactive":
            payload = req.payload
            try:
                self._handler(payload)
            finally:
                self._client.send_socket_mode_response({"envelope_id": req.envelope_id})
        else:
            self._client.send_socket_mode_response({"envelope_id": req.envelope_id})

    def start(self) -> None:
        self._client.connect()
        Event().wait()


__all__ = ["SlackSocketModeRunner"]
