main
Colby Knox 0.2.90 (source, not released; final shapes not run in Altium yet): the eleven verbs of standard 0.30.14 in the standard… 78b01ce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
//! Board design data an engineer sets up before routing: net classes (with their width and clearance rules)
//! and differential pairs.
use crate::support::{self, s};
use crate::agent;
use serde_json::{json, Value};
use std::time::Duration;

fn agent_data(r: &Value) -> Result<Value, Value> {
    match r.get("data") {
        Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => Ok(d.clone()),
        Some(d) => Err(json!({"success": false, "errorCode": d.get("errorCode").cloned().unwrap_or(json!("agent_error")), "error": d.get("error"), "reply": d})),
        None => Err(r.clone()),
    }
}

/// `["A","B"]` or `"A,B"` -> the agent's `A;B`.
fn name_list(v: Option<&Value>) -> Vec<String> {
    match v {
        Some(Value::Array(a)) => a.iter().filter_map(|x| x.as_str()).map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(),
        Some(Value::String(t)) => t.split([',', ';']).map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(),
        _ => vec![],
    }
}

fn open_board(args: &Value) -> Option<Value> {
    if let Some(g) = support::need_licensed() { return Some(g); }
    s(args, "filePath").and_then(|p| support::must_open(&p, 60))
}

/// The box around the named parts' pads (absolute mm, as altium_routing_state reports them), grown by `margin`. Pure.
pub fn pads_box(state: &Value, members: &[String], margin: f64) -> Option<(f64, f64, f64, f64)> {
    let mut b: Option<(f64, f64, f64, f64)> = None;
    for p in state["pads"].as_array().cloned().unwrap_or_default() {
        if !members.iter().any(|m| p["ref"].as_str().map(|r| r.eq_ignore_ascii_case(m)).unwrap_or(false)) { continue; }
        let (x, y) = (p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0));
        let h = (p["sizeX"].as_f64().unwrap_or(0.0).powi(2) + p["sizeY"].as_f64().unwrap_or(0.0).powi(2)).sqrt() / 2.0;
        b = Some(match b { None => (x - h, y - h, x + h, y + h), Some(o) => (o.0.min(x - h), o.1.min(y - h), o.2.max(x + h), o.3.max(y + h)) });
    }
    b.map(|o| (o.0 - margin, o.1 - margin, o.2 + margin, o.3 + margin))
}

/// altium_component_classes {filePath?, name?, members?, room?, remove?}: without name, list them.
pub fn component_classes(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let Some(name) = s(args, "name") else {
        let r = agent::call("comp_classes", &[("op", "list".into())], None, Duration::from_secs(60));
        return match agent_data(&r) { Ok(d) => json!({"success": true, "classes": d["classes"], "_hint": "Make one with {name, members:[designators], room?:true}."}), Err(e) => e };
    };
    if args.get("remove").and_then(|b| b.as_bool()) == Some(true) {
        let r = agent::call("comp_classes", &[("op", "remove".into()), ("name", name.clone())], None, Duration::from_secs(60));
        return match agent_data(&r) { Ok(d) => json!({"success": true, "class": name, "removed": d["removed"], "roomRemoved": d["roomRemoved"]}), Err(e) => e };
    }
    let members: Vec<String> = args.get("members").and_then(|m| m.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
    if members.is_empty() { return json!({"success": false, "errorCode": "bad_args", "error": "members (designators) are required"}); }
    let mut p: Vec<(&str, String)> = vec![("op", "set".into()), ("name", name.clone()), ("members", members.join(";"))];
    // room: true (fitted around the members' pads), {marginMm}, or {rect:[x1, y1, x2, y2]} in mm
    let room = args.get("room").cloned().unwrap_or(Value::Null);
    let mut rect = Value::Null;
    if room == json!(true) || room.is_object() {
        let r = match room.get("rect").and_then(|r| r.as_array()).filter(|a| a.len() == 4) {
            Some(a) => { let v: Vec<f64> = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); Some((v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3]))) }
            None => {
                let st = crate::routing::routing_state(&json!({}));
                pads_box(&st, &members, room.get("marginMm").and_then(|m| m.as_f64()).unwrap_or(1.0))
            }
        };
        let Some((x1, y1, x2, y2)) = r else { return json!({"success": false, "errorCode": "no_room_area", "error": "none of the members has a pad on the board to fit the room around; pass room:{rect:[x1,y1,x2,y2]}"}) };
        use crate::routing::raw;
        p.extend([("room", "1".into()), ("rx1", raw(x1).to_string()), ("ry1", raw(y1).to_string()), ("rx2", raw(x2).to_string()), ("ry2", raw(y2).to_string())]);
        rect = json!([(x1 * 1000.0).round() / 1000.0, (y1 * 1000.0).round() / 1000.0, (x2 * 1000.0).round() / 1000.0, (y2 * 1000.0).round() / 1000.0]);
    }
    let r = agent::call("comp_classes", &p, None, Duration::from_secs(60));
    match agent_data(&r) {
        Ok(d) => {
            let missing = d["missing"].as_array().map(|a| !a.is_empty()).unwrap_or(false);
            json!({"success": !missing, "errorCode": if missing { json!("parts_not_on_board") } else { Value::Null }, "class": name, "members": d["members"], "missing": d["missing"], "roomMm": rect, "room": d["room"],
                "_hint": "The class can scope rules (InComponentClass('<name>')); the room keeps its parts inside the rectangle (DRC reports a part outside). altium_replicate_layout copies one channel's placement to the others. Save with altium_save."})
        }
        Err(e) => e,
    }
}

