use std::io;

/// Initialize opt-in structured logging.
///
/// Reads `CCD_LOG` env var. When absent or empty, no subscriber is
/// installed (zero overhead). When set, configures tracing-subscriber
/// writing to stderr only — stdout is never touched.
///
/// Filter syntax follows `tracing_subscriber::EnvFilter`:
///   CCD_LOG=debug
///   CCD_LOG=ccd=info
///   CCD_LOG=ccd::db=trace,ccd=debug
pub fn init() {
    let filter = match std::env::var("CCD_LOG") {
        Ok(val) if !val.is_empty() => val,
        _ => return,
    };

    let subscriber = tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_new(&filter)
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("ccd=info")),
        )
        .with_writer(io::stderr)
        .with_ansi(io::IsTerminal::is_terminal(&io::stderr()))
        .compact()
        .finish();

    let _ = tracing::subscriber::set_global_default(subscriber);
}
