main
Colby Knox 0.2.80 (unreleased): place_decoupling, plan_fanout, estimate_cost and check_clearance from engine 0.10.3 (236/236 stand… 8144f67
//! Board edits from the EDA Bridge Standard's batch 3 (proposed by kicad-lane): remove, edit and align parts, set the
//! copper layer count, copy a channel's routing, measure part clearances and remove board graphics. Millimetres, the
//! board frame, KiCad layer names; every edit takes expectedRevision and dryRun and answers the board's new revision.
use adom_eda_checks::placement::part_boxes;
use crate::routing::{self, apply, guarded, layer_id, layer_name, raw, PER_MM, BOTTOM, TOP};
use crate::sch::{agent_data, clean, st as sv};
use crate::agent;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;

type Rect = (f64, f64, f64, f64);

fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }
fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }
fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }
fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }
fn refs_of(v: Option<&Value>) -> Vec<String> { v.and_then(|x| x.as_array()).map(|a| a.iter().map(sv).filter(|s| !s.is_empty()).collect()).unwrap_or_default() }

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

// -- remove_parts ---------------------------------------------------------------------------------------------------------

/// altium_remove_parts {refs, allowLocked?, expectedRevision?, dryRun?}
pub fn remove_parts(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let refs = refs_of(args.get("refs"));
    if refs.is_empty() { return bad("refs: [\"R7\", ...] is required"); }
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let have: BTreeSet<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_uppercase())).collect();
    let missing: Vec<&String> = refs.iter().filter(|r| !have.contains(&r.to_uppercase())).collect();
    if !missing.is_empty() { return json!({"success": false, "errorCode": "part_not_found", "error": format!("not on the board: {missing:?}")}); }
    let nets_of = |r: &str| -> Vec<String> { let mut n: Vec<String> = st["pads"].as_array().cloned().unwrap_or_default().iter().filter(|p| p["ref"].as_str().map(|x| x.eq_ignore_ascii_case(r)).unwrap_or(false)).map(|p| st_net(p)).filter(|n| !n.is_empty()).collect(); n.sort(); n.dedup(); n };
    if dry(args) { return json!({"success": true, "dryRun": true, "removed": refs.iter().map(|r| json!({"ref": r, "nets": nets_of(r)})).collect::<Vec<_>>(), "revision": st["revision"]}); }
    let allow = if args.get("allowLocked").and_then(|v| v.as_bool()) == Some(true) { "1" } else { "0" };
    let ops: Vec<String> = refs.iter().map(|r| format!("R|{}|{allow}", clean(r))).collect();
    let mut out = apply(&ops, &st, "remove_parts");
    let res = out["results"].as_array().cloned().unwrap_or_default();
    let (mut removed, mut failed) = (vec![], vec![]);
    for (r, x) in refs.iter().zip(res.iter()) {
        let s = st_str(x);
        match s.strip_prefix("ok:") {
            Some(n) => removed.push(json!({"ref": r, "nets": n.split(';').filter(|x| !x.is_empty()).collect::<Vec<_>>()})),
            None => failed.push(json!({"ref": r, "error": if s.contains("part_locked") { "part_locked: pass allowLocked:true".to_string() } else { s.trim_start_matches("err:").to_string() }})),
        }
    }
    if !failed.is_empty() { out["success"] = json!(false); out["errorCode"] = json!(if failed.iter().any(|f| f["error"].as_str().map(|e| e.starts_with("part_locked")).unwrap_or(false)) { "part_locked" } else { "some_not_removed" }); }
    out["removed"] = json!(removed); out["failedParts"] = json!(failed);
    out.as_object_mut().map(|o| o.remove("state"));
    out["_hint"] = json!("Tracks and vias that met the pads stay: altium_routing_state shows them (unconnected and splitNets). A part still on the schematic comes back at the next altium_update_pcb.");
    out
}

fn st_net(p: &Value) -> String { p["net"].as_str().unwrap_or("").to_string() }
fn st_str(v: &Value) -> String { v.as_str().unwrap_or("").to_string() }

// -- edit_parts -----------------------------------------------------------------------------------------------------------

