"""
Thread-local context management for releaseops telemetry.

Stores bundle metadata in contextvars so it's available throughout
execution without explicit passing.
"""

from __future__ import annotations

import logging
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Generator, Optional

from llmhq_releaseops.telemetry.models import TelemetryContext

logger = logging.getLogger(__name__)

_bundle_metadata: ContextVar[Optional[TelemetryContext]] = ContextVar(
    "releaseops_bundle_metadata", default=None
)


def set_bundle_metadata(metadata: TelemetryContext) -> None:
    """Store metadata in the current context."""
    current = _bundle_metadata.get()
    if current is not None:
        logger.warning(
            "Overriding existing bundle metadata in context "
            f"(was {current.bundle_id}@{current.environment}, "
            f"now {metadata.bundle_id}@{metadata.environment})"
        )
    _bundle_metadata.set(metadata)


def get_bundle_metadata() -> Optional[TelemetryContext]:
    """Retrieve metadata from the current context, or None if not set."""
    return _bundle_metadata.get()


def clear_bundle_metadata() -> None:
    """Remove metadata from the current context."""
    _bundle_metadata.set(None)


@contextmanager
def bundle_context(
    metadata: TelemetryContext,
) -> Generator[TelemetryContext, None, None]:
    """
    Context manager that sets metadata on entry and clears on exit.

    Usage:
        with bundle_context(metadata):
            agent.run()  # metadata available via get_bundle_metadata()
        # metadata cleared automatically
    """
    token = _bundle_metadata.set(metadata)
    try:
        yield metadata
    finally:
        _bundle_metadata.reset(token)