/// altium_net_classes {filePath?, name?, nets?, width?, clearance?, remove?}: without name, list them.
pub fn net_classes(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let Some(name) = s(args, "name") else {
        let r = agent::call("net_classes", &[("op", "list".into())], None, Duration::from_secs(60));
        return match agent_data(&r) {
            Ok(d) => json!({"success": true, "classes": d["classes"],
                "_hint": "'All Nets' is Altium's own class of every net (superClass). Make one with {name, nets, width?, clearance?}; rules scoped InNetClass('<name>') then apply to its nets."}),
            Err(e) => e,
        };
    };
    if name.contains(['\'', '\n', ';']) { return json!({"success": false, "errorCode": "bad_args", "error": "a class name cannot hold quotes, semicolons or newlines"}); }
    let scope = format!("InNetClass('{name}')");
    if args.get("remove").and_then(|b| b.as_bool()) == Some(true) {
        let r = agent::call("net_classes", &[("op", "remove".into()), ("name", name.clone())], None, Duration::from_secs(60));
        let d = match agent_data(&r) { Ok(d) => d, Err(e) => return e };
        let rules: Vec<Value> = ["width", "clearance"].iter().map(|k| {
            let r = crate::routing::add_rule(&json!({"kind": k, "name": format!("{name} {k}"), "remove": true}));
            json!({"kind": k, "removed": r.get("removed")})
        }).collect();
        return json!({"success": true, "class": name, "removed": d["removed"], "rules": rules});
    }
    let nets = name_list(args.get("nets"));
    if nets.is_empty() { return json!({"success": false, "errorCode": "bad_args", "error": "nets is required: [\"VIN\",\"GND\"]", "_hint": "altium_list_nets names the board's nets."}); }
    let r = agent::call("net_classes", &[("op", "set".into()), ("name", name.clone()), ("nets", nets.join(";"))], None, Duration::from_secs(60));
    let d = match agent_data(&r) { Ok(d) => d, Err(e) => return e };
    let mut rules = Vec::new();
    // width: a number (mm, min = preferred) or {min, preferred, max}
    if let Some(w) = args.get("width") {
        let (min, pref, max) = match w {
            Value::Number(n) => { let v = n.as_f64().unwrap_or(0.0); (v, v, v.max(5.0)) }
            Value::Object(_) => {
                let min = w.get("min").and_then(|v| v.as_f64()).or_else(|| w.get("preferred").and_then(|v| v.as_f64())).unwrap_or(0.0);
                (min, w.get("preferred").and_then(|v| v.as_f64()).unwrap_or(min), w.get("max").and_then(|v| v.as_f64()).unwrap_or(min.max(5.0)))
            }
            _ => (0.0, 0.0, 0.0),
        };
        if min <= 0.0 { return json!({"success": false, "errorCode": "bad_args", "error": "width is mm (0.5) or {min, preferred, max} in mm", "class": d}); }
        let r = crate::routing::add_rule(&json!({"kind": "width", "name": format!("{name} width"), "scope1": scope, "min": min, "preferred": pref, "max": max,
            "comment": format!("net class {name}")}));
        rules.push(json!({"kind": "width", "minMm": min, "preferredMm": pref, "maxMm": max, "success": r.get("success"), "name": r.get("name"), "error": r.get("error")}));
    }
    if let Some(g) = args.get("clearance").and_then(|v| v.as_f64()) {
        let r = crate::routing::add_rule(&json!({"kind": "clearance", "name": format!("{name} clearance"), "scope1": scope, "scope2": "All", "gap": g,
            "comment": format!("net class {name}")}));
        rules.push(json!({"kind": "clearance", "gapMm": g, "success": r.get("success"), "name": r.get("name"), "error": r.get("error")}));
    }
    let not_on_board = d["notOnBoard"].as_array().cloned().unwrap_or_default();
    let ok = rules.iter().all(|r| r["success"] == json!(true));
    json!({"success": ok, "class": name, "members": d["members"], "replaced": d["replaced"], "notOnBoard": not_on_board, "rules": rules, "scope": scope,
        "_hint": if !not_on_board.is_empty() { "Some nets are not on the board (names are case-insensitive but must exist: altium_list_nets). The class was made without them." }
                 else { "The class is on the board, and its rules (if any) come first among their kind. New tracks on its nets take the preferred width; existing ones keep theirs (re-route or check with altium_run_drc). Save with altium_save. A class made on the board is kept by altium_update_pcb unless the project removes board-only classes." }})
}

/// altium_diff_pairs {filePath?, name?, pos?, neg?, remove?}: without name, list them.
pub fn diff_pairs(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let Some(name) = s(args, "name") else {
        let r = agent::call("diff_pairs", &[("op", "list".into())], None, Duration::from_secs(60));
        return match agent_data(&r) {
            Ok(d) => json!({"success": true, "pairs": d["pairs"], "_hint": "Make one with {name, pos, neg} (board net names, e.g. USB_P / USB_N)."}),
            Err(e) => e,
        };
    };
    if args.get("remove").and_then(|b| b.as_bool()) == Some(true) {
        let r = agent::call("diff_pairs", &[("op", "remove".into()), ("name", name.clone())], None, Duration::from_secs(60));
        return match agent_data(&r) { Ok(d) => json!({"success": true, "pair": name, "removed": d["removed"]}), Err(e) => e };
    }
    let (Some(pos), Some(neg)) = (s(args, "pos"), s(args, "neg")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "pos and neg (board net names) are required", "_hint": "altium_list_nets names the board's nets; USB_D+/USB_D- style pairs are the usual ones."});
    };
    let r = agent::call("diff_pairs", &[("op", "set".into()), ("name", name.clone()), ("pos", pos), ("neg", neg)], None, Duration::from_secs(60));
    match agent_data(&r) {
        Ok(d) => json!({"success": true, "pair": name, "pos": d["pos"], "neg": d["neg"], "replaced": d["replaced"],
            "_hint": "The pair is defined on the board: Altium's interactive differential-pair router and its Differential Pairs Routing rule use it. Save with altium_save."}),
        Err(mut e) => { if e.get("errorCode") == Some(&json!("net_not_on_board")) { e["_hint"] = json!("A net name is not on the board: altium_list_nets lists them."); } e }
    }
}

fn read_stack() -> Result<Value, Value> { agent_data(&agent::call("layer_stack", &[], None, Duration::from_secs(60))) }

