use std::collections::HashMap;

pub fn substitute(template: &str, vars: &HashMap<String, String>) -> String {
    let mut result = template.to_string();
    for (k, v) in vars {
        result = result.replace(&format!("{{{{{k}}}}}"), v);
    }
    result
}

pub fn load_env(name: &str) -> anyhow::Result<HashMap<String, String>> {
    let path = format!(".rok-studio/envs/{name}.json");
    let content = std::fs::read_to_string(&path)?;
    let map: HashMap<String, String> = serde_json::from_str(&content)?;
    Ok(map)
}

pub fn list_envs() -> Vec<String> {
    let dir = std::path::Path::new(".rok-studio/envs");
    if !dir.exists() {
        return Vec::new();
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .filter_map(|e| e.ok())
        .filter_map(|e| {
            let p = e.path();
            if p.extension().and_then(|x| x.to_str()) == Some("json") {
                p.file_stem()
                    .and_then(|s| s.to_str())
                    .map(|s| s.to_string())
            } else {
                None
            }
        })
        .collect()
}

pub fn ensure_studio_dirs() -> anyhow::Result<()> {
    std::fs::create_dir_all(".rok-studio/envs")?;
    std::fs::create_dir_all(".rok-studio/collections")?;
    let dev = std::path::Path::new(".rok-studio/envs/dev.json");
    if !dev.exists() {
        std::fs::write(dev, r#"{"BASE_URL":"http://localhost:3000","TOKEN":""}"#)?;
    }
    Ok(())
}

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

    #[test]
    fn substitute_replaces_vars() {
        let mut vars = HashMap::new();
        vars.insert("TOKEN".to_string(), "abc123".to_string());
        vars.insert("BASE_URL".to_string(), "http://localhost:3000".to_string());
        assert_eq!(substitute("Bearer {{TOKEN}}", &vars), "Bearer abc123");
        assert_eq!(
            substitute("{{BASE_URL}}/users", &vars),
            "http://localhost:3000/users"
        );
    }

    #[test]
    fn substitute_leaves_unknown_vars() {
        let vars = HashMap::new();
        assert_eq!(substitute("{{UNKNOWN}}", &vars), "{{UNKNOWN}}");
    }
}
