use slog::{Drain, Logger};
use slog_async::Async;
use slog_term::{CompactFormat, TermDecorator};
use std::sync::{
    Arc, LazyLock,
    atomic::{self, AtomicU8},
};

use crate::logging::runtime_filter::RuntimeLevelFilter;

pub static LOG_LEVEL: LazyLock<Arc<AtomicU8>> = LazyLock::new(|| Arc::new(AtomicU8::new(0)));

pub static INTERNAL_LOGGER: LazyLock<Logger> = LazyLock::new(|| {
    let decorator = TermDecorator::new().build();
    let drain = CompactFormat::new(decorator).build().fuse();
    let drain = RuntimeLevelFilter {
        drain,
        on: LOG_LEVEL.clone(),
    }
    .fuse();
    let drain = Async::new(drain).build().fuse();
    Logger::root(drain, slog::o!())
});

pub fn set_verbose(level: &str) {
    let level_id = match level {
        "TRACE" | "trace" | "t" => 0,
        "DEBUG" | "debug" | "d" => 1,
        "WARNING" | "warning" | "w" => 3,
        "ERROR" | "error" | "e" => 4,
        "CRITICAL" | "critical" | "c" => 5,
        _ => 2, // Default to INFO (2)
    };

    LOG_LEVEL.store(level_id, atomic::Ordering::SeqCst);
}
