use std::env;
use std::error::Error;
use std::path::{Path, PathBuf};

fn main() -> Result<(), Box<dyn Error>> {
    configure_protoc();

    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
    let repo_root = manifest_dir
        .parent()
        .and_then(Path::parent)
        .ok_or("clients/rust must live two levels below the repository root")?;
    let proto_root = repo_root.join("src/ZB.MOM.WW.MxGateway.Contracts/Protos");
    let gateway_proto = proto_root.join("mxaccess_gateway.proto");
    let worker_proto = proto_root.join("mxaccess_worker.proto");
    let galaxy_proto = proto_root.join("galaxy_repository.proto");
    let descriptor_path = PathBuf::from(env::var("OUT_DIR")?).join("mxaccessgw-client-v1.protoset");

    println!("cargo:rerun-if-changed={}", gateway_proto.display());
    println!("cargo:rerun-if-changed={}", worker_proto.display());
    println!("cargo:rerun-if-changed={}", galaxy_proto.display());

    tonic_build::configure()
        .build_server(true)
        .build_client(true)
        .file_descriptor_set_path(descriptor_path)
        .compile_protos(
            &[
                gateway_proto.as_path(),
                worker_proto.as_path(),
                galaxy_proto.as_path(),
            ],
            &[proto_root.as_path()],
        )?;

    Ok(())
}

fn configure_protoc() {
    if env::var_os("PROTOC").is_some() {
        return;
    }

    for candidate in protoc_candidates() {
        if candidate.is_file() {
            env::set_var("PROTOC", candidate);
            return;
        }
    }
}

fn protoc_candidates() -> Vec<PathBuf> {
    let mut candidates = Vec::new();

    if cfg!(windows) {
        if let Some(local_app_data) = env::var_os("LOCALAPPDATA") {
            candidates.push(PathBuf::from(local_app_data).join(
                "Microsoft/WinGet/Packages/Google.Protobuf_Microsoft.Winget.Source_8wekyb3d8bbwe/bin/protoc.exe",
            ));
        }
    }

    candidates.push(PathBuf::from("protoc"));
    candidates
}
