use serde_json::Value;
use time::format_description::well_known::Rfc3339;

fn progress_enabled() -> bool {
    std::env::var("RPKI_PROGRESS_LOG")
        .ok()
        .map(|v| matches!(v.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
        .unwrap_or(false)
}

pub fn slow_threshold_secs() -> f64 {
    std::env::var("RPKI_PROGRESS_SLOW_SECS")
        .ok()
        .and_then(|v| v.parse::<f64>().ok())
        .filter(|v| *v >= 0.0)
        .unwrap_or(30.0)
}

pub fn stage_fresh_slow_threshold_ms() -> u64 {
    std::env::var("RPKI_PROGRESS_STAGE_FRESH_SLOW_MS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(1_000)
}

pub fn pp_control_slow_threshold_ms() -> u64 {
    std::env::var("RPKI_PROGRESS_PP_CONTROL_SLOW_MS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(100)
}

pub fn pp_cache_slow_threshold_ms() -> u64 {
    std::env::var("RPKI_PROGRESS_PP_CACHE_SLOW_MS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(50)
}

pub fn control_loop_slow_threshold_ms() -> u64 {
    std::env::var("RPKI_PROGRESS_CONTROL_LOOP_SLOW_MS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(1_000)
}

pub fn emit(kind: &str, payload: Value) {
    if !progress_enabled() {
        return;
    }
    let ts = time::OffsetDateTime::now_utc()
        .format(&Rfc3339)
        .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string());
    let mut map = serde_json::Map::new();
    map.insert("ts".to_string(), Value::String(ts));
    map.insert("kind".to_string(), Value::String(kind.to_string()));
    match payload {
        Value::Object(obj) => {
            for (k, v) in obj {
                map.insert(k, v);
            }
        }
        other => {
            map.insert("value".to_string(), other);
        }
    }
    eprintln!("[progress] {}", Value::Object(map));
}