fn as_list(v: Option<&Value>) -> Vec<Value> {
    match v { Some(Value::Array(a)) => a.clone(), Some(o @ Value::Object(_)) => vec![o.clone()], _ => vec![] }
}

/// altium_layer_stack {add?, remove?, set?, totalMm?}: edit the current board's stack (the read is in verbs.rs).
///   add:    [{kind: plane|signal, net?, name?, n?}]  (n = plane/mid number; default the lowest free one)
///   remove: [{name}]
///   set:    [{name, copperUm?, dielectricUm?, dk?, material?, net?, pullbackUm?, rename?}]
///   totalMm: board thickness: the dielectrics are spread evenly to reach it
pub fn layer_stack_edit(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let mut steps = Vec::new();
    let mut stack = match read_stack() { Ok(d) => d, Err(e) => return e };
    let layers = |st: &Value| st["layers"].as_array().cloned().unwrap_or_default();
    for a in as_list(args.get("add")) {
        let kind = a.get("kind").and_then(|v| v.as_str()).unwrap_or("signal");
        if kind != "plane" && kind != "signal" { return json!({"success": false, "errorCode": "bad_args", "error": "add.kind is plane or signal", "stack": stack}); }
        let key = if kind == "plane" { "plane" } else { "mid" };
        let used: Vec<i64> = layers(&stack).iter().filter_map(|l| l[key].as_i64()).collect();
        let n = a.get("n").and_then(|v| v.as_i64()).unwrap_or_else(|| (1..=30).find(|k| !used.contains(k)).unwrap_or(1));
        if used.contains(&n) { return json!({"success": false, "errorCode": "layer_exists", "error": format!("{kind} {n} is already in the stack"), "stack": stack}); }
        let mut p: Vec<(&str, String)> = vec![("op", "insert".into()), ("kind", kind.into()), ("n", n.to_string())];
        if let Some(net) = a.get("net").and_then(|v| v.as_str()) { p.push(("net", net.into())); }
        if let Some(nm) = a.get("name").and_then(|v| v.as_str()) { p.push(("name", nm.into())); }
        match agent_data(&agent::call("layer_stack_edit", &p, None, Duration::from_secs(90))) { Ok(d) => { stack = d; steps.push(json!({"added": kind, "n": n})); } Err(e) => return e }
    }
    for r in as_list(args.get("remove")) {
        let name = r.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let Some(l) = layers(&stack).into_iter().find(|l| l["name"].as_str().map(|x| x.eq_ignore_ascii_case(name)).unwrap_or(false)) else {
            return json!({"success": false, "errorCode": "layer_not_found", "error": format!("no layer named {name}"), "stack": stack});
        };
        let (kind, n) = if let Some(n) = l["plane"].as_i64() { ("plane", n) } else if let Some(n) = l["mid"].as_i64() { ("signal", n) } else {
            return json!({"success": false, "errorCode": "outer_layer", "error": "the top and bottom layers stay", "stack": stack});
        };
        match agent_data(&agent::call("layer_stack_edit", &[("op", "remove".into()), ("kind", kind.into()), ("n", n.to_string())], None, Duration::from_secs(90))) {
            Ok(d) => { stack = d; steps.push(json!({"removed": name})); } Err(e) => return e
        }
    }
    let mut sets = as_list(args.get("set"));
    // copper weights first, so a thickness target is spread over the final copper
    let (copper_sets, rest): (Vec<Value>, Vec<Value>) = sets.into_iter().partition(|x| x.get("copperUm").is_some() && x.get("dielectricUm").is_none());
    sets = rest;
    for x in copper_sets {
        let name = x.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
        let mut p: Vec<(&str, String)> = vec![("op", "set".into()), ("target", name.clone()), ("copperUm", (x["copperUm"].as_f64().unwrap_or(35.0).round() as i64).to_string())];
        if let Some(v) = x.get("pullbackUm").and_then(|v| v.as_f64()) { p.push(("pullbackUm", (v.round() as i64).to_string())); }
        for (k, a) in [("material", "material"), ("net", "net"), ("rename", "name")] { if let Some(v) = x.get(k).and_then(|v| v.as_str()) { p.push((a, v.into())); } }
        if let Some(v) = x.get("dk").and_then(|v| v.as_f64()) { p.push(("dk1000", ((v * 1000.0).round() as i64).to_string())); }
        match agent_data(&agent::call("layer_stack_edit", &p, None, Duration::from_secs(90))) { Ok(d) => { stack = d; steps.push(json!({"set": name})); } Err(e) => return e }
    }
    if let Some(total) = args.get("totalMm").and_then(|v| v.as_f64()) {
        let ls = layers(&stack);
        let copper: f64 = ls.iter().filter_map(|l| l["copperUm"].as_f64()).sum::<f64>();
        let gaps = ls.len().saturating_sub(1);
        let each = if gaps > 0 { ((total * 1000.0 - copper) / gaps as f64).round() } else { 0.0 };
        if each < 50.0 { return json!({"success": false, "errorCode": "too_thin", "error": format!("{total} mm leaves {each} um per dielectric"), "stack": stack}); }
        for l in ls.iter().take(gaps) {
            let name = l["name"].as_str().unwrap_or("").to_string();
            if !sets.iter().any(|x| x.get("name").and_then(|v| v.as_str()).map(|v| v.eq_ignore_ascii_case(&name)).unwrap_or(false) && x.get("dielectricUm").is_some()) {
                sets.push(json!({"name": name, "dielectricUm": each}));
            }
        }
    }
    for x in sets {
        let Some(name) = x.get("name").and_then(|v| v.as_str()) else { return json!({"success": false, "errorCode": "bad_args", "error": "set entries need name", "stack": stack}) };
        let mut p: Vec<(&str, String)> = vec![("op", "set".into()), ("target", name.into())];
        let num = |k: &str| x.get(k).and_then(|v| v.as_f64()).map(|v| (v.round() as i64).to_string());
        if let Some(v) = num("copperUm") { p.push(("copperUm", v)); }
        if let Some(v) = num("dielectricUm") { p.push(("dielectricUm", v)); }
        if let Some(v) = x.get("dk").and_then(|v| v.as_f64()) { p.push(("dk1000", ((v * 1000.0).round() as i64).to_string())); }
        if let Some(v) = num("pullbackUm") { p.push(("pullbackUm", v)); }
        for (k, a) in [("material", "material"), ("net", "net"), ("rename", "name")] { if let Some(v) = x.get(k).and_then(|v| v.as_str()) { p.push((a, v.into())); } }
        match agent_data(&agent::call("layer_stack_edit", &p, None, Duration::from_secs(90))) { Ok(d) => { stack = d; steps.push(json!({"set": name})); } Err(e) => return e }
    }
    json!({"success": true, "steps": steps, "copperLayers": stack["copperLayers"], "totalUm": stack["totalUm"], "layers": stack["layers"],
        "_hint": "The stack is changed on the board in memory: altium_save keeps it. Planes connect to their net's pads and vias through Altium's Power Plane Connect rule (relief by default); check with altium_run_drc. Inner signal layers route with altium_route_net {layer}. Fab-quote thickness is totalUm."})
}

