use forge::signal::compactor;
use once_cell::sync::Lazy;
use regex::Regex;

static PROGRESS_RE: Lazy<Regex> = Lazy::new(||
    // curl progress meter lines: "  % Total    % Received ..."
    Regex::new(r"(?m)^\s+%\s+Total[^\n]*\n?|^\s+\d+\s+\d+[^\n]*\n?").unwrap());
static VERBOSE_HEADER_RE: Lazy<Regex> = Lazy::new(||
    // curl -v connection lines
    Regex::new(r"(?m)^[*<>] [^\n]+\n?").unwrap());

pub fn compress_curl(subcmd: &str, raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s = PROGRESS_RE.replace_all(&cleaned, "");
    // If -v / --verbose, also strip connection chatter but keep response body
    if subcmd.contains("-v") || subcmd.contains("--verbose") {
        let s2 = VERBOSE_HEADER_RE.replace_all(&s, "");
        return compactor::collapse_blanks(&s2);
    }
    compactor::collapse_blanks(&s)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn curl_strips_progress() {
        let raw = "  % Total    % Received  % Xferd\n  100  1234  100  1234    0     0\n{\"status\":\"ok\"}\n";
        let out = compress_curl("curl https://api.example.com", raw);
        assert!(!out.contains("% Total"), "{out}");
        assert!(out.contains("status"), "{out}");
    }
}
