"""Telemetry configuration management."""

from __future__ import annotations

import os
from dataclasses import dataclass, field
from typing import Any


@dataclass
class TelemetryConfig:
    """Configuration for telemetry reporting."""

    # Required
    api_key: str | None = None

    # Connection
    base_url: str = "https://api.rotascale.com"
    timeout: float = 5.0

    # Feature flags
    enabled: bool = False
    send_content: bool = False  # Whether to send prompt/response text
    send_metadata: bool = True  # Whether to send model, tokens, latency

    # Batching
    batch_size: int = 100
    flush_interval: float = 10.0  # seconds
    max_queue_size: int = 1000

    # Sampling
    sample_rate: float = 1.0  # 0.0-1.0

    # Filtering
    exclude_models: list[str] = field(default_factory=list)

    # Package info (set automatically)
    package_name: str = "rotalabs"
    package_version: str = "unknown"

    # Custom metadata
    metadata: dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_env(cls) -> "TelemetryConfig":
        """Load configuration from environment variables."""
        return cls(
            api_key=os.environ.get("ROTASCALE_API_KEY"),
            base_url=os.environ.get("ROTASCALE_BASE_URL", "https://api.rotascale.com"),
            enabled=os.environ.get("ROTASCALE_TELEMETRY_ENABLED", "").lower() == "true",
            send_content=os.environ.get("ROTASCALE_SEND_CONTENT", "").lower() == "true",
            sample_rate=float(os.environ.get("ROTASCALE_SAMPLE_RATE", "1.0")),
        )


# Global configuration instance
_config: TelemetryConfig | None = None


def configure(
    api_key: str | None = None,
    base_url: str | None = None,
    enabled: bool = True,
    send_content: bool = False,
    send_metadata: bool = True,
    batch_size: int = 100,
    flush_interval: float = 10.0,
    max_queue_size: int = 1000,
    sample_rate: float = 1.0,
    exclude_models: list[str] | None = None,
    package_name: str = "rotalabs",
    package_version: str = "unknown",
    metadata: dict[str, Any] | None = None,
) -> None:
    """Configure telemetry reporting.

    Args:
        api_key: Rotascale API key. Required if enabled=True.
        base_url: Rotascale API base URL.
        enabled: Whether to enable telemetry. Default True when configure() is called.
        send_content: Whether to send prompt/response text. Default False.
        send_metadata: Whether to send model, tokens, latency. Default True.
        batch_size: Number of events per batch.
        flush_interval: Seconds between batch flushes.
        max_queue_size: Maximum events to queue before dropping.
        sample_rate: Fraction of events to sample (0.0-1.0).
        exclude_models: Model names to exclude from telemetry.
        package_name: Name of the package (e.g., "rotalabs-steer").
        package_version: Version of the package.
        metadata: Custom metadata to attach to all events.
    """
    global _config

    # Load from environment first, then override with arguments
    _config = TelemetryConfig.from_env()

    if api_key is not None:
        _config.api_key = api_key
    if base_url is not None:
        _config.base_url = base_url
    _config.enabled = enabled
    _config.send_content = send_content
    _config.send_metadata = send_metadata
    _config.batch_size = batch_size
    _config.flush_interval = flush_interval
    _config.max_queue_size = max_queue_size
    _config.sample_rate = sample_rate
    if exclude_models is not None:
        _config.exclude_models = exclude_models
    _config.package_name = package_name
    _config.package_version = package_version
    if metadata is not None:
        _config.metadata = metadata

    # Validate
    if _config.enabled and not _config.api_key:
        raise ValueError(
            "API key required when telemetry is enabled. "
            "Pass api_key or set ROTASCALE_API_KEY environment variable."
        )


def disable() -> None:
    """Disable telemetry reporting."""
    global _config
    if _config is not None:
        _config.enabled = False
    else:
        _config = TelemetryConfig(enabled=False)


def is_enabled() -> bool:
    """Check if telemetry is enabled."""
    if _config is None:
        return False
    return _config.enabled and _config.api_key is not None


def get_config() -> TelemetryConfig | None:
    """Get the current telemetry configuration."""
    return _config
