# Copyright (c) 2019 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

import json
from functools import partialmethod

import httpx

from src.utils.console import markdown_format
from src.utils.data import JSONSanity


class SlackWeb:
    """
    Handles sending messages to Slack via webhooks.
    """

    def __init__(self, webhook_url=None):
        """
        Initialize the Slack webhook client.

        Args:
            webhook_url: The Slack webhook URL
        """
        self.webhook_url = webhook_url
        self.response = None
        self.payload = None

    def notify(self, **kwargs):
        """
        Send message to slack API using kwargs for the payload.

        Returns:
            bool: Success status
        """
        if self.webhook_url is None:
            return False

        return self.send(kwargs)

    def send(self, payload):
        """
        Send payload to slack API.

        Args:
            payload: A properly formatted slack message object

        Returns:
            response: The HTTP response from Slack API
        """
        self.payload = json.dumps(payload, cls=JSONSanity)
        self.response = httpx.post(self.webhook_url, content=self.payload)
        return self.response

    def message(self, title, details, detail_title=None, color="#36A646"):
        """
        Send a formatted message to Slack.

        Args:
            title: Message title
            details: Message details (text or list of detail objects)
            detail_title: Optional title for details section
            color: Message color

        Returns:
            response: The HTTP response from Slack API
        """
        if not isinstance(details, list):
            details = [{"text": details}]

        formatted_attachments = []

        for detail in details:
            attachment = {
                "pretext": detail.get("title", detail_title),
                "color": detail.get("color", color),
                "text": markdown_format(detail.get("text")),
                "mrkdwn_in": ["text"],
            }
            formatted_attachments.append(attachment)

        return self.notify(text=f"*{title}*", mrkdwn=True, attachments=formatted_attachments)

    # Convenience methods for different message types
    info_message = partialmethod(message, color="#36A646")
    warning_message = partialmethod(message, color="#FFFF00")
    error_message = partialmethod(message, color="#e33a4f")