/// altium_board_outline {filePath?, mech?, widthMm?, replace?}: the board shape as tracks and arcs on a
/// mechanical layer, the outline a fab house reads from the Gerbers.
pub fn board_outline(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let mech = args.get("mech").and_then(|v| v.as_i64()).unwrap_or(1).clamp(1, 16);
    let w = args.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(0.1);
    let raw = ((w / 25.4) * 10_000_000.0).round() as i64;
    let mut p: Vec<(&str, String)> = vec![("op", "draw".into()), ("mech", mech.to_string()), ("width", raw.to_string())];
    if args.get("replace").and_then(|v| v.as_bool()) == Some(true) { p.push(("replace", "1".into())); }
    match agent_data(&agent::call("outline_tracks", &p, None, Duration::from_secs(60))) {
        Ok(d) => {
            let drawn = d["drawn"].as_i64().unwrap_or(0);
            json!({"success": true, "layer": d["layer"], "drawn": drawn, "alreadyThere": d["alreadyThere"], "outlineVertices": d["outlineVertices"],
                "_hint": if drawn > 0 { "The outline is on the board in memory: altium_save keeps it, and the layer's Gerber now carries it (altium_export_manufacturing plots Mechanical 1)." }
                         else { "Nothing drawn: the layer already holds primitives (pass replace:true to draw the outline anyway), or the board has no shape (altium_set_outline)." }})
        }
        Err(e) => e,
    }
}

/// altium_set_track_width {filePath?, nets? | netClass?, widthMm, layer?}: widen (or narrow) the existing copper
/// on nets: rules only steer new routing, so a class's preferred width left its old tracks thin.
pub fn set_track_width(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let Some(w) = args.get("widthMm").and_then(|v| v.as_f64()).filter(|w| *w > 0.0 && *w < 20.0) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "widthMm is required (e.g. 0.5)"});
    };
    let mut nets = name_list(args.get("nets"));
    if let Some(class) = s(args, "netClass") {
        let r = agent::call("net_classes", &[("op", "list".into())], None, Duration::from_secs(60));
        let d = match agent_data(&r) { Ok(d) => d, Err(e) => return e };
        match d["classes"].as_array().and_then(|a| a.iter().find(|c| c["name"].as_str().map(|n| n.eq_ignore_ascii_case(&class)).unwrap_or(false))) {
            Some(c) => nets.extend(c["nets"].as_array().cloned().unwrap_or_default().iter().filter_map(|n| n.as_str().map(str::to_string))),
            None => return json!({"success": false, "errorCode": "class_not_found", "error": format!("no net class {class}"), "classes": d["classes"]}),
        }
    }
    if nets.is_empty() { return json!({"success": false, "errorCode": "bad_args", "error": "nets [..] or netClass is required"}); }
    let layer = match s(args, "layer").map(|l| l.to_ascii_lowercase()) {
        None => 0, Some(l) if l.starts_with("top") => 1, Some(l) if l.starts_with("bottom") => 32,
        Some(l) => match l.trim_start_matches("mid").trim_start_matches("inner").trim().parse::<i64>() { Ok(n) if (1..=30).contains(&n) => 1 + n, _ => return json!({"success": false, "errorCode": "bad_args", "error": "layer is top, bottom or mid N"}) },
    };
    let raw = ((w / 25.4) * 10_000_000.0).round() as i64;
    let r = agent::call("track_width", &[("nets", nets.join(";")), ("width", raw.to_string()), ("layer", layer.to_string())], None, Duration::from_secs(120));
    let d = match agent_data(&r) { Ok(d) => d, Err(e) => return e };
    let drc = crate::routing::routing_drc(&json!({}));
    json!({"success": true, "widthMm": w, "nets": nets, "changed": d["changed"], "byNet": d["byNet"],
        "drcAfter": {"errors": drc.get("errors"), "unconnected": drc.get("unconnected")},
        "_hint": "Existing tracks and arcs on those nets now have that width (component copper untouched). Wider copper can break clearance: drcAfter counts online DRC; altium_routing_drc {full:true} lists the violations. altium_save keeps it."})
}

/// raw Altium units (1e-4 mil) -> mm
fn raw_mm(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) / 10000.0 * 0.0254 }

fn inside(poly: &[(f64, f64)], x: f64, y: f64) -> bool {
    let mut c = false;
    let n = poly.len();
    for i in 0..n {
        let (xi, yi) = poly[i];
        let (xj, yj) = poly[(i + n - 1) % n];
        if (yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi { c = !c; }
    }
    c
}

fn seg_dist(px: f64, py: f64, (ax, ay): (f64, f64), (bx, by): (f64, f64)) -> f64 {
    let (dx, dy) = (bx - ax, by - ay);
    let l2 = dx * dx + dy * dy;
    let t = if l2 == 0.0 { 0.0 } else { (((px - ax) * dx + (py - ay) * dy) / l2).clamp(0.0, 1.0) };
    ((px - ax - t * dx).powi(2) + (py - ay - t * dy).powi(2)).sqrt()
}

/// Rect [l, b, r, t] grown by g.
fn grow(r: [f64; 4], g: f64) -> [f64; 4] { [r[0] - g, r[1] - g, r[2] + g, r[3] + g] }
fn hits(a: [f64; 4], b: [f64; 4]) -> bool { a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3] }

