import json
import logging
import threading
import time
from typing import Optional

import requests

logger = logging.getLogger("agentmetrics")


class HttpClient:
    def __init__(self, api_key: str, base_url: str):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self._pending_threads: list[threading.Thread] = []
        self._lock = threading.Lock()

    def fire_and_forget(self, payload: dict) -> None:
        """Post event in a background thread. Never blocks. Never raises."""
        t = threading.Thread(target=self._post_with_retry, args=(payload,), daemon=True)
        with self._lock:
            self._pending_threads.append(t)
        t.start()

    def _post_with_retry(self, payload: dict, retries: int = 3) -> None:
        url = f"{self.base_url}/events"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }
        for attempt in range(retries):
            try:
                resp = requests.post(url, json=payload, headers=headers, timeout=5)
                if resp.status_code in (200, 201):
                    return
                logger.debug("AgentMetrics: non-2xx response %s", resp.status_code)
            except Exception as exc:
                logger.debug("AgentMetrics: send failed (attempt %d): %s", attempt + 1, exc)
                if attempt < retries - 1:
                    time.sleep(1)

    def flush(self, timeout: float = 10.0) -> None:
        """Wait for all in-flight events to complete. Useful in tests and shutdown."""
        with self._lock:
            threads = list(self._pending_threads)
        for t in threads:
            t.join(timeout=timeout)
        with self._lock:
            self._pending_threads = [t for t in self._pending_threads if t.is_alive()]
