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

#[allow(dead_code)]
static TIMING_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?m)^Found \d+ errors? in [^\n]+ \(\d+ fixed[^\)]*\)\n?").unwrap());

pub fn compress_ruff(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    // Strip "All checks passed!" noise; keep error lines + summary
    let out: Vec<&str> = cleaned.lines().filter(|l| !l.trim().is_empty()).collect();
    if out.len() <= 1 {
        return cleaned;
    }
    compactor::collapse_blanks(&out.join("\n"))
}

/// Compress `ruff check` output: keep file:line findings + summary only.
pub fn compress_ruff_check(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let out: Vec<&str> = cleaned
        .lines()
        .filter(|l| {
            // Keep lines like "path/to/file.py:10:4: E501 ..." or summary lines
            l.contains(": ") && (l.contains(".py:") || l.contains(".pyi:"))
                || l.starts_with("Found")
                || l.starts_with("All checks")
        })
        .collect();
    if out.is_empty() {
        cleaned
    } else {
        out.join("\n")
    }
}

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

    #[test]
    fn ruff_check_keeps_findings() {
        let raw = "src/foo.py:10:4: E501 Line too long\nsrc/bar.py:5:1: F401 unused import\nFound 2 errors.\n";
        let out = compress_ruff_check(raw);
        assert!(out.contains("E501"), "{out}");
        assert!(out.contains("F401"), "{out}");
        assert!(out.contains("Found 2 errors"), "{out}");
    }
}
