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

static DOWNLOAD_RE: Lazy<Regex> = Lazy::new(||
    // Matches both `  Downloading …` and `  - Installing …` (poetry format)
    Regex::new(r"(?m)^[ \t]*-?[ \t]*(Downloading|Installing|Resolving|Fetching)[^\n]+\n?").unwrap());
static LOCK_PROGRESS_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?m)^Updating dependencies\nResolving dependencies\.\.\.[^\n]*\n?").unwrap()
});

pub fn compress_poetry(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s = DOWNLOAD_RE.replace_all(&cleaned, "");
    let s = LOCK_PROGRESS_RE.replace_all(&s, "");
    compactor::collapse_blanks(&s)
}

/// Also used for `uv sync`, `conda install`, `pipx install`.
pub fn compress_uv(raw: &str) -> String {
    compress_poetry(raw)
}

pub fn compress_pkg_manager(subcmd: &str, raw: &str) -> String {
    let _ = subcmd;
    compress_poetry(raw)
}

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

    #[test]
    fn poetry_strips_installing_lines() {
        let raw = "  - Installing requests (2.28.0)\n  - Installing urllib3 (1.26.0)\nPackage operations: 2 installs\n";
        let out = compress_poetry(raw);
        assert!(!out.contains("Installing requests"), "{out}");
        assert!(out.contains("Package operations"));
    }
}
