use opentelemetry::trace::TraceError;
use opentelemetry_sdk::trace::{Sampler, TracerProvider as SdkTracerProvider};

/// 创建带有采样率的追踪提供者
///
/// # 参数
///
/// * `sampling_rate` - 采样率，范围 [0.0, 1.0]
///   - 0.0: 不采样任何追踪
///   - 1.0: 采样所有追踪
///   - 0.5: 采样50%的追踪
///
/// # 示例
///
/// ```rust
/// use dbnexus::tracing::sampler::create_trace_provider_with_sampling;
///
/// // 采样50%的追踪
/// let provider = create_trace_provider_with_sampling(0.5).unwrap();
/// ```
///
/// # 返回
///
/// 返回一个配置了采样率的 `SdkTracerProvider`
pub fn create_trace_provider_with_sampling(sampling_rate: f64) -> Result<SdkTracerProvider, TraceError> {
    /// 采样率限制在 [0.0, 1.0] 范围内
    let clamped_rate = sampling_rate.clamp(0.0, 1.0);

    /// 创建基于TraceId比率的采样器
    let sampler = Sampler::TraceIdRatioBased(clamped_rate);

    /// 构建追踪提供者并配置采样器
    Ok(SdkTracerProvider::builder()
        .with_config(opentelemetry_sdk::trace::Config::default().with_sampler(sampler))
        .build())
}