/// altium_edit_parts {edits:[{ref, value?, newRef?, locked?, excludeFromBom?, ...}], expectedRevision?, dryRun?}
pub fn edit_parts(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let Some(edits) = args.get("edits").and_then(|v| v.as_array()).filter(|a| !a.is_empty()) else { return bad("edits: [{ref, value?, newRef?, locked?, excludeFromBom?}] is required") };
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let have: BTreeSet<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_uppercase())).collect();
    let mut ops = Vec::new();
    let mut owner = Vec::new();
    let mut failed = Vec::new();
    for e in edits {
        let r = st_str(&e["ref"]);
        if !have.contains(&r.to_uppercase()) { failed.push(json!({"ref": r, "error": "part_not_found"})); continue; }
        // what Altium keeps elsewhere: do-not-populate is a variant, mounting comes from the footprint, parameters from the schematic
        for (k, why) in [("dnp", "do-not-populate is an assembly variant in Altium: altium_variants"), ("excludeFromPos", "Altium has no per-part pick-and-place exclusion on the board"),
            ("mount", "the mounting type comes from the footprint's pads in Altium"), ("fields", "a placed part's parameters come from the schematic in Altium: altium_sheet_params")] {
            if e.get(k).is_some() { failed.push(json!({"ref": r, "field": k, "error": format!("not_supported: {why}")})); }
        }
        if let Some(n) = e.get("newRef").and_then(|v| v.as_str()) {
            if have.contains(&n.to_uppercase()) && !n.eq_ignore_ascii_case(&r) { failed.push(json!({"ref": r, "error": format!("designator_taken: {n} is on the board")})); continue; }
            ops.push(format!("E|{}|designator|{}", clean(&r), clean(n)));
            owner.push(r.clone());
        }
        let cur = e.get("newRef").and_then(|v| v.as_str()).unwrap_or(&r).to_string();
        if let Some(v) = e.get("value").and_then(|v| v.as_str()) { ops.push(format!("E|{}|comment|{}", clean(&cur), clean(v))); owner.push(r.clone()); }
        if let Some(b) = e.get("locked").and_then(|v| v.as_bool()) { ops.push(format!("E|{}|locked|{}", clean(&cur), if b { 1 } else { 0 })); owner.push(r.clone()); }
        // Altium's component kinds: 0 Standard, 5 Standard (no BOM)
        if let Some(b) = e.get("excludeFromBom").and_then(|v| v.as_bool()) { ops.push(format!("E|{}|kind|{}", clean(&cur), if b { 5 } else { 0 })); owner.push(r.clone()); }
    }
    if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no edit Altium can make on the board", "failed": failed}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "steps": ops.len(), "failed": failed, "revision": st["revision"]}); }
    let mut out = apply(&ops, &st, "edit_parts");
    let res = out["results"].as_array().cloned().unwrap_or_default();
    let mut after: BTreeMap<String, Value> = BTreeMap::new();
    for (r, x) in owner.iter().zip(res.iter()) {
        let s = st_str(x);
        if s.starts_with("err") { failed.push(json!({"ref": r, "error": s.trim_start_matches("err:")})); continue; }
        let p: Vec<&str> = s.trim_start_matches("ok:").split('|').collect();
        after.insert(r.clone(), json!({"ref": p.first(), "value": p.get(1), "locked": p.get(2).map(|x| *x == "true"), "excludeFromBom": p.get(3).map(|x| *x == "5" || *x == "4")}));
    }
    out["edited"] = json!(after.into_iter().map(|(r, a)| json!({"ref": r, "after": a})).collect::<Vec<_>>());
    if !failed.is_empty() { out["success"] = json!(false); out["errorCode"] = json!("some_not_applied"); }
    out["failed"] = json!(failed);
    out.as_object_mut().map(|o| o.remove("state"));
    out["_hint"] = json!("Designators and values the schematic owns come back at the next altium_update_pcb: change them on the sheet too (altium_sch_edit). excludeFromBom sets Altium's component kind Standard (no BOM).");
    out
}

// -- align_parts ----------------------------------------------------------------------------------------------------------

