"""Lightweight async Slack poster for admin alerts.

Uses the Bot User OAuth Token (``SLACK_BOT_TOKEN``) and channel IDs to fan out
notifications to the right Slack channels.  Falls back gracefully when env vars
are missing or the API is unreachable — alerts should never block the caller.
"""

from __future__ import annotations

import logging
import os
from typing import Optional

import httpx

log = logging.getLogger(__name__)

_SLACK_POST_URL = "https://slack.com/api/chat.postMessage"
_TIMEOUT = httpx.Timeout(10.0, connect=5.0)


def _get_bot_token() -> Optional[str]:
    return os.getenv("SLACK_BOT_TOKEN") or None


def _get_channel(env_key: str) -> Optional[str]:
    return os.getenv(env_key) or None


async def post_message(
    *,
    channel_id: str,
    text: str,
    bot_token: Optional[str] = None,
) -> bool:
    """Post a plain-text message to a Slack channel.  Returns True on success."""
    token = bot_token or _get_bot_token()
    if not token:
        log.debug("SLACK_BOT_TOKEN not set; skipping Slack post")
        return False

    try:
        async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
            resp = await client.post(
                _SLACK_POST_URL,
                headers={
                    "Authorization": f"Bearer {token}",
                    "Content-Type": "application/json; charset=utf-8",
                },
                json={"channel": channel_id, "text": text},
            )
            data = resp.json()
            if not data.get("ok"):
                log.warning(
                    "Slack API error for channel %s: %s",
                    channel_id,
                    data.get("error", "unknown"),
                )
                return False
            return True
    except Exception as exc:
        log.warning("Slack post failed for channel %s: %s", channel_id, exc)
        return False


# ── Channel-specific helpers ───────────────────────────────────────────────


async def notify_beta_channel(text: str) -> bool:
    """Post to #beta-signups."""
    channel = _get_channel("SLACK_BETA_CHANNEL_ID")
    if not channel:
        return False
    return await post_message(channel_id=channel, text=text)


async def notify_support_channel(text: str) -> bool:
    """Post to #support-alerts."""
    channel = _get_channel("SLACK_SUPPORT_CHANNEL_ID")
    if not channel:
        return False
    return await post_message(channel_id=channel, text=text)


async def notify_growth_channel(text: str) -> bool:
    """Post to #growth-attribution (optional)."""
    channel = _get_channel("SLACK_GROWTH_CHANNEL_ID")
    if not channel:
        return False
    return await post_message(channel_id=channel, text=text)
