from __future__ import annotations

import os
from typing import Literal


def resolve_trace_parent(value: str | Literal[False] | None) -> str | None:
    """Resolve trace parent with priority: explicit > OTel > env > None."""
    if value is False:
        return None
    if isinstance(value, str):
        return value
    # Auto-detect
    otel = _try_otel_context()
    if otel:
        return otel
    return os.environ.get("TRACEPARENT")


def _try_otel_context() -> str | None:
    """Try to extract traceparent from the current OpenTelemetry span."""
    try:
        from opentelemetry import trace

        span = trace.get_current_span()
        ctx = span.get_span_context()
        if ctx and ctx.trace_id and ctx.span_id:
            # Format as W3C traceparent
            trace_id = format(ctx.trace_id, "032x")
            span_id = format(ctx.span_id, "016x")
            flags = format(ctx.trace_flags, "02x")
            return f"00-{trace_id}-{span_id}-{flags}"
    except (ImportError, Exception):
        pass
    return None
