//use anyhow::bail;
//use regex::Regex;
pub use python_config::{Error as PyCError, PythonConfig};
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
//use std::process::Command;

/// Adds CONDA_PREFIX/lib/pkgconfig/ to PKG_CONFIG_PATH
pub fn pkgconfig_conda() -> Result<Option<PathBuf>, anyhow::Error> {
    if let Some(conda_root_) = option_env!("CONDA_PREFIX") {
        let conda_root = PathBuf::from(conda_root_);
        let conda_pkgconfig = conda_root.join("lib/pkgconfig/");

        // Prepend CONDA_PREFIX to any existing PKG_CONFIG_PATH
        let new_path = match option_env!("PKG_CONFIG_PATH") {
            Some(path) => {
                let mut paths = env::split_paths(&path).collect::<Vec<_>>();
                paths.insert(0, conda_pkgconfig);
                env::join_paths(paths)?
            }
            None => conda_pkgconfig.into(),
        };

        // Set the environment variable
        unsafe {
            env::set_var("PKG_CONFIG_PATH", &new_path);
        }

        Ok(Some(conda_root))
    } else {
        Ok(None)
    }
}

/// Looks up conda Python
pub fn python_conda() -> Option<OsString> {
    option_env!("CONDA_PREFIX").and_then(|conda_prefix| {
        /* This does not point to the right place.
        option_env!("CONDA_PYTHON_EXE")
            .map(OsString::from)
            .or_else(|| { */
        let py = PathBuf::from(conda_prefix).join("bin/python");
        if py.exists() {
            Some(py.into())
        } else {
            None
        }
        /* })*/
    })
}

/// Returns a the python configuration and indication whether it's from Conda
pub fn python_config() -> (Result<PythonConfig, PyCError>, bool) {
    if let Some(py) = python_conda() {
        (PythonConfig::interpreter(py), true)
    } else {
        (Ok(PythonConfig::new()), false)
    }
}

/*
/// Looks up python includes given executable
pub fn python_includes(mut py: OsString) -> Result<Vec<String>, anyhow::Error> {
    py.push("3-config");
    let output = Command::new(&py).args(["--includes"]).output()?;
    if !output.status.success() {
        bail!("Failed to run {}.", py.display())
    }
    let re = Regex::new(r"\w+-I\w*").unwrap();
    let includes = re
        .split(format!(" {}", String::from_utf8(output.stdout)?).as_str())
        .map(String::from)
        .collect();
    Ok(includes)
}
*/
