use std::fs;
use std::path::{PathBuf};

pub fn load_config(target_key: &str) -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let rc_path = PathBuf::from(home).join(".sculblogrc");

    if !rc_path.exists() {
        eprintln!("Error: ~/.sculblogrc not found! Please create it and define {}.", target_key);
        std::process::exit(1);
    }

    let content = fs::read_to_string(&rc_path).expect("Failed to read ~/.sculblogrc");
    let prefix = format!("{}=", target_key);
    for line in content.lines() {
        let line = line.trim();
        if line.starts_with(&prefix) {
            let dir = line.trim_start_matches(&prefix).trim();
            let dir = dir.trim_matches('"').trim_matches('\'');
            return PathBuf::from(dir);
        }
    }

    eprintln!("Error: {} not defined in ~/.sculblogrc", target_key);
    std::process::exit(1);
}

/// Filter out lines from a tab-separated map file where the path column matches `exclude_path`.
pub fn filter_filename_map(content: &str, exclude_path: &str) -> String {
    let filtered: Vec<&str> = content
        .lines()
        .filter(|line| {
            line.split_once('\t')
                .map(|(p, _)| p != exclude_path)
                .unwrap_or(true)
        })
        .collect();
    let mut out = filtered.join("\n");
    if !out.is_empty() {
        out.push('\n');
    }
    out
}