/// altium_find_space {near?|at?, part?|sizeMm?, side?, clearanceMm?, edgeMm?, count?, radiusMm?, check?}: free spots for a part
/// near another (clear of every other part on that side, of that side's copper, and inside the outline), or with
/// check:true the parts that already overlap or leave the outline.
pub fn find_space(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let rects = match agent_data(&agent::call("comp_rects", &[], None, Duration::from_secs(120))) { Ok(d) => d, Err(e) => return e };
    let st = crate::routing::routing_state(&json!({}));
    let poly: Vec<(f64, f64)> = st["outline"].as_array().cloned().unwrap_or_default().iter().filter_map(|p| Some((p[0].as_f64()?, p[1].as_f64()?))).collect();
    let parts: Vec<(String, [f64; 4], bool)> = rects["rects"].as_array().cloned().unwrap_or_default().iter()
        .map(|r| (r[0].as_str().unwrap_or("").to_string(), [raw_mm(&r[1]), raw_mm(&r[2]), raw_mm(&r[3]), raw_mm(&r[4])], r[5].as_bool().unwrap_or(false))).collect();
    let clr = args.get("clearanceMm").and_then(|v| v.as_f64()).unwrap_or(0.25);
    let edge = args.get("edgeMm").and_then(|v| v.as_f64()).unwrap_or(0.3);
    let in_outline = |r: [f64; 4]| -> bool {
        if poly.len() < 3 { return true; }
        let corners = [(r[0], r[1]), (r[2], r[1]), (r[2], r[3]), (r[0], r[3])];
        corners.iter().all(|&(x, y)| inside(&poly, x, y) && (0..poly.len()).all(|i| seg_dist(x, y, poly[i], poly[(i + 1) % poly.len()]) >= edge))
    };
    if args.get("check").and_then(|b| b.as_bool()) == Some(true) {
        let mut overlaps = Vec::new();
        for i in 0..parts.len() { for j in i + 1..parts.len() {
            if parts[i].2 == parts[j].2 && hits(parts[i].1, parts[j].1) { overlaps.push(json!([parts[i].0, parts[j].0])); }
        } }
        let outside: Vec<&String> = parts.iter().filter(|p| !in_outline(p.1)).map(|p| &p.0).collect();
        // precise: Altium's own batch DRC, whose Component Clearance rule measures primitive to primitive
        let precise = if args.get("precise").and_then(|b| b.as_bool()) == Some(true) {
            let d = crate::routing::routing_drc(&json!({"full": true}));
            let v: Vec<Value> = d["violations"].as_array().cloned().unwrap_or_default().into_iter()
                .filter(|x| x["rule"].as_str().map(|r| r.to_lowercase().replace(' ', "").contains("componentclearance")).unwrap_or(false)).collect();
            json!({"componentClearance": v, "count": v.len()})
        } else { Value::Null };
        return json!({"success": true, "overlaps": overlaps, "outsideOutline": outside, "parts": parts.len(), "precise": precise,
            "_hint": "Overlaps compare each part's extent as Altium's Component Clearance rule does: 3D bodies and pads when it has a body, else every primitive but text (silkscreen outline included). precise:true also runs Altium's batch DRC and lists its Component Clearance violations (primitive to primitive, against the board's rule). altium_find_space {near, part} finds a free spot; altium_move_parts moves it."});
    }
    let comp = |d: &str| st["components"].as_array().and_then(|a| a.iter().find(|c| c["ref"].as_str().map(|r| r.eq_ignore_ascii_case(d)).unwrap_or(false)).cloned());
    // what to place: an existing part (its extent and origin) or a size
    let me = s(args, "part").and_then(|p| parts.iter().find(|x| x.0.eq_ignore_ascii_case(&p)).cloned());
    let (w, h, off, my_bottom) = match (&me, args.get("sizeMm").and_then(|v| v.as_array())) {
        (Some((d, r, b)), _) => {
            let c = comp(d).unwrap_or(Value::Null);
            let (ox, oy) = (c["x"].as_f64().unwrap_or((r[0] + r[2]) / 2.0), c["y"].as_f64().unwrap_or((r[1] + r[3]) / 2.0));
            (r[2] - r[0], r[3] - r[1], (ox - (r[0] + r[2]) / 2.0, oy - (r[1] + r[3]) / 2.0), *b)
        }
        (None, Some(sz)) if sz.len() == 2 => (sz[0].as_f64().unwrap_or(1.0), sz[1].as_f64().unwrap_or(1.0), (0.0, 0.0), false),
        _ => return json!({"success": false, "errorCode": "bad_args", "error": "part (a designator on the board) or sizeMm [w, h] is required"}),
    };
    let bottom = match s(args, "side").as_deref() { Some("bottom") => true, Some("top") => false, _ => my_bottom };
    let (cx, cy) = if let Some(n) = s(args, "near") {
        match parts.iter().find(|x| x.0.eq_ignore_ascii_case(&n)) { Some((_, r, _)) => ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), None => return json!({"success": false, "errorCode": "near_not_found", "error": format!("{n} is not on the board")}) }
    } else if let Some(a) = args.get("at") {
        (a["x"].as_f64().unwrap_or(0.0), a["y"].as_f64().unwrap_or(0.0))
    } else { return json!({"success": false, "errorCode": "bad_args", "error": "near (a designator) or at {x, y} is required"}) };
    let mine = me.as_ref().map(|m| m.0.clone()).unwrap_or_default();
    let mut blocks: Vec<[f64; 4]> = parts.iter().filter(|p| p.2 == bottom && !p.0.eq_ignore_ascii_case(&mine)).map(|p| grow(p.1, clr)).collect();
    if args.get("copper").and_then(|b| b.as_bool()) != Some(false) {
        let layer = if bottom { 32 } else { 1 };
        for t in st["tracks"].as_array().cloned().unwrap_or_default() {
            if t["layerId"].as_i64() != Some(layer) { continue; }
            let (a, b, hw) = ((t["start"]["x"].as_f64().unwrap_or(0.0), t["start"]["y"].as_f64().unwrap_or(0.0)), (t["end"]["x"].as_f64().unwrap_or(0.0), t["end"]["y"].as_f64().unwrap_or(0.0)), t["width"].as_f64().unwrap_or(0.2) / 2.0);
            blocks.push(grow([a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)], hw + clr));
        }
        for v in st["vias"].as_array().cloned().unwrap_or_default() {
            let (x, y, r) = (v["position"]["x"].as_f64().unwrap_or(0.0), v["position"]["y"].as_f64().unwrap_or(0.0), v["size"].as_f64().unwrap_or(0.6) / 2.0);
            blocks.push(grow([x - r, y - r, x + r, y + r], clr));
        }
    }
    let count = args.get("count").and_then(|v| v.as_u64()).unwrap_or(5) as usize;
    let radius = args.get("radiusMm").and_then(|v| v.as_f64()).unwrap_or(10.0);
    let step = 0.25;
    let mut cands: Vec<(f64, f64, f64)> = Vec::new();
    let n = (radius / step).ceil() as i64;
    for i in -n..=n { for j in -n..=n {
        let (x, y) = (cx + i as f64 * step, cy + j as f64 * step);
        let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt();
        if d <= radius { cands.push((d, x, y)); }
    } }
    cands.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
    let mut spots: Vec<Value> = Vec::new();
    let mut taken: Vec<[f64; 4]> = Vec::new();
    for (d, x, y) in cands {
        let r = [x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0];
        if blocks.iter().any(|b| hits(r, *b)) || taken.iter().any(|t| hits(r, *t)) || !in_outline(r) { continue; }
        let round = |v: f64| (v * 1000.0).round() / 1000.0;
        spots.push(json!({"x": round(x + off.0), "y": round(y + off.1), "distanceMm": round(d), "extent": [round(r[0]), round(r[1]), round(r[2]), round(r[3])]}));
        taken.push(grow(r, clr));
        if spots.len() >= count { break; }
    }
    json!({"success": !spots.is_empty(), "errorCode": if spots.is_empty() { json!("no_space") } else { Value::Null }, "spots": spots,
        "part": if mine.is_empty() { Value::Null } else { json!(mine) }, "sizeMm": [((w * 1000.0).round() / 1000.0), ((h * 1000.0).round() / 1000.0)], "side": if bottom { "bottom" } else { "top" },
        "_hint": "spots[].x/y are where the part's origin goes: altium_move_parts {parts:[{ref, x, y, rotation}]}, then altium_repour (copper pours are not avoided: a pour clears around the new pads when repoured). Each spot keeps clearanceMm between part extents (3D bodies and pads, or every primitive but text for a part with no body, as Altium's Component Clearance does), from that side's tracks and vias, and edgeMm from the outline; nearest first. altium_find_space {check:true} lists parts that already overlap."})
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn free_space_geometry() {
        let sq = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
        assert!(inside(&sq, 5.0, 5.0));
        assert!(!inside(&sq, 11.0, 5.0));
        assert!((seg_dist(5.0, 5.0, (0.0, 0.0), (10.0, 0.0)) - 5.0).abs() < 1e-9);
        assert!(hits([0.0, 0.0, 2.0, 2.0], [1.0, 1.0, 3.0, 3.0]));
        assert!(!hits([0.0, 0.0, 1.0, 1.0], grow([1.2, 0.0, 2.0, 1.0], 0.1)));
        assert!(hits([0.0, 0.0, 1.0, 1.0], grow([1.2, 0.0, 2.0, 1.0], 0.25)));
    }
}

