"""ResourceProvider for managing OTel resource attributes.

Provides resource attributes (service.name, service.version,
deployment.environment, and custom attributes) that are attached to every
LogRecord produced by the logging bridge.

If ``service.name`` is not supplied, it defaults to ``"unknown_service"``.
"""

from __future__ import annotations

import os
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, Optional


@dataclass
class ResourceConfig:
    """Configuration for resource attributes.

    Attributes:
        service_name:           Service name (default ``"unknown_service"``).
        service_version:        Optional service version string.
        deployment_environment: Optional deployment environment (e.g. ``"production"``).
        custom_attributes:      Optional dict of additional resource key-value pairs.
    """

    service_name: str = "unknown_service"
    service_version: Optional[str] = None
    deployment_environment: Optional[str] = None
    custom_attributes: Optional[Dict[str, Any]] = None


class ResourceProvider:
    """Builds resource attribute dicts from a :class:`ResourceConfig`.

    Always includes ``service.name`` in the returned resource dict.
    Optional fields are included only when set.  Custom attributes are
    merged in and can use arbitrary keys.
    """

    def __init__(self, config: Optional[ResourceConfig] = None) -> None:
        self._config = config or ResourceConfig()

    @property
    def config(self) -> ResourceConfig:
        """Return the current resource configuration."""
        return self._config

    def get_resource(self) -> Dict[str, Any]:
        """Return resource attributes dict.

        The dict always contains ``"service.name"``.  ``"service.version"``
        and ``"deployment.environment"`` are included when configured.
        Any ``custom_attributes`` are merged into the result.

        Returns:
            A dict of resource attribute key-value pairs.
        """
        resource: Dict[str, Any] = {
            "service.name": self._config.service_name,
        }

        if self._config.service_version is not None:
            resource["service.version"] = self._config.service_version

        if self._config.deployment_environment is not None:
            resource["deployment.environment"] = self._config.deployment_environment

        if self._config.custom_attributes:
            resource.update(self._config.custom_attributes)

        return resource

    @staticmethod
    def parse_otel_resource_attributes() -> Dict[str, str]:
        """Parse ``OTEL_RESOURCE_ATTRIBUTES`` env var into a dict.

        The env var contains comma-separated ``key=value`` pairs.
        Malformed pairs (those without ``=``) are skipped with a warning
        to stderr.  Whitespace is trimmed from keys and values.
        Values containing ``=`` are handled correctly via ``split("=", 1)``.

        Returns:
            A dict of parsed resource attribute key-value pairs.
        """
        raw = os.environ.get("OTEL_RESOURCE_ATTRIBUTES", "")
        if not raw:
            return {}
        result: Dict[str, str] = {}
        for pair in raw.split(","):
            if "=" in pair:
                key, value = pair.split("=", 1)
                result[key.strip()] = value.strip()
            else:
                print(
                    f"Warning: skipping malformed OTEL_RESOURCE_ATTRIBUTES pair: '{pair.strip()}'",
                    file=sys.stderr,
                )
        return result
