// {{ display_name }} MCP server — generated by mcpify. Do not hand-edit.
//
// Named `otel.rs` rather than `tracing.rs` (the name
// `targets::typescript`'s equivalent file uses) to avoid shadowing the
// `tracing` crate this whole project logs through.

use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::Resource;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing_subscriber::Layer;

use super::logger::BoxedLayer;

/// Builds the OpenTelemetry tracing bridge layer — REQ-2.3.2 — exported via
/// OTLP. Unlike `targets::typescript`'s `tracing.ts` (separate Jaeger trace
/// and Prometheus metrics exporters), this target exports over the single
/// OTLP wire protocol, which modern Jaeger/Prometheus deployments both
/// ingest via a collector; a deliberate simplification given this crate's
/// toolchain already includes `opentelemetry-otlp` and adding
/// exporter-specific crates for each backend isn't otherwise warranted.
///
/// Returns the layer (for `logger::init_logging` to compose into the one
/// global subscriber `tracing` allows) alongside the `SdkTracerProvider`
/// handle `shutdown_tracing` needs.
pub fn build_layer(service_name: &str) -> anyhow::Result<(BoxedLayer, SdkTracerProvider)> {
    // `.with_http()` rather than `.with_tonic()`: OTLP/HTTP is enabled by
    // `opentelemetry-otlp`'s default features, so this needs no extra
    // feature-flag wiring in Cargo.toml — gRPC would require opting into
    // the `grpc-tonic` feature for no benefit here.
    let exporter = opentelemetry_otlp::SpanExporter::builder()
        .with_http()
        .build()?;

    let provider = SdkTracerProvider::builder()
        .with_batch_exporter(exporter)
        .with_resource(
            Resource::builder()
                .with_service_name(service_name.to_string())
                .build(),
        )
        .build();

    let tracer = provider.tracer(service_name.to_string());
    let layer = tracing_opentelemetry::layer().with_tracer(tracer).boxed();

    Ok((layer, provider))
}

pub fn shutdown_tracing(provider: SdkTracerProvider) {
    if let Err(err) = provider.shutdown() {
        tracing::error!(error = %err, "failed to shut down OpenTelemetry tracer provider");
    }
}
