"""
aiel_sdk.integrations.slack.remote
==================================

Remote-backed Slack operations via the AIEL Integrations API.
"""

from __future__ import annotations

from typing import Any, Dict, Optional

from ...client import AielClient
from ...scope import ensure_non_empty, resolve_workspace_project
from .types import (
    DEFAULT_SLACK_CAPABILITIES,
    SlackAuthIdentity,
    SlackCapabilities,
    SlackPostMessageRequest,
    SlackPostMessageResult,
)

Json = Dict[str, Any]


class RemoteSlack:
    @property
    def capabilities(self) -> SlackCapabilities:
        return DEFAULT_SLACK_CAPABILITIES

    def __init__(
        self,
        client: AielClient,
        *,
        workspace_id: str | None = None,
        project_id: str | None = None,
        connection_id: str,
    ) -> None:
        self._c = client
        self._ws, self._proj = resolve_workspace_project(
            client,
            workspace_id=workspace_id,
            project_id=project_id,
        )
        self._conn = ensure_non_empty(connection_id, "connection_id")

    def _invoke(
        self,
        *,
        action: str,
        params: Optional[Json] = None,
        request_id: str | None = None,
    ) -> Any:
        return self._c.integrations.invoke_action(
            self._ws,
            self._proj,
            connection_id=self._conn,
            action=action,
            payload={"params": params or {}},
            request_id=request_id,
        )

    def auth_test(
        self,
        *,
        use_api_test: bool = False,
        request_id: str | None = None,
    ) -> SlackAuthIdentity:
        action = "slack.api_test" if use_api_test else "slack.auth_test"
        raw = self._invoke(action=action, params={}, request_id=request_id)
        return SlackAuthIdentity.from_json(raw if isinstance(raw, dict) else {"raw": raw})

    def post_message(
        self,
        req: SlackPostMessageRequest,
        *,
        request_id: str | None = None,
    ) -> SlackPostMessageResult:
        raw = self._invoke(action="slack.post_message", params=req.to_params(), request_id=request_id)
        return SlackPostMessageResult.from_json(raw if isinstance(raw, dict) else {"raw": raw})
