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

use abi_generator::{
    abi::{ty::TypeWidth, AbiBuilder},
    syntax::UnwrapFancy,
    TargetEnv,
};

fn load_abi_definitions<P: AsRef<Path>>(path: P) -> String {
    let mut content = String::new();
    for file in fs::read_dir(path).unwrap() {
        let file = file.unwrap();
        if file.path().extension().map(|x| x == "abi").unwrap_or(false) {
            println!("cargo:rerun-if-changed={}", file.path().display());
            content.extend(fs::read_to_string(file.path()));
        }
    }
    content
}

fn generate_abi<P: AsRef<Path>>(target_is_64bit: bool, abi_path: P) {
    let output_dir = std::env::var("OUT_DIR").expect("$OUT_DIR not set");
    let generated_types = Path::new(&output_dir).join("generated_types.rs");

    let target_env = if target_is_64bit {
        TargetEnv {
            thin_pointer_width: TypeWidth::U64,
            fat_pointer_width: TypeWidth::U128,
        }
    } else {
        TargetEnv {
            thin_pointer_width: TypeWidth::U32,
            fat_pointer_width: TypeWidth::U64,
        }
    };

    let abi = load_abi_definitions(abi_path);
    let abi = AbiBuilder::from_string(&abi, target_env).unwrap_fancy(&abi);

    let types = prettyplease::unparse(
        &abi.emit_file(true, false)
            .unwrap_fancy("Could not emit types"),
    );

    fs::write(generated_types, types).unwrap();
}

fn main() {
    let target_is_64bit = env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64";
    generate_abi(target_is_64bit, "def");
}
