import json
import httpx
import logging
from typing import Optional, Dict
from ..interfaces import MetricProvider
from ..utils import get_logger

class SumologicProvider(MetricProvider):
    def __init__(
        self,
        sumologic_url: str = None,
        timeout: int = 29,
        logger: Optional[logging.Logger] = None
    ):
        self.sumologic_url = sumologic_url
        self.timeout = timeout  # seconds
        self.logger = logger or get_logger(__name__)

    def send(self, *args, **kwargs):
        """
        Unified send method for Sumologic.
        Converts Datadog-style arguments to a JSON payload for Sumo Logic.
        """
        if not self.sumologic_url:
            self.logger.warning("Sumologic URL is not configured. Metrics will be dropped.")
            return

        metric_type = kwargs.pop('metric_type', None)

        if metric_type == 'event':
            self._log_event(*args, **kwargs)
        else:
            self._metric(*args, **kwargs)

    def _send(self, payload: Dict):
        """
        Send payload to sumologic
        """
        self.logger.info("Sending JSON payload to Sumologic: %s", json.dumps(payload, default=str))
        httpx.post(self.sumologic_url, json=payload, timeout=self.timeout)

    def _log_event(self, event_name: str, message: str, tags: Optional[Dict[str, str]] = None, event_type: str = "info", **kwargs):
        """
        Log an event to Sumologic.
        """
        safe_tags = tags or {}
        payload = {
            "event": event_name,
            "type": event_type,
            "message": message,
            **safe_tags,
        }
        try:
            self._send(payload)
            return True
        except Exception as e:
            self.logger.error("Error sending event to Sumologic: %s", str(e))
            return False

    def _metric(self, metric: str, value: int = 1, tags: Optional[Dict[str, str]] = None, **kwargs):
        """
        Send metric to sumologic
        """
        safe_tags = tags or {}
        payload = {
            "type": "info",
            "event": metric,
            "value": value,
            **safe_tags,
        }
        try:
            self._send(payload)
            return True
        except Exception as e:
            self.logger.error("Error sending metric to Sumologic: %s", str(e))
            return False



