"""Slack integration for optional operational notifications."""

from __future__ import annotations

import logging
from typing import Any

import requests

logger = logging.getLogger(__name__)


class SlackIntegration:
    """Send optional KIESSCLAW notifications to Slack."""

    def __init__(self, webhook_url: str | None, bot_token: str | None):
        """Initialize webhook-based Slack notifier."""
        self.webhook_url = (webhook_url or "").strip()
        self.bot_token = (bot_token or "").strip()

    def notify(self, event: str, payload: dict[str, Any]) -> bool:
        """Post one event notification and return success state."""
        if not self.webhook_url:
            return False

        message: dict[str, Any]
        if event == "qualified_lead":
            message = self.format_lead_alert(
                contact=payload.get("contact"),
                icp_score=int(payload.get("icp_score") or 0),
                workflow=str(payload.get("workflow") or "outreach_sdr"),
            )
        elif event == "reply_received":
            message = self.format_reply_alert(
                contact=payload.get("contact"),
                intent=str(payload.get("intent") or "unknown"),
                text=str(payload.get("text_preview") or payload.get("text") or ""),
            )
        elif event == "workflow_complete":
            workflow = str(payload.get("usecase_id") or "workflow")
            enrolled = int(payload.get("enrolled") or 0)
            contacts_created = int(payload.get("contacts_created") or 0)
            errors = payload.get("errors") or []
            message = {
                "blocks": [
                    {
                        "type": "header",
                        "text": {"type": "plain_text", "text": "Workflow Complete", "emoji": True},
                    },
                    {
                        "type": "section",
                        "fields": [
                            {"type": "mrkdwn", "text": f"*Use Case:*\n`{workflow}`"},
                            {"type": "mrkdwn", "text": f"*Contacts Created:*\n{contacts_created}"},
                            {"type": "mrkdwn", "text": f"*Enrolled:*\n{enrolled}"},
                            {"type": "mrkdwn", "text": f"*Errors:*\n{len(errors)}"},
                        ],
                    },
                ]
            }
        else:
            message = {
                "blocks": [
                    {
                        "type": "section",
                        "text": {"type": "mrkdwn", "text": f"*KIESSCLAW Event:* `{event}`"},
                    }
                ]
            }

        try:
            response = requests.post(self.webhook_url, json=message, timeout=5)
            if response.status_code >= 400:
                logger.warning("[SlackIntegration] webhook returned %s for event=%s", response.status_code, event)
                return False
            return True
        except Exception as exc:  # noqa: BLE001
            logger.warning("[SlackIntegration] failed to notify event=%s: %s", event, exc)
            return False

    def format_lead_alert(self, contact: Any, icp_score: int, workflow: str) -> dict[str, Any]:
        """Format one qualified lead notification using Slack Block Kit."""
        contact_value = self._contact_label(contact)
        return {
            "blocks": [
                {
                    "type": "header",
                    "text": {"type": "plain_text", "text": "Qualified Lead", "emoji": True},
                },
                {
                    "type": "section",
                    "fields": [
                        {"type": "mrkdwn", "text": f"*Contact:*\n{contact_value}"},
                        {"type": "mrkdwn", "text": f"*ICP Score:*\n{icp_score}"},
                        {"type": "mrkdwn", "text": f"*Workflow:*\n`{workflow}`"},
                    ],
                },
            ]
        }

    def format_reply_alert(self, contact: Any, intent: str, text: str) -> dict[str, Any]:
        """Format one reply classification notification using Block Kit."""
        contact_value = self._contact_label(contact)
        preview = text.strip().replace("\n", " ")
        if len(preview) > 180:
            preview = preview[:177] + "..."
        return {
            "blocks": [
                {
                    "type": "header",
                    "text": {"type": "plain_text", "text": "Reply Received", "emoji": True},
                },
                {
                    "type": "section",
                    "fields": [
                        {"type": "mrkdwn", "text": f"*Contact:*\n{contact_value}"},
                        {"type": "mrkdwn", "text": f"*Intent:*\n`{intent}`"},
                    ],
                },
                {
                    "type": "section",
                    "text": {"type": "mrkdwn", "text": f"*Preview:*\n{preview or '(empty reply text)'}"},
                },
            ]
        }

    def _contact_label(self, contact: Any) -> str:
        """Return best-effort contact display label."""
        if isinstance(contact, str):
            return contact
        if isinstance(contact, dict):
            name = f"{contact.get('first_name', '')} {contact.get('last_name', '')}".strip()
            if name:
                return name
            if contact.get("email"):
                return str(contact["email"])
        return "Unknown contact"