/// altium_selection {filePath?}: what is selected in the current board or sheet.
pub fn selection(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    if let Some(p) = s(args, "filePath") { if let Some(e) = support::must_open(&p, 60) { return e; } }
    let set = name_list(args.get("select"));
    let p: Vec<(&str, String)> = if set.is_empty() { vec![] } else { vec![("set", set.join(";"))] };
    let d = match agent_data(&agent::call("selection", &p, None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };
    let board = d["kind"] == json!("board");
    let rows: Vec<Value> = d["selected"].as_array().cloned().unwrap_or_default().iter().map(|r| if board {
        let mm = |v: &Value| (raw_mm(v) * 1000.0).round() / 1000.0;
        json!({"ref": r[0], "x": mm(&r[1]), "y": mm(&r[2]), "rotation": r[3].as_f64().unwrap_or(0.0) / 1000.0, "side": if r[4].as_bool() == Some(true) { "bottom" } else { "top" },
               "footprint": r[5], "widthMm": mm(&r[6]), "heightMm": mm(&r[7])})
    } else {
        json!({"designator": r[0], "xMil": r[1], "yMil": r[2], "orientation": r[3], "libReference": r[4], "comment": r[5]})
    }).collect();
    json!({"success": true, "kind": d["kind"], "document": d["document"], "count": rows.len(), "selected": rows,
        "_hint": if rows.is_empty() { "Nothing is selected in the current document. Select parts in Altium (or altium_select_net / altium_sch_zoom select), then ask again." }
                 else if board { "Board positions in mm (Altium's frame), as altium_move_parts takes them: move these with {ref, x, y} or {ref, dx, dy}." }
                 else { "Sheet positions in mils, as altium_sch_edit {action:'move'} takes them." }})
}

/// altium_select_items {filePath?, refs?, clear?}: select parts by designator, everything else deselected; or clear.
pub fn select_items(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    if let Some(p) = s(args, "filePath") { if let Some(e) = support::must_open(&p, 60) { return e; } }
    let refs = name_list(args.get("refs"));
    let clear = args.get("clear").and_then(|v| v.as_bool()) == Some(true);
    if refs.is_empty() && !clear { return json!({"success": false, "errorCode": "bad_args", "error": "refs: [designator], or clear: true"}); }
    // the standard's where: board by default, or what filePath names. A mismatch with the current document is refused.
    let named = s(args, "filePath").map(|p| if p.to_lowercase().ends_with(".schdoc") { "sheet" } else { "board" });
    let wher = args.get("where").and_then(|v| v.as_str()).or(named).unwrap_or("board").to_string();
    if wher != "board" && wher != "sheet" { return json!({"success": false, "errorCode": "bad_args", "error": format!("where is board or sheet (got {wher})")}); }
    let now = match agent_data(&agent::call("selection", &[], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };
    if now["kind"].as_str() != Some(wher.as_str()) {
        return json!({"success": false, "errorCode": "wrong_document", "error": format!("where is {wher}, but the current document is a {}: name the document with filePath", now["kind"].as_str().unwrap_or("different kind")), "document": now["document"], "mutated": false});
    }
    // a name no part has clears every part, on a board and on a sheet
    let set = if refs.is_empty() { "\u{1}none".to_string() } else { refs.join(";") };
    let d = match agent_data(&agent::call("selection", &[("set", set)], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };
    let got: Vec<String> = d["selected"].as_array().cloned().unwrap_or_default().iter().filter_map(|r| r[0].as_str().map(str::to_string)).collect();
    let failed: Vec<Value> = refs.iter().filter(|r| !got.iter().any(|g| g.eq_ignore_ascii_case(r))).map(|r| json!({"ref": r, "error": "not on this document"})).collect();
    let verified = if clear && refs.is_empty() { got.is_empty() } else { failed.is_empty() && got.len() == refs.len() };
    json!({"success": verified, "kind": d["kind"], "document": d["document"], "selected": got, "failed": failed, "verified": verified,
        "_hint": "The parts Altium reports selected after the call, read back: everything else is deselected. failed names designators not on this document. select_net selects a whole net; altium_selection reads what the user selected."})
}

fn dist(a: (f64, f64), b: (f64, f64)) -> f64 { ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() }

pub fn mst_pub(pts: &[(f64, f64)]) -> f64 { mst(pts) }

/// Minimum spanning tree length of points (Prim's, O(n^2): nets are small).
fn mst(pts: &[(f64, f64)]) -> f64 {
    if pts.len() < 2 { return 0.0; }
    let mut inside = vec![false; pts.len()];
    let mut best = vec![f64::MAX; pts.len()];
    best[0] = 0.0;
    let mut total = 0.0;
    for _ in 0..pts.len() {
        let mut u = usize::MAX;
        for i in 0..pts.len() { if !inside[i] && (u == usize::MAX || best[i] < best[u]) { u = i; } }
        inside[u] = true;
        total += best[u];
        for v in 0..pts.len() { if !inside[v] { let d = dist(pts[u], pts[v]); if d < best[v] { best[v] = d; } } }
    }
    total
}

/// altium_check_orientation {filePath?, parts?, minImprovementMm?, planeNetPads?}: advisory. For each 2-pad part,
/// every orthogonal rotation is scored in place: a routable net by its airline (MST) length with the pad there, a
/// plane-like net (many pads, GND) by the distance to its nearest same-net pad. Parts whose best rotation beats the
/// current one by minImprovementMm are reported. Nothing is moved.
pub fn check_orientation(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let st = crate::routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
    let min_gain = args.get("minImprovementMm").and_then(|v| v.as_f64()).unwrap_or(0.6);
    let plane_pads = args.get("planeNetPads").and_then(|v| v.as_u64()).unwrap_or(12) as usize;
    let want = name_list(args.get("parts")).into_iter().map(|x| x.to_ascii_uppercase()).collect::<Vec<_>>();
    let pads = st["pads"].as_array().cloned().unwrap_or_default();
    let comps = st["components"].as_array().cloned().unwrap_or_default();
    let mut net_pads: std::collections::HashMap<String, Vec<(String, (f64, f64))>> = std::collections::HashMap::new();
    for p in &pads {
        let n = p["net"].as_str().unwrap_or("");
        if n.is_empty() { continue; }
        net_pads.entry(n.to_string()).or_default().push((p["ref"].as_str().unwrap_or("").to_string(), (p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0))));
    }
    let mut findings = Vec::new();
    let mut checked = 0;
    for c in &comps {
        let r = c["ref"].as_str().unwrap_or("").to_string();
        if !want.is_empty() && !want.contains(&r.to_ascii_uppercase()) { continue; }
        let mine: Vec<&Value> = pads.iter().filter(|p| p["ref"].as_str() == Some(&r)).collect();
        if mine.len() != 2 { continue; }
        checked += 1;
        let (cx, cy, rot) = (c["x"].as_f64().unwrap_or(0.0), c["y"].as_f64().unwrap_or(0.0), c["rotation"].as_f64().unwrap_or(0.0));
        let score = |delta: f64| -> f64 {
            let a = delta.to_radians();
            let mut total = 0.0;
            for p in &mine {
                let net = p["net"].as_str().unwrap_or("");
                if net.is_empty() { continue; }
                let (px, py) = (p["x"].as_f64().unwrap_or(0.0) - cx, p["y"].as_f64().unwrap_or(0.0) - cy);
                let at = (cx + px * a.cos() - py * a.sin(), cy + px * a.sin() + py * a.cos());
                let others: Vec<(f64, f64)> = net_pads.get(net).map(|v| v.iter().filter(|(o, _)| o != &r).map(|(_, q)| *q).collect()).unwrap_or_default();
                if others.is_empty() { continue; }
                total += if others.len() + 1 > plane_pads {
                    others.iter().map(|q| dist(at, *q)).fold(f64::MAX, f64::min)
                } else {
                    let mut pts = others.clone(); pts.push(at); mst(&pts)
                };
            }
            total
        };
        let now = score(0.0);
        let mut best = (0.0, now);
        for d in [90.0, 180.0, 270.0] { let sc = score(d); if sc < best.1 - 1e-9 { best = (d, sc); } }
        if now - best.1 >= min_gain {
            let round = |v: f64| (v * 1000.0).round() / 1000.0;
            findings.push(json!({"ref": r, "rotation": rot, "suggested": (rot + best.0).rem_euclid(360.0), "airlineNowMm": round(now), "airlineThenMm": round(best.1), "savesMm": round(now - best.1)}));
        }
    }
    findings.sort_by(|a, b| b["savesMm"].as_f64().partial_cmp(&a["savesMm"].as_f64()).unwrap_or(std::cmp::Ordering::Equal));
    json!({"success": true, "checked": checked, "suggestions": findings,
        "_hint": "Advisory only: each 2-pad part's rotations scored by airline length (MST of a routable net with the pad there; distance to the nearest pad of a plane-like net such as GND). Rotate with altium_move_parts {parts:[{ref, rotation}]} (position kept), then reroute those nets. Routed copper is not considered: on a routed board, rip up first or treat these as hints."})
}

/// altium_replicate_layout {filePath?, source: [refs], targets: [[refs]] (same order as source), anchor?}: copy one
/// channel's placement to others. Each target channel keeps its anchor part (the first, or `anchor`'s index) where
/// it is; every other part goes to the same offset and rotation from it as in the source.
pub fn replicate_layout(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let src = name_list(args.get("source"));
    let targets: Vec<Vec<String>> = args.get("targets").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().map(|t| name_list(Some(t))).collect();
    if src.len() < 2 || targets.is_empty() { return json!({"success": false, "errorCode": "bad_args", "error": "source: [refs] (2 or more) and targets: [[refs], ...] in the same order are required"}); }
    if let Some(bad) = targets.iter().find(|t| t.len() != src.len()) { return json!({"success": false, "errorCode": "bad_args", "error": format!("target {:?} has {} parts, the source {}", bad, bad.len(), src.len())}); }
    let anchor = args.get("anchor").and_then(|v| v.as_str()).and_then(|a| src.iter().position(|x| x.eq_ignore_ascii_case(a))).unwrap_or(0);
    let st = crate::routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
    let comp = |r: &str| st["components"].as_array().and_then(|c| c.iter().find(|c| c["ref"].as_str().map(|x| x.eq_ignore_ascii_case(r)).unwrap_or(false)).cloned());
    let get = |r: &str| -> Option<(f64, f64, f64, String, String)> { comp(r).map(|c| (c["x"].as_f64().unwrap_or(0.0), c["y"].as_f64().unwrap_or(0.0), c["rotation"].as_f64().unwrap_or(0.0), c["side"].as_str().unwrap_or("").to_string(), c["pattern"].as_str().unwrap_or("").to_string())) };
    let mut srcp = Vec::new();
    for r in &src { match get(r) { Some(p) => srcp.push(p), None => return json!({"success": false, "errorCode": "part_not_found", "error": format!("{r} is not on the board")}) } }
    let (ax, ay, arot, _, _) = srcp[anchor].clone();
    let mut moves = Vec::new();
    let mut warnings = Vec::new();
    for t in &targets {
        let Some((tx, ty, trot, _, _)) = get(&t[anchor]) else { return json!({"success": false, "errorCode": "part_not_found", "error": format!("{} is not on the board", t[anchor])}) };
        // the target channel may sit rotated against the source: turn the offsets by the anchors' difference
        let d = (trot - arot).to_radians();
        for (i, r) in t.iter().enumerate() {
            if i == anchor { continue; }
            let Some(tp) = get(r) else { return json!({"success": false, "errorCode": "part_not_found", "error": format!("{r} is not on the board")}) };
            if tp.4 != srcp[i].4 { warnings.push(json!({"ref": r, "footprint": tp.4, "source": src[i], "sourceFootprint": srcp[i].4})); }
            let (ox, oy) = (srcp[i].0 - ax, srcp[i].1 - ay);
            let (x, y) = (tx + ox * d.cos() - oy * d.sin(), ty + ox * d.sin() + oy * d.cos());
            moves.push(json!({"ref": r, "x": (x * 10000.0).round() / 10000.0, "y": (y * 10000.0).round() / 10000.0, "rotation": (srcp[i].2 + (trot - arot)).rem_euclid(360.0)}));
        }
    }
    let m = crate::routing::move_parts(&json!({"parts": moves}));
    json!({"success": m.get("success").and_then(|b| b.as_bool()) == Some(true), "moved": moves.len(), "moves": moves, "footprintMismatches": warnings,
        "errorCode": m.get("errorCode"), "mismatches": m.get("mismatches"),
        "_hint": "Each target channel's anchor stayed put and its other parts took the source's offsets and rotations (turned by the anchors' rotation difference). Routing is not copied: route the targets (altium_route_net) or use Altium's Copy Room Formats for copper. Check with altium_find_space {check:true} and altium_routing_drc."})
}

#[cfg(test)]
mod room_tests {
    use super::*;
    #[test]
    fn a_room_fits_the_members_pads_plus_the_margin() {
        let st = json!({"pads": [{"ref": "U1", "x": 10.0, "y": 10.0, "sizeX": 0.6, "sizeY": 0.8}, {"ref": "U1", "x": 14.0, "y": 12.0, "sizeX": 0.6, "sizeY": 0.8},
                                 {"ref": "R9", "x": 30.0, "y": 30.0, "sizeX": 1.0, "sizeY": 1.0}]});
        let b = pads_box(&st, &["u1".to_string()], 1.0).unwrap();
        assert!((b.0 - 8.5).abs() < 1e-9 && (b.3 - 13.5).abs() < 1e-9);
        assert!(pads_box(&st, &["U7".to_string()], 1.0).is_none());
    }
}