//! Build script for quicproquo-proto.
//!
//! Runs two code generators:
//! 1. Cap'n Proto (v1 legacy) — from `schemas/*.capnp`
//! 2. Protobuf/prost (v2) — from `proto/qpq/v1/*.proto`

use std::{env, path::PathBuf};

fn main() {
    // Vendor protoc from protobuf-src so the build doesn't require system protoc.
    std::env::set_var("PROTOC", protobuf_src::protoc());

    let manifest_dir =
        PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
    let workspace_root = manifest_dir
        .join("../..")
        .canonicalize()
        .expect("canonicalize workspace root");

    // ── v1: Cap'n Proto codegen ──────────────────────────────────────────────
    let schemas_dir = workspace_root.join("schemas");

    for schema in &["auth.capnp", "delivery.capnp", "node.capnp", "federation.capnp"] {
        println!("cargo:rerun-if-changed={}", schemas_dir.join(schema).display());
    }

    capnpc::CompilerCommand::new()
        .src_prefix(&schemas_dir)
        .file(schemas_dir.join("auth.capnp"))
        .file(schemas_dir.join("delivery.capnp"))
        .file(schemas_dir.join("node.capnp"))
        .file(schemas_dir.join("federation.capnp"))
        .run()
        .expect(
            "Cap'n Proto schema compilation failed. \
             Is `capnp` installed? (apt-get install capnproto / brew install capnp)",
        );

    // ── v2: Protobuf/prost codegen ───────────────────────────────────────────
    let proto_dir = workspace_root.join("proto");

    let proto_files = [
        "qpq/v1/common.proto",
        "qpq/v1/auth.proto",
        "qpq/v1/delivery.proto",
        "qpq/v1/keys.proto",
        "qpq/v1/channel.proto",
        "qpq/v1/user.proto",
        "qpq/v1/blob.proto",
        "qpq/v1/device.proto",
        "qpq/v1/p2p.proto",
        "qpq/v1/federation.proto",
        "qpq/v1/push.proto",
        "qpq/v1/group.proto",
        "qpq/v1/moderation.proto",
        "qpq/v1/recovery.proto",
    ];

    let full_paths: Vec<PathBuf> = proto_files.iter().map(|f| proto_dir.join(f)).collect();

    for path in &full_paths {
        println!("cargo:rerun-if-changed={}", path.display());
    }

    prost_build::Config::new()
        .out_dir(PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR")))
        .compile_protos(&full_paths, &[&proto_dir])
        .expect("prost compile_protos failed");
}