/// Where each part's anchor goes so its box (or anchor) lines up. Pure.
pub fn align_plan(parts: &[(String, f64, f64, Rect)], mode: &str, to: Option<f64>, gap: Option<f64>, by_anchor: bool) -> Result<Vec<(String, f64, f64)>, String> {
    if parts.len() < 2 { return Err("align needs at least two parts".into()); }
    let left = |p: &(String, f64, f64, Rect)| if by_anchor { p.1 } else { p.3 .0 };
    let right = |p: &(String, f64, f64, Rect)| if by_anchor { p.1 } else { p.3 .2 };
    let bottom = |p: &(String, f64, f64, Rect)| if by_anchor { p.2 } else { p.3 .1 };
    let top = |p: &(String, f64, f64, Rect)| if by_anchor { p.2 } else { p.3 .3 };
    let cx = |p: &(String, f64, f64, Rect)| if by_anchor { p.1 } else { (p.3 .0 + p.3 .2) / 2.0 };
    let cy = |p: &(String, f64, f64, Rect)| if by_anchor { p.2 } else { (p.3 .1 + p.3 .3) / 2.0 };
    let n = parts.len() as f64;
    let out: Vec<(String, f64, f64)> = match mode {
        "left" => { let t = to.unwrap_or_else(|| parts.iter().map(left).fold(f64::MAX, f64::min)); parts.iter().map(|p| (p.0.clone(), p.1 + t - left(p), p.2)).collect() }
        "right" => { let t = to.unwrap_or_else(|| parts.iter().map(right).fold(f64::MIN, f64::max)); parts.iter().map(|p| (p.0.clone(), p.1 + t - right(p), p.2)).collect() }
        "bottom" => { let t = to.unwrap_or_else(|| parts.iter().map(bottom).fold(f64::MAX, f64::min)); parts.iter().map(|p| (p.0.clone(), p.1, p.2 + t - bottom(p))).collect() }
        "top" => { let t = to.unwrap_or_else(|| parts.iter().map(top).fold(f64::MIN, f64::max)); parts.iter().map(|p| (p.0.clone(), p.1, p.2 + t - top(p))).collect() }
        "centerX" => { let t = to.unwrap_or_else(|| parts.iter().map(cx).sum::<f64>() / n); parts.iter().map(|p| (p.0.clone(), p.1 + t - cx(p), p.2)).collect() }
        "centerY" => { let t = to.unwrap_or_else(|| parts.iter().map(cy).sum::<f64>() / n); parts.iter().map(|p| (p.0.clone(), p.1, p.2 + t - cy(p))).collect() }
        "distributeX" | "distributeY" => {
            let xax = mode == "distributeX";
            let mut v: Vec<&(String, f64, f64, Rect)> = parts.iter().collect();
            v.sort_by(|a, b| (if xax { cx(a) } else { cy(a) }).partial_cmp(&(if xax { cx(b) } else { cy(b) })).unwrap());
            let (first, last) = (if xax { cx(v[0]) } else { cy(v[0]) }, if xax { cx(v[v.len() - 1]) } else { cy(v[v.len() - 1]) });
            let step = gap.unwrap_or((last - first) / (v.len() - 1) as f64);
            v.iter().enumerate().map(|(i, p)| { let t = first + step * i as f64; if xax { (p.0.clone(), p.1 + t - cx(p), p.2) } else { (p.0.clone(), p.1, p.2 + t - cy(p)) } }).collect()
        }
        o => return Err(format!("mode {o}: left, right, top, bottom, centerX, centerY, distributeX or distributeY")),
    };
    Ok(out.into_iter().map(|(r, x, y)| (r, r3(x), r3(y))).collect())
}

fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }

fn in_poly(p: (f64, f64), poly: &[(f64, f64)]) -> bool {
    let mut inside = false;
    let n = poly.len();
    for k in 0..n { let (a, b) = (poly[k], poly[(k + n - 1) % n]); if (a.1 > p.1) != (b.1 > p.1) && p.0 < (b.0 - a.0) * (p.1 - a.1) / (b.1 - a.1) + a.0 { inside = !inside; } }
    inside
}

