"""Slack notification helpers for Autopilot."""

from __future__ import annotations

import os
from typing import Any, Dict

from .contracts import PlanV1, ReceiptV1
from .slack_blocks import build_plan_approval_blocks

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


def _ensure_slack() -> None:
    if WebClient is None:  # pragma: no cover
        raise RuntimeError("slack-sdk is required for Slack notifications.") from _slack_import_error


def create_client(bot_token: str) -> "WebClient":
    _ensure_slack()
    return WebClient(token=bot_token)


def resolve_channel(policy_defaults: Any) -> str | None:
    return policy_defaults.slack_channel or os.getenv("G_GREMLIN_SLACK_CHANNEL")


def post_approval_request(
    web_client: Any,
    channel: str,
    plan: PlanV1,
    approve_token: str,
) -> Dict[str, Any]:
    blocks = build_plan_approval_blocks(plan, approve_token)
    text = f"Autopilot approval required for run {plan.run_id}"
    return web_client.chat_postMessage(channel=channel, text=text, **blocks)


def post_receipt_summary(
    web_client: Any,
    channel: str,
    receipt: ReceiptV1,
) -> Dict[str, Any]:
    changes_count = len(receipt.changes or [])
    blocks = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": "Autopilot Receipt"},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Run:* {receipt.run_id}\n"
                    f"*Outcome:* {receipt.outcome}\n"
                    f"*Changes:* {changes_count}"
                ),
            },
        },
    ]
    text = f"Autopilot run {receipt.run_id} completed: {receipt.outcome}"
    return web_client.chat_postMessage(channel=channel, text=text, blocks=blocks)


__all__ = ["create_client", "resolve_channel", "post_approval_request", "post_receipt_summary"]
