use std::path::PathBuf;

use anyhow::Context;
use serde::Deserialize;

use crate::json;

pub fn read_env(var: &'static str) -> anyhow::Result<String> {
    log::trace!("read_env: {var}");
    std::env::var(var)
        .map_err(|e| anyhow::format_err!("Could not read {var} environment variable: {e}"))
}

pub fn read_path_env(var: &'static str) -> anyhow::Result<PathBuf> {
    Ok(read_env(var)?.into())
}

pub fn read_env_json<T: for<'de> Deserialize<'de>>(var: &'static str) -> anyhow::Result<T> {
    let json_text = read_env(var)?;
    json::from_str(&json_text).with_context(|| {
        format!("Could not parse contents of env var {var} into the correct json format")
    })
}