/// altium_align_parts {refs, mode, by?, to?, gapMm?, allowOverlap?, allowOutside?, expectedRevision?, dryRun?}
pub fn align_parts(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let refs = refs_of(args.get("refs"));
    let Some(mode) = args.get("mode").and_then(|v| v.as_str()) else { return bad("mode is required: left, right, top, bottom, centerX, centerY, distributeX, distributeY") };
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let boxes = part_boxes(&st, &BTreeMap::new());
    let mut parts = Vec::new();
    for r in &refs {
        let Some(c) = st["components"].as_array().and_then(|a| a.iter().find(|c| c["ref"].as_str().map(|x| x.eq_ignore_ascii_case(r)).unwrap_or(false))) else { return json!({"success": false, "errorCode": "part_not_found", "error": format!("{r} is not on the board")}) };
        let b = boxes.get(st_str(&c["ref"]).as_str()).map(|x| x.1).unwrap_or((f(&c["x"]), f(&c["y"]), f(&c["x"]), f(&c["y"])));
        parts.push((st_str(&c["ref"]), f(&c["x"]), f(&c["y"]), b));
    }
    let by_anchor = args.get("by").and_then(|v| v.as_str()) == Some("anchor");
    let plan = match align_plan(&parts, mode, args.get("to").and_then(|v| v.as_f64()), args.get("gapMm").and_then(|v| v.as_f64()), by_anchor) { Ok(p) => p, Err(e) => return bad(e) };
    // the checks move_parts would make: no courtyard overlap with another part, inside the outline
    let moved: BTreeMap<&str, Rect> = plan.iter().zip(parts.iter()).map(|((r, x, y), p)| (r.as_str(), (p.3 .0 + x - p.1, p.3 .1 + y - p.2, p.3 .2 + x - p.1, p.3 .3 + y - p.2))).collect();
    let mut problems = Vec::new();
    if args.get("allowOverlap").and_then(|v| v.as_bool()) != Some(true) {
        for (r, b) in &moved {
            let side = boxes.get(*r).map(|x| x.0).unwrap_or(false);
            for (o, (os, ob)) in &boxes {
                if o.as_str() == *r || *os != side { continue; }
                let ob = moved.get(o.as_str()).copied().unwrap_or(*ob);
                if hit(*b, ob) && r < &o.as_str() || (hit(*b, ob) && !moved.contains_key(o.as_str())) { problems.push(json!({"ref": r, "problem": "overlap", "with": o})); }
            }
        }
    }
    let ring: Vec<(f64, f64)> = st["outline"].as_array().cloned().unwrap_or_default().iter().map(|p| (f(&p[0]), f(&p[1]))).collect();
    if args.get("allowOutside").and_then(|v| v.as_bool()) != Some(true) && ring.len() >= 3 {
        for (r, b) in &moved { if [(b.0, b.1), (b.2, b.1), (b.2, b.3), (b.0, b.3)].iter().any(|p| !in_poly(*p, &ring)) { problems.push(json!({"ref": r, "problem": "outside_board"})); } }
    }
    let targets: Vec<Value> = plan.iter().map(|(r, x, y)| json!({"ref": r, "x": x, "y": y})).collect();
    if !problems.is_empty() { return json!({"success": false, "errorCode": "align_blocked", "error": "the aligned parts would overlap or leave the board", "problems": problems, "targets": targets, "_hint": "Pass allowOverlap or allowOutside to align anyway, or choose another line (to)."}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "targets": targets, "revision": st["revision"]}); }
    let mut out = routing::move_parts(&json!({"parts": targets, "expectedRevision": st["revision"]}));
    out["targets"] = json!(targets);
    out.as_object_mut().map(|o| o.remove("state"));
    out
}

// -- set_layer_count ---------------------------------------------------------------------------------------------------------

