"""
Telemetry metadata extraction for releaseops.

Extracts metadata from bundles and makes it ready for injection
into observability traces.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from llmhq_releaseops.telemetry.models import TelemetryContext

if TYPE_CHECKING:
    from llmhq_releaseops.core.resolver import Resolver
    from llmhq_releaseops.models.bundle import BundleManifest

logger = logging.getLogger(__name__)


class TelemetryInjector:
    """
    Extracts metadata from bundles for telemetry injection.

    Stateless — no constructor state. Converts BundleManifest into
    TelemetryContext suitable for span attributes.
    """

    def extract_metadata(
        self, bundle: BundleManifest, environment: str
    ) -> TelemetryContext:
        """
        Extract telemetry metadata from a bundle manifest.

        Args:
            bundle: The bundle manifest to extract from.
            environment: Which environment (dev/staging/prod).

        Returns:
            TelemetryContext with all bundle metadata.
        """
        prompt_refs = {
            role: ref.ref for role, ref in bundle.prompts.items()
        }
        policy_refs = {
            role: ref.ref for role, ref in bundle.policies.items()
        }
        model_config = {}
        if bundle.model_config:
            model_config = bundle.model_config.to_dict()

        return TelemetryContext(
            bundle_id=bundle.id,
            bundle_version=bundle.version,
            bundle_hash=bundle.bundle_hash or "",
            environment=environment,
            prompt_refs=prompt_refs,
            policy_refs=policy_refs,
            model_config=model_config,
        )

    def extract_from_resolved_bundle(
        self, bundle_id: str, environment: str, resolver: Resolver
    ) -> TelemetryContext:
        """
        Convenience method: resolve bundle then extract metadata.

        Args:
            bundle_id: Bundle identifier.
            environment: Environment to resolve from.
            resolver: Resolver instance.

        Returns:
            TelemetryContext for the resolved bundle.

        Raises:
            ValueError: If bundle not found in environment.
            FileNotFoundError: If bundle manifest doesn't exist.
        """
        bundle = resolver.resolve(bundle_id, environment)
        return self.extract_metadata(bundle, environment)
