#[cfg(feature = "observability")]
use once_cell::sync::OnceCell;

#[cfg(feature = "observability")]
static TRACING_INIT: OnceCell<()> = OnceCell::new();

pub fn init_tracing(service_name: &str, log_level: Option<&str>, log_format: Option<&str>) {
    #[cfg(feature = "observability")]
    {
        use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

        if TRACING_INIT.get().is_some() {
            return;
        }

        let format = log_format
            .map(|s| s.to_lowercase())
            .or_else(|| std::env::var("LOG_FORMAT").ok().map(|s| s.to_lowercase()))
            .unwrap_or_else(|| "pretty".to_string());

        let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
            .or_else(|_| {
                let lvl = log_level
                    .map(|s| s.to_string())
                    .or_else(|| std::env::var("LOG_LEVEL").ok())
                    .unwrap_or_else(|| "info".to_string());

                let fallback = format!("{},{}=debug", lvl, service_name);
                Ok::<_, anyhow::Error>(tracing_subscriber::EnvFilter::new(fallback))
            })
            .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));

        let registry = tracing_subscriber::registry().with(env_filter);

        if format == "pretty" {

            let layer = tracing_subscriber::fmt::layer()
                .with_target(true)
                .with_thread_ids(true)
                .compact();

            let _ = registry.with(layer).try_init();
        } else {
            let layer = tracing_subscriber::fmt::layer()
                .json()
                .with_target(true)
                .with_thread_ids(true);

            let _ = registry.with(layer).try_init();
        }

        TRACING_INIT.set(()).ok();
        tracing::info!("Observability initialized for service: {}", service_name);
    }

    #[cfg(not(feature = "observability"))]
    {
        let _ = (service_name, log_level, log_format);
    }
}
