"""
Anonymous telemetry for A2RAG free tier.

What is sent (free tier):
  - action (answer/clarify/abstain)
  - confidence score
  - query_type (generic_policy/instance_specific)
  - language detected
  - latency_ms
  - a2rag_version

What is NEVER sent:
  - query content
  - contexts
  - draft answer
  - customer-specific metadata
  - any identifiable information

Paid tiers can disable telemetry: A2RAGClient(telemetry=False)
"""
from __future__ import annotations
import threading, json, urllib.request, logging

logger = logging.getLogger(__name__)
VERSION = "1.0.0"


class Telemetry:
    def __init__(self, api_key: str, enabled: bool = True, base_url: str = ""):
        self.enabled  = enabled
        self.base_url = base_url
        # Free tier identified by key prefix
        self._is_free = api_key.startswith("a2rag_sandbox_") or api_key.startswith("a2rag_free_")

    def record(self, decision) -> None:
        if not self.enabled or not self._is_free:
            return
        payload = {
            "action":      decision.action,
            "confidence":  round(decision.confidence, 3),
            "query_type":  decision.query_type,
            "language":    decision.language,
            "latency_ms":  decision.latency_ms,
            "version":     VERSION,
        }
        threading.Thread(
            target=self._send,
            args=(payload,),
            daemon=True,
        ).start()

    def _send(self, payload: dict) -> None:
        try:
            data = json.dumps(payload).encode()
            req = urllib.request.Request(
                f"{self.base_url}/telemetry",
                data=data,
                headers={"Content-Type": "application/json"},
                method="POST",
            )
            urllib.request.urlopen(req, timeout=3)
        except Exception:
            pass  # Telemetry failures are silent
