use build_print::info;
use conda_build::pkgconfig_conda;
use itertools::Itertools;
use std::env;

fn main() -> Result<(), anyhow::Error> {
    if let Some(conda_root) = pkgconfig_conda()? {
        info!(
            "Directing pkg-config to look for fenics-dolfinx within the Conda environment {}.",
            conda_root.display()
        );
    }

    println!("cargo:rerun-if-changed=build.rs");

    let mut pkg = pkg_config::Config::new();
    locate_dolfinx(&mut pkg)
}

fn locate_dolfinx(pkg: &mut pkg_config::Config) -> Result<(), anyhow::Error> {
    let lib = pkg.probe("dolfinx").or_else(|e| {
        // Debian/Ubuntu has separate real and complex dolfinx.
        info!("Could not find dolfinx, trying dolfinx_real (as the library is named if installed through a Debian/Ubuntu package).");
        // If that's also not found, return original error instead of Debian/Ubuntu-specic error.
        pkg.probe("dolfinx_real").map_err(|_| e)
    })?;

    // We also need fmt for linking to work.
    pkg.probe("fmt")?;

    let cleaned_paths = lib.include_paths.iter().unique().collect::<Vec<_>>();
    let includes = env::join_paths(cleaned_paths)?.into_string().unwrap();
    println!("cargo:include={}", includes);

    println!(
        "cargo:ldflags={}",
        env::join_paths(lib.ld_args.iter().map(|s| s.join(",")))?
            .into_string()
            .unwrap()
    );

    // let cleaned_rpaths = lib.link_paths.iter().unique().collect::<Vec<_>>();
    // let rpaths = env::join_paths(cleaned_rpaths)?.into_string().unwrap();
    // println!("cargo:rpath={}", rpaths);

    // for lp in lib.link_paths.iter().unique() {
    //     println!("cargo:rustc-link-arg=-Wl,-rpath,{}", lp.display());
    // }

    Ok(())
}
