use opentelemetry::KeyValue;
use opentelemetry::global;
use opentelemetry_otlp::{WithExportConfig, WithTonicConfig};
use opentelemetry_sdk::{Resource, logs, runtime};
use tonic::transport::{Channel, ClientTlsConfig};

pub fn init_telemetry() -> (
    opentelemetry_sdk::trace::TracerProvider,
    opentelemetry_sdk::logs::LoggerProvider,
) {
    let endpoint = "https://signoz.racooncity.org".to_string();
    let channel = Channel::from_shared(endpoint.clone())
        .unwrap()
        .tls_config(ClientTlsConfig::new().with_native_roots())
        .unwrap()
        .connect_lazy();
    let exporter = opentelemetry_otlp::SpanExporter::builder()
        .with_tonic()
        .with_endpoint(endpoint.clone())
        .with_channel(channel.clone())
        .build()
        .expect("Failed to Build Exporter");
    let log_exporter = opentelemetry_otlp::LogExporter::builder()
        .with_tonic()
        .with_endpoint(endpoint.clone())
        .with_channel(channel.clone())
        .build()
        .expect("Failed to build log exporter");
    let logger_provider = logs::LoggerProvider::builder()
        .with_resource(Resource::new(vec![KeyValue::new(
            "service.name",
            "RhythmWorks",
        )]))
        .with_batch_exporter(log_exporter, runtime::Tokio)
        .build();
    let tracer_provider = opentelemetry_sdk::trace::TracerProvider::builder()
        .with_batch_exporter(exporter, runtime::Tokio)
        .with_resource(Resource::new(vec![KeyValue::new(
            "service.name",
            "RhythmWorks",
        )]))
        .build();
    (tracer_provider, logger_provider)
}
