"""Slack webhook notifications for escalations and project events."""

from __future__ import annotations

import json
import logging
from urllib.request import Request, urlopen
from urllib.error import URLError

logger = logging.getLogger(__name__)

SEVERITY_COLORS = {
    "info": "#36a64f",      # green
    "warning": "#daa038",   # yellow
    "error": "#cc0000",     # red
}


async def send_slack_notification(
    webhook_url: str,
    message: str,
    task_id: str | None = None,
    severity: str = "info",
) -> bool:
    """Send a notification to Slack via incoming webhook.

    Uses stdlib urllib to avoid adding aiohttp/httpx as a dependency.
    Runs the blocking HTTP call in the default executor.

    Returns True if the message was sent successfully.
    """
    if not webhook_url:
        return False

    import asyncio

    color = SEVERITY_COLORS.get(severity, SEVERITY_COLORS["info"])

    fields = []
    if task_id:
        fields.append({"title": "Task ID", "value": f"`{task_id}`", "short": True})
    fields.append({"title": "Severity", "value": severity.upper(), "short": True})

    payload = {
        "attachments": [
            {
                "color": color,
                "text": message,
                "fields": fields,
                "footer": "Loom Orchestrator",
            }
        ]
    }

    def _send() -> bool:
        try:
            data = json.dumps(payload).encode("utf-8")
            req = Request(
                webhook_url,
                data=data,
                headers={"Content-Type": "application/json"},
            )
            with urlopen(req, timeout=10) as resp:
                return resp.status == 200
        except (URLError, OSError):
            logger.warning("Failed to send Slack notification", exc_info=True)
            return False

    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(None, _send)
