//! Build script: generate the nucel API client from `openapi/nucel.json` via progenitor.
//!
//! We read from the crate-local `${CARGO_MANIFEST_DIR}/openapi/nucel.json` so
//! that published tarballs (which don't contain the workspace root) still
//! build. The workspace-level `openapi/nucel.json` is the reviewable source
//! of truth; the `export-openapi` bin dual-writes both copies.

use std::env;
use std::fs;
use std::path::PathBuf;

fn main() {
    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let spec_path = manifest.join("openapi/nucel.json");
    println!("cargo:rerun-if-changed={}", spec_path.display());

    let spec_content = fs::read_to_string(&spec_path)
        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", spec_path.display()));

    let spec: serde_json::Value =
        serde_json::from_str(&spec_content).expect("Failed to parse openapi/nucel.json");

    let spec: openapiv3::OpenAPI =
        serde_json::from_value(spec).expect("Failed to deserialize as OpenAPI v3 spec");

    let mut generator = progenitor::Generator::new(
        progenitor::GenerationSettings::default()
            .with_interface(progenitor::InterfaceStyle::Builder),
    );

    let tokens = generator
        .generate_tokens(&spec)
        .expect("progenitor failed to generate client");

    let ast = syn::parse2(tokens).expect("progenitor produced invalid Rust");
    let content = prettyplease::unparse(&ast);

    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let out_file = out_dir.join("codegen.rs");
    fs::write(&out_file, content).unwrap();
}
