import asyncio
import json
import logging
from typing import Any, Dict, Optional

try:
    import requests
except ImportError:
    requests = None

from jazzmine.logging.exceptions import LoggerDependencyError


class SyncHTTPHandler(logging.Handler):
    def __init__(self, url: str, method: str = "POST", headers: Optional[Dict[str, str]] = None, timeout: float = 2.0):
        super().__init__()
        if requests is None:
            raise LoggerDependencyError("requests is required for sync http sinks (pip install requests)")
        self.url = url
        self.method = method.upper()
        self.headers = headers or {}
        self.timeout = timeout

    def emit(self, record: logging.LogRecord) -> None:
        try:
            payload: Any
            if isinstance(record.msg, (dict, list)):
                payload = record.msg
            else:
                try:
                    payload = json.loads(record.getMessage())
                except Exception:
                    payload = {"message": record.getMessage(), "level": record.levelname}
            
            try:
                loop = asyncio.get_running_loop()
                asyncio.run_coroutine_threadsafe(asyncio.to_thread(self._post, payload), loop)
            except RuntimeError:
                self._post(payload)
        except Exception:
            self.handleError(record)

    def _post(self, payload: Any) -> None:
        try:
            if self.method == "POST":
                requests.post(self.url, json=payload, headers=self.headers, timeout=self.timeout)
            else:
                requests.request(self.method, self.url, json=payload, headers=self.headers, timeout=self.timeout)
        except Exception:
            pass
