use std::env;
use std::process::Command;
use std::path::PathBuf;

fn main() {
    let proto_file = "proto/interop.proto";

    // 1. Generate prost/tonic code
    tonic_build::compile_protos(proto_file).expect("Failed to compile protos with tonic-build");

    // 2. Generate roto code
    // Find protoc-gen-roto
    // We assume it's in the target/debug folder of the root project
    let root_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let plugin_path = PathBuf::from(&root_dir)
        .join("../")
        .join("target/debug/protoc-gen-roto");

    if !plugin_path.exists() {
        println!("cargo:warning=protoc-gen-roto plugin not found at {:?}. Roto code generation will be skipped.", plugin_path);
        return;
    }

    let out_dir = PathBuf::from(&root_dir).join("src/generated");

    let status = Command::new("protoc")
        .arg(format!("--plugin=protoc-gen-roto={}", plugin_path.to_str().unwrap()))
        .arg(format!("--roto_out={}", out_dir.to_str().unwrap()))
        .arg(proto_file)
        .status()
        .expect("Failed to execute protoc");

    if !status.success() {
        panic!("protoc failed to generate roto code");
    }
}
