use std::env;
use std::path::PathBuf;

use dotenv::from_path;

fn main() {
    // Load the .env.build file for build-time environment variables
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set");
    let manifest_path = PathBuf::from(manifest_dir);
    from_path(manifest_path.join(".env.build")).ok();

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

    // Add local lib directory to the linker search path (for def files and static libs)
    let static_lib_path = manifest_path.join("lib");
    println!(
        "cargo::rustc-link-search=native={}",
        static_lib_path.display()
    );

    // Add the SESAM_FSV_LIB_PATH to the linker search path
    let fsv_lib_path =
        PathBuf::from(env::var("SESAM_FSV_LIB_PATH").expect("SESAM_FSV_LIB_PATH must be set"));
    println!("cargo::rustc-link-search=native={}", fsv_lib_path.display());

    // Add the SESAM_FSV_LIB_PATH to the PATH environment variable
    if cfg!(target_os = "windows") {
        let path = env::var("PATH").unwrap_or_default();
        println!("cargo:rustc-env=PATH={};{}", fsv_lib_path.display(), path);
    } else if cfg!(target_os = "linux") {
        println!("cargo:rustc-env=LD_LIBRARY_PATH={}", fsv_lib_path.display());
    }

    // Link the SESAM_FSV_SSVLIB dynamic library
    println!(
        "cargo::rustc-link-lib=dylib={}",
        env::var("SESAM_FSV_SSVLIB").expect("SESAM_FSV_SSVLIB must be set")
    );
    // TODO : try `raw-dylib` instead of `dylib` on Windows to avoid the need of the `lib` headers compiled from the `def`
}