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

static PROGRESS_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?m)^\s*(Downloading|Collecting|Using cached|Obtaining|Building wheel)[^\n]+\n?")
        .unwrap()
});
static ALREADY_SATISFIED_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?m)^Requirement already satisfied:[^\n]+\n?").unwrap());
static CHECKING_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s+Checking [^\n]+\n?").unwrap());

// ── pip install ───────────────────────────────────────────────────────────────

pub fn compress_install(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s = PROGRESS_RE.replace_all(&cleaned, "");
    let s = ALREADY_SATISFIED_RE.replace_all(&s, "");
    let s = CHECKING_RE.replace_all(&s, "");
    compactor::collapse_blanks(&s)
}

// ── pip list / freeze ─────────────────────────────────────────────────────────

pub fn compress_list(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let lines: Vec<&str> = cleaned.lines().collect();
    if lines.len() <= 30 {
        return cleaned;
    }
    format!(
        "{}\n... [{} more packages] ...",
        lines[..30].join("\n"),
        lines.len() - 30
    )
}

// ── pip show ─────────────────────────────────────────────────────────────────

pub fn compress_show(raw: &str) -> String {
    // Already compact key: value format — just normalise
    compactor::normalise(raw)
}

// ── top-level dispatcher ──────────────────────────────────────────────────────

pub fn compress_pip(subcmd: &str, raw: &str) -> String {
    let sub = subcmd.trim();
    if sub.starts_with("install") || sub.starts_with("download") {
        return compress_install(raw);
    }
    if sub.starts_with("list") || sub.starts_with("freeze") {
        return compress_list(raw);
    }
    if sub.starts_with("show") || sub.starts_with("check") {
        return compress_show(raw);
    }
    compactor::normalise(raw)
}

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

    #[test]
    fn install_strips_downloading() {
        let raw = "Collecting requests\n  Downloading requests-2.28.0-py3-none-any.whl\nRequirement already satisfied: urllib3\nSuccessfully installed requests-2.28.0\n";
        let out = compress_install(raw);
        assert!(!out.contains("Downloading requests"), "{out}");
        assert!(!out.contains("already satisfied"), "{out}");
        assert!(out.contains("Successfully installed"));
    }

    #[test]
    fn list_truncates_many_packages() {
        let raw = (0..40)
            .map(|i| format!("pkg{i}   1.{i}.0"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = compress_list(&raw);
        assert!(out.contains("more packages"), "{out}");
    }
}
