use forge::signal::compactor;

static NOISE_VARS: &[&str] = &[
    "LS_COLORS=",
    "LESS_TERMCAP_",
    "LSCOLORS=",
    "PS1=",
    "PS2=",
    "BASH_FUNC_",
    "PROMPT_COMMAND=",
    "_=",
];

pub fn compress_env(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let out: Vec<&str> = cleaned
        .lines()
        .filter(|l| !NOISE_VARS.iter().any(|n| l.starts_with(n)))
        .collect();
    let result = out.join("\n");
    // Truncate if huge (very noisy environments)
    let lines: Vec<&str> = result.lines().collect();
    if lines.len() > 50 {
        return format!(
            "{}\n... [{} more env vars] ...",
            lines[..50].join("\n"),
            lines.len() - 50
        );
    }
    result
}

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

    #[test]
    fn env_strips_noise_vars() {
        let raw = "PATH=/usr/bin\nLS_COLORS=rs=0:di=01;34\nHOME=/home/user\nPS1=\\u@\\h\n";
        let out = compress_env(raw);
        assert!(!out.contains("LS_COLORS="), "{out}");
        assert!(!out.contains("PS1="), "{out}");
        assert!(out.contains("PATH="), "{out}");
        assert!(out.contains("HOME="), "{out}");
    }

    #[test]
    fn env_truncates_large_output() {
        let raw = (0..60)
            .map(|i| format!("VAR{i}=value{i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = compress_env(&raw);
        assert!(out.contains("more env vars"), "{out}");
    }
}
