fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Générer les bindings Rust à partir des fichiers .proto
    let proto_dir = "proto";
    let proto_files = vec!["proto/stream/stream.proto", "proto/common/auth.proto"];

    // Vérifier si protoc est disponible
    // Si les fichiers générés existent déjà, on peut continuer sans protoc
    let generated_dir = std::path::Path::new("src/generated");
    let required_files = vec![
        generated_dir.join("veza.stream.rs"),
        generated_dir.join("veza.common.auth.rs"),
    ];
    
    let all_generated_exist = required_files.iter().all(|p| p.exists());
    
    if all_generated_exist {
        // Les fichiers générés existent, on peut continuer sans protoc
        println!("cargo:warning=Using pre-generated protobuf files. protoc not required.");
        for proto_file in &proto_files {
            println!("cargo:rerun-if-changed={}", proto_file);
        }
        println!("cargo:rerun-if-changed=build.rs");
        return Ok(());
    }

    // Configuration tonic-build
    tonic_build::configure()
        .build_server(true)
        .build_client(false) // Stream server est serveur, pas client
        .out_dir("src/generated")
        .compile(&proto_files, &[proto_dir])?;

    // Recompiler si les fichiers .proto changent
    for proto_file in &proto_files {
        println!("cargo:rerun-if-changed={}", proto_file);
    }

    println!("cargo:rerun-if-changed=build.rs");

    Ok(())
}
