//! Bake the production service-kicad URL into the binary at compile time.
//!
//! Precedence:
//!   1. $SERVICE_KICAD_URL (set by wiki-publish or release CI).
//!   2. The `url` field from /service-kicad/service.json (updated by
//!      deploy.sh at container provisioning).
//!   3. Local dev fallback: `http://127.0.0.1:8780`.
//!
//! Binaries built without an explicit URL default to localhost so the
//! `service-kicad --version` smoke still passes in a plain `cargo build`.

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

fn main() {
    println!("cargo:rerun-if-env-changed=SERVICE_KICAD_URL");
    println!("cargo:rerun-if-changed=../service.json");

    let url = std::env::var("SERVICE_KICAD_URL")
        .or_else(|_| read_url_from_service_json())
        .unwrap_or_else(|_| "http://127.0.0.1:8780".to_string());

    println!("cargo:rustc-env=SERVICE_KICAD_URL={}", url);
}

fn read_url_from_service_json() -> Result<String, std::io::Error> {
    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let svc_json = manifest.parent().and_then(|p| p.join("service.json").canonicalize().ok());
    let Some(path) = svc_json else {
        return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "service.json"));
    };
    let contents = fs::read_to_string(&path)?;
    // Minimal JSON scrape — avoids pulling serde_json into the build
    // dependency graph. Looks for `"url": "…"`.
    for line in contents.lines() {
        if let Some(rest) = line.split_once("\"url\"") {
            if let Some(v) = rest.1.split('"').nth(1) {
                return Ok(v.to_string());
            }
        }
    }
    Err(std::io::Error::new(std::io::ErrorKind::NotFound, "no url in service.json"))
}