/// altium_set_layer_count {count: 2|4|6|8, expectedRevision?, dryRun?}
pub fn set_layer_count(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let Some(count) = args.get("count").and_then(|v| v.as_i64()).filter(|c| [2, 4, 6, 8].contains(c)) else { return bad("count: 2, 4, 6 or 8") };
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let stack = match agent_data(&agent::call("layer_stack", &[], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };
    let layers = stack["layers"].as_array().cloned().unwrap_or_default();
    let inner: Vec<&Value> = layers.iter().filter(|l| l["mid"].as_i64().is_some() || l["plane"].as_i64().is_some()).collect();
    let now = inner.len() as i64 + 2;
    let total_mm = stack["totalUm"].as_f64().map(|u| u / 1000.0);
    let mut edit = json!({});
    if count > now {
        edit["add"] = json!((0..(count - now)).map(|_| json!({"kind": "signal"})).collect::<Vec<_>>());
    } else if count < now {
        // remove inner layers from the bottom of the stack up, refusing any that carries copper
        let used = layers_with_copper(&st);
        let drop: Vec<&&Value> = inner.iter().rev().take((now - count) as usize).collect();
        let busy: Vec<String> = drop.iter().filter_map(|l| { let n = copper_names(&[json!({}), (**l).clone(), json!({})])[1].clone(); if used.contains(&n) { Some(format!("{} ({n})", st_str(&l["name"]))) } else { None } }).collect();
        if !busy.is_empty() { return json!({"success": false, "errorCode": "layer_in_use", "error": format!("these layers still carry copper: {busy:?}"), "_hint": "Clear them first (altium_layers_in_use shows what is on each)."}); }
        edit["remove"] = json!(drop.iter().map(|l| json!({"name": l["name"]})).collect::<Vec<_>>());
    } else {
        return json!({"success": true, "changed": false, "layers": copper_names(&layers), "stackup": stack, "revision": st["revision"]});
    }
    if let Some(t) = total_mm { edit["totalMm"] = json!(t); }
    if dry(args) { return json!({"success": true, "dryRun": true, "from": now, "to": count, "plan": edit, "revision": st["revision"]}); }
    let r = crate::design::layer_stack_edit(&edit);
    if r.get("success").and_then(|b| b.as_bool()) != Some(true) { return r; }
    let after = routing::routing_state(&json!({}));
    json!({"success": true, "changed": true, "from": now, "to": count, "layers": copper_names(r["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[])), "stackup": {"layers": r["layers"], "totalUm": r["totalUm"]},
        "revision": after["revision"], "_hint": "New inner layers are signal layers with even dielectrics keeping the board's thickness: re-check an impedance-controlled stack-up with altium_layer_stack. Rules and classes are unchanged; altium_save keeps it."})
}

/// The stack's copper layers by the board model's names, top to bottom: F.Cu, the inner layers, B.Cu. Altium names a
/// mid layer by its number (In<n>.Cu) and an internal plane by its layer id (L<38+n>) in the board model.
fn copper_names(layers: &[Value]) -> Vec<String> {
    let n = layers.len();
    layers.iter().enumerate().map(|(i, l)| {
        if let Some(m) = l["mid"].as_i64() { format!("In{m}.Cu") } else if let Some(p) = l["plane"].as_i64() { format!("L{}", 38 + p) }
        else if i == 0 { "F.Cu".into() } else if i + 1 == n { "B.Cu".into() } else { st_str(&l["name"]) }
    }).collect()
}

/// The copper layers the board model shows copper on (tracks, arcs, pads on one layer, pours).
fn layers_with_copper(st: &Value) -> BTreeSet<String> {
    let mut s = BTreeSet::new();
    for k in ["tracks", "arcs", "pads", "polygons"] { for x in st[k].as_array().cloned().unwrap_or_default() { s.insert(st_str(&x["layer"])); } }
    s
}

// -- copy_routing ---------------------------------------------------------------------------------------------------------

/// The net each source net becomes, by pairing parts: a pad's net maps to its partner pad's net. Pure.
pub fn net_map(pads: &[Value], pairs: &[(String, String)]) -> Result<BTreeMap<String, String>, Vec<String>> {
    let key = |r: &str, n: &str| format!("{}.{}", r.to_uppercase(), n.to_uppercase());
    let net_at: BTreeMap<String, String> = pads.iter().filter_map(|p| Some((key(p["ref"].as_str()?, p["name"].as_str()?), st_net(p)))).collect();
    let mut m: BTreeMap<String, String> = BTreeMap::new();
    let mut conflicts = Vec::new();
    for (a, b) in pairs {
        for p in pads.iter().filter(|p| p["ref"].as_str().map(|x| x.eq_ignore_ascii_case(a)).unwrap_or(false)) {
            let (from, Some(to)) = (st_net(p), net_at.get(&key(b, p["name"].as_str().unwrap_or("")))) else { continue };
            if from.is_empty() || to.is_empty() { continue; }
            match m.get(&from) { Some(t) if t != to => conflicts.push(format!("{from} -> {t} and {to}")), _ => { m.insert(from, to.clone()); } }
        }
    }
    if conflicts.is_empty() { Ok(m) } else { Err(conflicts) }
}

fn glob(pat: &str, s: &str) -> Option<String> {
    // one * matches any run; returns what it matched
    let (pre, post) = pat.split_once('*')?;
    let u = s.to_uppercase();
    if u.starts_with(&pre.to_uppercase()) && u.ends_with(&post.to_uppercase()) && u.len() >= pre.len() + post.len() { Some(s[pre.len()..s.len() - post.len()].to_string()) } else { None }
}

/// altium_copy_routing {box, offset, refMap? | refPattern?, netMap?, keepUnmappedNets?, layers?, validate?, expectedRevision?, dryRun?}
pub fn copy_routing(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let bx: Vec<f64> = args.get("box").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default();
    let off: Vec<f64> = args.get("offset").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default();
    if bx.len() != 4 || off.len() != 2 { return bad("box: [x1, y1, x2, y2] and offset: [dx, dy] mm are required"); }
    let (x0, x1, y0, y1) = (bx[0].min(bx[2]), bx[0].max(bx[2]), bx[1].min(bx[3]), bx[1].max(bx[3]));
    let inside = |x: f64, y: f64| x >= x0 && x <= x1 && y >= y0 && y <= y1;
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let comps: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().map(|c| st_str(&c["ref"])).collect();
    let mut pairs: Vec<(String, String)> = args.get("refMap").and_then(|v| v.as_object()).map(|o| o.iter().map(|(a, b)| (a.clone(), sv(b))).collect()).unwrap_or_default();
    if let Some(p) = args.get("refPattern") {
        let (from, to) = (st_str(&p["from"]), st_str(&p["to"]));
        for c in &comps { if let Some(m) = glob(&from, c) { let t = to.replacen('*', &m, 1); if comps.iter().any(|x| x.eq_ignore_ascii_case(&t)) { pairs.push((c.clone(), t)); } } }
    }
    let mut map = match net_map(st["pads"].as_array().map(|v| v.as_slice()).unwrap_or(&[]), &pairs) {
        Ok(m) => m,
        Err(c) => return json!({"success": false, "errorCode": "net_map_conflict", "error": "a source net maps to two target nets", "conflicts": c, "_hint": "Settle each with netMap {source: target}."}),
    };
    if let Some(o) = args.get("netMap").and_then(|v| v.as_object()) { for (a, b) in o { map.insert(a.clone(), sv(b)); } }
    let keep = args.get("keepUnmappedNets").and_then(|v| v.as_bool()) == Some(true);
    let only: Option<Vec<String>> = args.get("layers").and_then(|v| v.as_array()).map(|a| a.iter().map(sv).collect());
    let (dx, dy) = (off[0], off[1]);
    let mut ops = Vec::new();
    let mut skipped = Vec::new();
    let (mut nt, mut nv) = (0, 0);
    let target = |net: &str| -> Option<String> { if net.is_empty() { return Some(String::new()); } map.get(net).cloned().or(if keep { Some(net.to_string()) } else { None }) };
    for t in st["tracks"].as_array().cloned().unwrap_or_default() {
        let (a, b) = (&t["start"], &t["end"]);
        if !(inside(f(&a["x"]), f(&a["y"])) && inside(f(&b["x"]), f(&b["y"]))) { continue; }
        let layer = st_str(&t["layer"]);
        if let Some(o) = &only { if !o.contains(&layer) { continue; } }
        let Some(lid) = layer_id(&t["layerId"]).or_else(|| layer_id(&t["layer"])) else { continue };
        match target(&st_net(&t)) {
            Some(n) => { ops.push(format!("T|{}|{}|{}|{}|{}|{lid}|{}", raw(f(&a["x"]) + dx), raw(f(&a["y"]) + dy), raw(f(&b["x"]) + dx), raw(f(&b["y"]) + dy), raw(f(&t["width"])), clean(&n))); nt += 1; }
            None => skipped.push(json!({"item": "track", "net": st_net(&t), "why": "net not mapped (pass refMap, netMap or keepUnmappedNets)"})),
        }
    }
    for v in st["vias"].as_array().cloned().unwrap_or_default() {
        let p = &v["position"];
        if !inside(f(&p["x"]), f(&p["y"])) { continue; }
        let ls: Vec<String> = v["layers"].as_array().map(|a| a.iter().map(sv).collect()).unwrap_or_default();
        if ls != ["F.Cu", "B.Cu"] { skipped.push(json!({"item": "via", "at": [f(&p["x"]), f(&p["y"])], "why": "blind or buried: only through vias are copied"})); continue; }
        match target(&st_net(&v)) {
            Some(n) => { ops.push(format!("V|{}|{}|{}|{}|{TOP}|{BOTTOM}|{}", raw(f(&p["x"]) + dx), raw(f(&p["y"]) + dy), raw(f(&v["size"])), raw(f(&v["drill"])), clean(&n))); nv += 1; }
            None => skipped.push(json!({"item": "via", "net": st_net(&v), "why": "net not mapped"})),
        }
    }
    for a in st["arcs"].as_array().cloned().unwrap_or_default() {
        if inside(f(&a["center"]["x"]), f(&a["center"]["y"])) { skipped.push(json!({"item": "arc", "why": "arcs are not copied yet"})); }
    }
    let copied = json!({"tracks": nt, "vias": nv});
    if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no track or via of a mapped net inside the box", "netMap": map, "skipped": skipped}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "copied": copied, "netMap": map, "skipped": skipped, "revision": st["revision"]}); }
    let validate = args.get("validate").and_then(|v| v.as_bool()) != Some(false);
    let errs_before = if validate { routing::routing_drc(&json!({}))["errors"].as_i64() } else { None };
    let mut out = apply(&ops, &st, "copy_routing");
    out.as_object_mut().map(|o| o.remove("state"));
    out["copied"] = copied; out["netMap"] = json!(map); out["skipped"] = json!(skipped);
    if validate {
        let after = routing::routing_drc(&json!({}));
        let new = after["errors"].as_i64().zip(errs_before).map(|(a, b)| a - b);
        out["drc"] = json!({"ran": true, "before": errs_before, "after": after["errors"], "newErrors": new});
        if new.unwrap_or(0) > 0 {
            // take the copy back out: the same tracks and vias, by their exact coordinates
            let undo: Vec<String> = ops.iter().filter_map(|o| { let p: Vec<&str> = o.split('|').collect(); match p[0] {
                "T" => Some(format!("D|T|{}|{}|{}|{}|{}", p[1], p[2], p[3], p[4], p[6])), "V" => Some(format!("D|V|{}|{}", p[1], p[2])), _ => None } }).collect();
            let st2 = routing::routing_state(&json!({}));
            let _ = apply(&undo, &st2, "copy_routing undo");
            out["success"] = json!(false); out["errorCode"] = json!("drc_errors"); out["rolledBack"] = json!(true);
            out["error"] = json!(format!("the copy added {} DRC errors and was taken back out", new.unwrap_or(0)));
            out["revision"] = routing::routing_state(&json!({}))["revision"].clone();
            out["violations"] = after["violations"].clone();
        }
    }
    out["_hint"] = json!("The copy connects where the target parts sit at the same offset (place them first: altium_replicate_layout). Check netMap; altium_routing_drc shows what the copy did.");
    out
}

// -- check_clearance --------------------------------------------------------------------------------------------------------

/// altium_check_clearance {refs?, mode: courtyard|pads, thresholdMm?, includeSameNet?, maxPairs?}: the standard's shared
/// check (vendor/adom-eda-checks `placetools`, #22) on the board model and the parts' 3D bodies. Pads are measured by
/// their real outline (rounded pads as circles or stadiums), parts as their pads plus bodies; Altium courtyards are not read.
pub fn check_clearance(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let st = routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
    let b = crate::bodies::bodies_on(&json!({}), Some(&st));
    let b = if b.get("success").and_then(|v| v.as_bool()) == Some(true) { b } else { Value::Null };
    let mut a = args.clone();
    if let Some(o) = a.as_object_mut() { o.remove("filePath"); }
    crate::checks::engine("check_clearance", &json!({"board": st, "bodies": b, "args": a}))
}

// -- remove_graphics ---------------------------------------------------------------------------------------------------------

/// A board graphic from its agent key (kind:layer:numbers[:text]): id, kind, layer and points in mm. Pure.
pub fn graphic(key: &str) -> Value {
    let mut it = key.splitn(4, ':');
    let (kind, layer, nums, text) = (it.next().unwrap_or(""), it.next().unwrap_or("0").parse::<i64>().unwrap_or(0), it.next().unwrap_or(""), it.next());
    let n: Vec<f64> = nums.split(',').filter_map(|x| x.parse::<f64>().ok()).collect();
    let mm = |v: f64| r3(v / PER_MM);
    let pts: Vec<Value> = match kind {
        "line" | "rect" | "polygon" | "dimension" if n.len() >= 4 => vec![json!([mm(n[0]), mm(n[1])]), json!([mm(n[2]), mm(n[3])])],
        "arc" if n.len() >= 3 => vec![json!([mm(n[0]), mm(n[1])])],
        "text" if n.len() >= 2 => vec![json!([mm(n[0]), mm(n[1])])],
        _ => vec![],
    };
    let mut v = json!({"id": format!("{kind}-{}", &crate::routing::fnv(key)[..10]), "kind": kind, "layer": layer_name(layer), "layerId": layer, "points": pts});
    if kind == "arc" && n.len() >= 5 { v["radius"] = json!(mm(n[2])); v["startAngle"] = json!(n[3] / 1000.0); v["endAngle"] = json!(n[4] / 1000.0); }
    if let Some(t) = text { v["text"] = json!(t); }
    v
}

/// altium_remove_graphics {ids? | layer? + kinds?, expectedRevision?, dryRun?}
pub fn remove_graphics(args: &Value) -> Value {
    if let Some(e) = open_board(args) { return e; }
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let g = match agent_data(&agent::call("board_graphics", &[], None, Duration::from_secs(120))) { Ok(d) => d, Err(e) => return e };
    let all: Vec<(String, Value)> = g["graphics"].as_array().cloned().unwrap_or_default().iter().map(|k| { let k = st_str(k); let v = graphic(&k); (k, v) }).collect();
    let ids = refs_of(args.get("ids"));
    let layer = args.get("layer").and_then(|v| v.as_str()).map(str::to_string);
    let kinds: Option<Vec<String>> = args.get("kinds").and_then(|v| v.as_array()).map(|a| a.iter().map(sv).collect());
    if ids.is_empty() && layer.is_none() && kinds.is_none() {
        return json!({"success": true, "graphics": all.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(), "count": all.len(),
            "_hint": "Listed only: pass ids, or layer and kinds, to remove (dry-run a filter first)."});
    }
    let unknown: Vec<&String> = ids.iter().filter(|i| !all.iter().any(|(_, v)| v["id"] == json!(i))).collect();
    if !unknown.is_empty() { return json!({"success": false, "errorCode": "unknown_ids", "error": format!("no board graphic {unknown:?}"), "_hint": "Call with no filter to list the graphics and their ids."}); }
    let layer_match = |v: &Value| layer.as_ref().map(|l| v["layer"] == json!(l) || layer_id(&json!(l)).map(|id| v["layerId"] == json!(id)).unwrap_or(false)).unwrap_or(true);
    let picked: Vec<&(String, Value)> = all.iter().filter(|(_, v)| if !ids.is_empty() { ids.iter().any(|i| v["id"] == json!(i)) } else { layer_match(v) && kinds.as_ref().map(|k| k.iter().any(|x| v["kind"] == json!(x))).unwrap_or(true) }).collect();
    let removed: Vec<Value> = picked.iter().map(|(_, v)| v.clone()).collect();
    if picked.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no graphic matches"}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "removed": removed, "revision": st["revision"]}); }
    let ops: Vec<String> = picked.iter().map(|(k, _)| format!("G|{}", k.replace('|', " "))).collect();
    let mut out = apply(&ops, &st, "remove_graphics");
    out.as_object_mut().map(|o| o.remove("state"));
    out["removed"] = json!(removed);
    out["_hint"] = json!("Board-level graphics only (not in a part, not on a net). Removing the outline layer's lines removes the board shape.");
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn p(r: &str, x: f64, y: f64, w: f64, h: f64) -> (String, f64, f64, Rect) { (r.into(), x, y, (x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0)) }

    #[test]
    fn align_lines_up_edges_and_spreads_evenly() {
        let parts = vec![p("C1", 10.0, 5.0, 2.0, 1.0), p("C2", 14.0, 7.0, 4.0, 1.0), p("C3", 30.0, 6.0, 2.0, 1.0)];
        let l = align_plan(&parts, "left", None, None, false).unwrap();
        assert_eq!(l, vec![("C1".into(), 10.0, 5.0), ("C2".into(), 11.0, 7.0), ("C3".into(), 10.0, 6.0)]);
        let b = align_plan(&parts, "bottom", None, None, false).unwrap();
        assert!(b.iter().all(|(_, _, y)| (*y - 5.0).abs() < 1e-9));
        let d = align_plan(&parts, "distributeX", None, None, true).unwrap();
        assert_eq!(d.iter().map(|x| x.1).collect::<Vec<_>>(), vec![10.0, 20.0, 30.0]);
    }

    #[test]
    fn nets_map_through_paired_parts_and_conflicts_are_refused() {
        let pad = |r: &str, n: &str, net: &str| json!({"ref": r, "name": n, "net": net});
        let pads = vec![pad("U1", "1", "A1"), pad("U1", "2", "B1"), pad("U2", "1", "A2"), pad("U2", "2", "B2")];
        let m = net_map(&pads, &[("U1".into(), "U2".into())]).unwrap();
        assert_eq!(m.get("A1"), Some(&"A2".to_string()));
        let pads2 = vec![pad("U1", "1", "A1"), pad("U1", "2", "A1"), pad("U2", "1", "A2"), pad("U2", "2", "B2")];
        assert!(net_map(&pads2, &[("U1".into(), "U2".into())]).is_err());
        assert_eq!(glob("CH1_*", "CH1_R5").as_deref(), Some("R5"));
    }

    #[test]
    fn a_graphic_key_reads_as_mm_on_its_layer() {
        let k = format!("line:57:{},{},{},{},{}", raw(1.0), raw(2.0), raw(11.0), raw(2.0), raw(0.15));
        let g = graphic(&k);
        assert_eq!(g["kind"], "line");
        assert_eq!(g["points"], json!([[1.0, 2.0], [11.0, 2.0]]));
        assert_eq!(g["layer"], "L57");
        assert!(g["id"].as_str().unwrap().starts_with("line-"));
    }
}