use std::{
    env,
    fs,
    io,
    path::{Path, PathBuf},
};

fn main() -> io::Result<()> {
    let manifest_dir =
        PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
    let dll_source_dir = manifest_dir.join("open_wrapper").join("lib");

    if !dll_source_dir.exists() {
        println!(
            "cargo:warning=DLL source directory '{}' not found. Skipping copy.",
            dll_source_dir.display()
        );
        return Ok(());
    }

    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set"));
    // OUT_DIR = target/{profile}/build/<pkg>/out
    let profile_dir = out_dir
        .ancestors()
        .nth(3)
        .expect("Unable to compute profile dir from OUT_DIR");

    let dest_dir = Path::new(profile_dir);
    fs::create_dir_all(&dest_dir)?;

    for entry in fs::read_dir(&dll_source_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().map_or(false, |ext| ext.eq_ignore_ascii_case("dll")) {
            let file_name = entry.file_name();
            let dest_path = dest_dir.join(&file_name);
            fs::copy(&path, &dest_path)?;
        }
        println!("cargo:rerun-if-changed={}", path.display());
    }

    Ok(())
}
