"""Telemetry configuration dataclasses and builder.

.. deprecated::
    This module exists for backward compatibility with callers that still use
    setup_telemetry() / setup_telemetry_from_config().  New code should use
    init_supervision() which configures t_obs directly via ObsConfig.
"""

import logging
from dataclasses import dataclass
from typing import Any, Dict, Optional

logger = logging.getLogger(__name__)


@dataclass
class TelemetryConfig:
    """Backward-compat configuration for setup_telemetry().

    .. deprecated::
        Use init_supervision() instead. This class will be removed when the
        deprecated setup_telemetry() path is deleted.
    """

    service_name: str
    manifest: Optional[Any] = None
    # Deprecated: endpoint and auth_headers are now handled by t_obs/ObsConfig.
    endpoint: Optional[str] = None
    auth_headers: Optional[Dict[str, str]] = None
    # Deprecated: t_obs enables all signals by default. These toggles are
    # retained only for backward compatibility and are not honored by the
    # live init_supervision() path.
    enable_tracing: bool = True
    enable_metrics: bool = True
    enable_logging: bool = True
    resource_attributes: Optional[Dict[str, Any]] = None


class TelemetryConfigBuilder:
    """Builder for creating TelemetryConfig with proper defaults and validation.

    .. deprecated::
        Use init_supervision() instead.
    """

    def __init__(self):
        self._config = TelemetryConfig(service_name="")

    def with_service_name(self, name: str) -> "TelemetryConfigBuilder":
        """Set the service name."""
        self._config.service_name = name
        return self

    def with_manifest(self, manifest: Any) -> "TelemetryConfigBuilder":
        """Set the manifest object."""
        self._config.manifest = manifest
        return self

    def with_otlp_config(
        self, otlp_config: Optional[Dict[str, Any]]
    ) -> "TelemetryConfigBuilder":
        """Set endpoint and headers from OTLP config dict."""
        if not otlp_config:
            return self

        # Extract endpoint (prefer general endpoint, fallback to type-specific)
        self._config.endpoint = (
            otlp_config.get("endpoint")
            or otlp_config.get("traces_endpoint")
            or otlp_config.get("logs_endpoint")
            or otlp_config.get("metrics_endpoint")
        )

        # Extract headers
        if "headers" in otlp_config:
            self._config.auth_headers = otlp_config["headers"]

        return self

    def with_feature_toggles(self, **toggles) -> "TelemetryConfigBuilder":
        """Set feature toggles."""
        for key, value in toggles.items():
            if hasattr(self._config, key):
                setattr(self._config, key, value)
        return self

    def build(self) -> TelemetryConfig:
        """Build and validate the configuration."""
        self._validate()
        return self._config

    def _validate(self) -> None:
        """Validate the configuration."""
        # Extract service name from manifest if available (use full UID)
        if (
            self._config.manifest
            and hasattr(self._config.manifest, "uid")
            and self._config.manifest.uid
        ):
            self._config.service_name = self._config.manifest.uid

        if not self._config.service_name:
            raise ValueError("Service name is required")
