"""Webhooks resource."""

import hmac
import hashlib
import json
from typing import Dict, Any, Optional
from ..http_client import HttpClient


class Webhooks:
    """Webhooks resource."""

    def __init__(self, http: HttpClient):
        self.http = http

    def get_settings(self) -> Dict[str, Any]:
        """Get webhook settings.
        
        Returns:
            Webhook settings dictionary
        """
        return self.http.get("/webhooks/settings")

    def update_settings(
        self,
        webhook_url: Optional[str] = None,
        enabled: Optional[bool] = None,
    ) -> Dict[str, Any]:
        """Update webhook settings.
        
        Args:
            webhook_url: New webhook URL
            enabled: Enable or disable webhooks
            
        Returns:
            Updated webhook settings dictionary
        """
        data = {}
        if webhook_url is not None:
            data["webhookUrl"] = webhook_url
        if enabled is not None:
            data["enabled"] = enabled

        return self.http.post("/webhooks/settings", data=data)

    def get_logs(self) -> list:
        """Get webhook logs.
        
        Returns:
            List of webhook log dictionaries
        """
        return self.http.get("/webhooks/logs")

    def test(self) -> Dict[str, Any]:
        """Test webhook delivery.
        
        Returns:
            Test webhook response
        """
        return self.http.post("/webhooks/test")

    def regenerate_secret(self) -> Dict[str, Any]:
        """Regenerate webhook secret.
        
        Returns:
            Dictionary containing new webhook secret
        """
        return self.http.post("/webhooks/regenerate-secret")

    @staticmethod
    def verify(payload: Any, signature: str, secret: str) -> bool:
        """Verify webhook signature.
        
        Args:
            payload: The webhook payload (dict or string)
            signature: The signature from x-lipana-signature header
            secret: Your webhook secret
            
        Returns:
            True if signature is valid, False otherwise
        """
        try:
            if isinstance(payload, dict):
                payload_string = json.dumps(payload, sort_keys=True)
            else:
                payload_string = str(payload)

            expected_signature = hmac.new(
                secret.encode("utf-8"),
                payload_string.encode("utf-8"),
                hashlib.sha256,
            ).hexdigest()

            return hmac.compare_digest(expected_signature, signature)
        except Exception:
            return False

