#![cfg(feature = "_build")]
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

fn get_protos_recursively(root: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut protos = Vec::new();
    for entry in fs::read_dir(root)? {
        let entry = entry?;
        if entry.path().is_dir() {
            protos.append(&mut get_protos_recursively(&entry.path())?)
        } else if let Some(ext) = entry.path().extension() {
            if ext == "proto" {
                protos.push(entry.path())
            }
        }
    }

    Ok(protos)
}

fn main() {
    // Get the directory containing Cargo.toml
    let manifest_dir =
        env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR environment variable not set");
    let manifest_path = Path::new(&manifest_dir);

    let proto_input = manifest_path.join("definitions/protos/");

    let proto_files = get_protos_recursively(&proto_input)
            .unwrap_or_else(|_| panic!("\n===\nFailed to read proto directory '{}'. Run `./gradlew :scout-service-api-rust:prepareNominalApis` to copy the files to the definitions directory.\n===\n", proto_input.display()));

    let mod_dir = manifest_path.join("src/proto");
    let proto_mod_file = mod_dir.join("mod.rs");

    tonic_build::configure()
        .build_server(false)
        .emit_rerun_if_changed(false)
        .compile_well_known_types(true)
        .include_file(&proto_mod_file)
        .out_dir(&mod_dir)
        .compile_protos(
            &proto_files,
            &[
                proto_input.clone(),
                manifest_path.join("definitions/proto-includes/"),
            ],
        )
        .expect("Failed to compile tonic grpc client from proto definitions");

    // rename the `gen` module `r#gen` as `gen` is a reserved keyword in rust edition 2024
    let content =
        fs::read_to_string(&proto_mod_file).expect("Failed to read generated tonic.rs file");
    let modified_content = content.replace("pub mod gen", "pub mod r#gen");
    fs::write(&proto_mod_file, modified_content).expect("Failed to write modified tonic.rs file");
}
