"""Webhook notification module."""

import requests
import logging
from typing import Dict, Any

logger = logging.getLogger(__name__)


class WebhookNotifier:
    """Sends notifications to webhooks."""
    
    def __init__(self, webhook_url: str):
        """Initialize notifier.
        
        Args:
            webhook_url: Webhook URL to send notifications to
        """
        self.webhook_url = webhook_url
    
    def send_summary(self, summary: str, repo_name: str, branch: str) -> bool:
        """Send summary to webhook.
        
        Args:
            summary: Markdown formatted summary
            repo_name: Repository name
            branch: Branch name
            
        Returns:
            True if successful, False otherwise
        """
        try:
            payload = {
                "repository": repo_name,
                "branch": branch,
                "summary": summary,
                "type": "commit_summary"
            }
            
            response = requests.post(
                self.webhook_url,
                json=payload,
                headers={"Content-Type": "application/json"},
                timeout=30
            )
            
            response.raise_for_status()
            logger.info(f"Successfully sent summary to webhook for {repo_name}/{branch}")
            return True
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to send summary to webhook: {e}")
            return False
    
    def send_markdown_webhook(self, summary: str, repo_name: str, branch: str,
                            webhook_type: str = "generic") -> bool:
        """Send summary in various webhook formats.
        
        Args:
            summary: Markdown formatted summary
            repo_name: Repository name
            branch: Branch name
            webhook_type: Type of webhook (generic, slack, discord, feishu)
            
        Returns:
            True if successful, False otherwise
        """
        if webhook_type == "slack":
            return self._send_slack(summary, repo_name, branch)
        elif webhook_type == "discord":
            return self._send_discord(summary, repo_name, branch)
        elif webhook_type == "feishu":
            return self._send_feishu(summary, repo_name, branch)
        else:
            return self.send_summary(summary, repo_name, branch)
    
    def _send_slack(self, summary: str, repo_name: str, branch: str) -> bool:
        """Send to Slack webhook.
        
        Args:
            summary: Summary text
            repo_name: Repository name
            branch: Branch name
            
        Returns:
            True if successful, False otherwise
        """
        try:
            payload = {
                "text": f"*{repo_name}/{branch}* - 每日提交汇总",
                "blocks": [
                    {
                        "type": "section",
                        "text": {
                            "type": "mrkdwn",
                            "text": summary[:3000]  # Slack has a limit
                        }
                    }
                ]
            }
            
            response = requests.post(
                self.webhook_url,
                json=payload,
                timeout=30
            )
            
            response.raise_for_status()
            return True
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to send to Slack: {e}")
            return False
    
    def _send_discord(self, summary: str, repo_name: str, branch: str) -> bool:
        """Send to Discord webhook.
        
        Args:
            summary: Summary text
            repo_name: Repository name
            branch: Branch name
            
        Returns:
            True if successful, False otherwise
        """
        try:
            payload = {
                "content": f"**{repo_name}/{branch}** - 每日提交汇总",
                "embeds": [
                    {
                        "description": summary[:4000],  # Discord embed limit
                        "color": 5814783
                    }
                ]
            }
            
            response = requests.post(
                self.webhook_url,
                json=payload,
                timeout=30
            )
            
            response.raise_for_status()
            return True
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to send to Discord: {e}")
            return False
    
    def _send_feishu(self, summary: str, repo_name: str, branch: str) -> bool:
        """Send to Feishu (Lark) webhook.
        
        Args:
            summary: Summary text
            repo_name: Repository name
            branch: Branch name
            
        Returns:
            True if successful, False otherwise
        """
        try:
            payload = {
                "msg_type": "post",
                "content": {
                    "post": {
                        "zh_cn": {
                            "title": f"{repo_name}/{branch} - 每日提交汇总",
                            "content": [
                                [
                                    {
                                        "tag": "text",
                                        "text": summary
                                    }
                                ]
                            ]
                        }
                    }
                }
            }
            
            response = requests.post(
                self.webhook_url,
                json=payload,
                timeout=30
            )
            
            response.raise_for_status()
            return True
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to send to Feishu: {e}")
            return False
