"""Dependency-free BestAgent telemetry client. Keep credentials on the server."""

import json
import random
import time
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener
from uuid import uuid4

ENDPOINT = "https://bestagent-ai.com/v1/telemetry/events"
USER_AGENT = "BestAgentResearchSDK/1.0 (+https://bestagent-ai.com/developers/telemetry/)"
OPTIONAL = {"error_category", "outcome_status", "outcome_source", "input_tokens",
            "output_tokens", "model_id", "cost_micros", "currency", "cost_source",
            "retry_count", "human_intervention", "feedback_score", "traffic_type"}
ALLOWED = OPTIONAL | {"schema_version", "event_id", "agent_id", "agent_version", "run_id",
                      "task_category", "task_complexity", "time_bucket", "duration_ms", "execution_status"}


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class TelemetryClient:
    def __init__(self, token, enabled=False):
        self.token = token
        self.enabled = enabled
        self.http = build_opener(NoRedirect())

    @staticmethod
    def event(agent_id, agent_version, task_category, task_complexity, *, duration_ms, execution_status, **metrics):
        if metrics.keys() - OPTIONAL:
            raise ValueError("Unsupported telemetry field")
        return {
            "schema_version": 1, "event_id": str(uuid4()), "run_id": str(uuid4()),
            "agent_id": agent_id, "agent_version": agent_version, "task_category": task_category,
            "task_complexity": task_complexity, "time_bucket": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:00:00Z"),
            "duration_ms": duration_ms, "execution_status": execution_status, "outcome_status": "unknown",
            **metrics,
        }

    def send(self, events):
        if not self.enabled:
            return {"status": "disabled"}
        if not isinstance(events, (list, tuple)) or not 1 <= len(events) <= 50:
            return {"status": "invalid_batch"}
        if any(not isinstance(event, dict) or event.keys() - ALLOWED for event in events):
            return {"status": "invalid_batch"}
        try:
            payload = json.dumps({"events": events}, allow_nan=False).encode("utf-8")
        except (TypeError, ValueError):
            return {"status": "invalid_batch"}
        if len(payload) > 65536:
            return {"status": "invalid_batch"}
        request = Request(ENDPOINT, data=payload, headers={"Authorization": "Bearer " + self.token,
                                                          "Content-Type": "application/json", "User-Agent": USER_AGENT})
        for attempt in range(3):
            try:
                with self.http.open(request, timeout=3) as response:
                    return {"status": "ok", **json.load(response)}
            except HTTPError as exc:
                if exc.code == 429:
                    return {"status": "rate_limited", "retry_after": exc.headers.get("Retry-After", "3600")}
                if exc.code < 500:
                    return {"status": "rejected", "http_status": exc.code}
            except (URLError, OSError, ValueError):
                pass
            if attempt < 2:
                time.sleep((0.2 * 2**attempt) + random.uniform(0, 0.1))
        return {"status": "unavailable"}
