//! Build script for coolprop-sys.
//!
//! This compiles the CoolProp C++ library statically.

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

fn coolprop_src_path() -> Option<PathBuf> {
    // Try to find CoolProp source in common locations
    let possible_paths = vec![
        // Vendor directory (recommended)
        PathBuf::from("vendor/coolprop"),
        // External directory
        PathBuf::from("external/coolprop"),
        // System paths
        PathBuf::from("/usr/local/src/CoolProp"),
        PathBuf::from("/opt/CoolProp"),
    ];

    for path in possible_paths {
        if path.join("CMakeLists.txt").exists() {
            return Some(path);
        }
    }

    None
}

fn main() {
    let static_linking = env::var("CARGO_FEATURE_STATIC").is_ok();

    // Check if CoolProp source is available
    if let Some(coolprop_path) = coolprop_src_path() {
        println!("cargo:rerun-if-changed={}", coolprop_path.display());

        // Configure build for CoolProp
        println!(
            "cargo:rustc-link-search=native={}/build",
            coolprop_path.display()
        );
    }

    // Link against CoolProp
    if static_linking {
        // Static linking - find libCoolProp.a
        println!("cargo:rustc-link-lib=static=CoolProp");
    } else {
        // Dynamic linking
        println!("cargo:rustc-link-lib=dylib=CoolProp");
    }

    // Link required system libraries
    println!("cargo:rustc-link-lib=dylib=m");
    println!("cargo:rustc-link-lib=dylib=stdc++");

    // Tell Cargo to rerun if build.rs changes
    println!("cargo:rerun-if-changed=build.rs");

    println!(
        "cargo:warning=CoolProp source not found in vendor/. 
              For full static build, run: 
              git clone https://github.com/CoolProp/CoolProp.git vendor/coolprop"
    );
}
