"""Fire-and-forget PostHog analytics for the Velar SDK.

All calls are best-effort — any exception is silently swallowed so
analytics never breaks user workflows.
"""

from __future__ import annotations

import os
import threading
from typing import Any

_client = None
_lock = threading.Lock()


def _get_client():
    global _client
    if _client is not None:
        return _client
    with _lock:
        if _client is not None:
            return _client
        try:
            import posthog  # type: ignore

            key = os.environ.get("POSTHOG_TOKEN", "phc_zFL6BOx1E2rXx4pzPzTmOLFgUcyMv9IJ5W5FZd9jckJ")
            posthog.project_api_key = key
            posthog.host = "https://us.i.posthog.com"
            posthog.disabled = False
            # Silence posthog's own logging
            posthog.log.setLevel("CRITICAL")
            _client = posthog
        except Exception:
            _client = None
    return _client


def capture(distinct_id: str, event: str, props: dict[str, Any] | None = None) -> None:
    """Emit a PostHog event. Never raises."""
    def _send():
        try:
            ph = _get_client()
            if ph:
                ph.capture(distinct_id, event, props or {})
        except Exception:
            pass

    threading.Thread(target=_send, daemon=True).start()
