main
Colby Knox 0.2.79 (unreleased): thermal_vias, via_fence, height_check and placement_check answer through the standard's engine (st… dd71650
//! Board furniture an AI adds to every real board: mounting holes, fiducials, keepouts and stitching vias, plus the
//! standard's via plans (thermal_vias, via_fence). The plans come from the EDA Bridge Standard's shared engine
//! (vendor/adom-eda-checks `features`, standard 0.7.0) on altium_routing_state, so they need no dialog; this bridge
//! places what the engine plans, as one undo step.
use adom_eda_checks::features::{corners, plan_stitching_with, region_of, summary};
use serde_json::{json, Value};

/// The engine's plan for `check` on the current board (guarded) with the board's rules, or the refusal to answer with.
fn plan(check: &str, args: &Value) -> Result<(Value, Value), Value> {
    if let Some(g) = crate::support::need_licensed() { return Err(g); }
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return Err(e); } }
    let st = crate::routing::guarded(args)?;
    // the board's Routing Via rule sizes the vias, so they pass its DRC (0.6/0.3 broke the Bluetooth Sentinel's 0.5/0.3
    // rule on every via)
    let rules = crate::agent::call("read_rules", &[], None, std::time::Duration::from_secs(60));
    let r = crate::checks::engine(check, &json!({"board": st, "rules": rules.get("data").cloned().unwrap_or(json!([])), "args": args}));
    Ok((r, st))
}

/// place_vias ops for an engine plan's `apply` ({verb: "place_vias", args: {vias: [{net, x, y, size, drill}]}}). Pure.
pub fn via_ops(apply: &Value) -> Vec<String> {
    use crate::routing::{raw, BOTTOM, TOP};
    apply["args"]["vias"].as_array().cloned().unwrap_or_default().iter()
        .map(|v| format!("V|{}|{}|{}|{}|{}|{}|{}", raw(f(&v["x"])), raw(f(&v["y"])), raw(f(&v["size"])), raw(f(&v["drill"])), TOP, BOTTOM, v["net"].as_str().unwrap_or(""))).collect()
}

/// Place the engine's plan (or return it for dryRun or a refusal), keeping the plan, the engine and its hint in the reply.
fn place(check: &str, args: &Value, hint: &str) -> Value {
    let (r, st) = match plan(check, args) { Ok(x) => x, Err(e) => return e };
    if r["success"] != json!(true) || r.get("apply").is_none() { return r; }
    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {
        return json!({"success": true, "dryRun": true, "planned": r["planned"], "engine": r["engine"], "_hint": "Nothing placed. Call again without dryRun to place exactly this."});
    }
    let a = crate::routing::apply(&via_ops(&r["apply"]), &st, check);
    json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "planned": r["planned"], "revision": a["revision"], "engine": r["engine"], "_hint": hint})
}

/// altium_thermal_vias {filePath?, ref, pad?, pitchMm?, size?, drill?, insetMm?, dryRun?}
pub fn thermal_vias(args: &Value) -> Value {
    place("thermal_vias", args, "Vias inside the pad carry its heat to the other layers' copper: pour the net on the far side (altium_apply_pours) so they have somewhere to go. Open vias in a pad wick solder: ask the fab to tent or plug them (JLCPCB: via covering), or use 0.3 mm or smaller drills. altium_routing_drc afterwards.")
}

/// altium_via_fence {filePath?, nets?, edge?, viaNet, pitchMm?, freqGHz?, offsetMm?, edgeInsetMm?, size?, drill?, clearance?, dryRun?}
pub fn via_fence(args: &Value) -> Value {
    place("via_fence", args, "Fence vias placed as one undo step, each clear of other copper by clearance and of the board edge, sized by the board's Routing Via rule. Repour (altium_repour) so pours join them, then altium_routing_drc {full:true} (the quick read can show stale test-point messages after a repour). candidates - vias are the spots where other copper, a pad or the edge was too close.")
}

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }

fn num(v: &Value, k: &str, d: f64) -> f64 { v.get(k).and_then(|x| x.as_f64().or_else(|| x.as_str().and_then(|s| s.parse().ok()))).unwrap_or(d) }

/// altium_board_features {mountingHoles?, fiducials?, stitching?, dryRun?, expectPath?, expectedRevision?}
pub fn board_features(args: &Value) -> Value {
    use crate::routing::{apply, guarded, raw, BOTTOM, TOP};
    if let Some(g) = crate::support::need_licensed() { return g; }
    // the board named (filePath, or the expectPath guard) is opened first: after schematic work the current document is
    // a sheet and the verb answered no_current_board (battery, 2026-10-23)
    if let Some(p) = crate::support::s(args, "filePath").or_else(|| crate::support::s(args, "expectPath")) {
        if let Some(e) = crate::support::must_open(&p, 60) { return e; }
    }
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let mut ops: Vec<String> = Vec::new();
    let mut planned = serde_json::Map::new();
    // P|x|y|padSize|hole|plated|layer|net|name|maskExpansion  (raw units; layer 74 = multi-layer)
    const MULTI: i64 = 74;
    // mounting holes: a list of {x, y}, or {corners: {inset}} for the four corners of the outline
    let holes = args.get("mountingHoles");
    let (hole_pts, hole_spec): (Vec<(f64, f64)>, Value) = match holes {
        Some(Value::Array(a)) => (a.iter().map(|h| (num(h, "x", 0.0), num(h, "y", 0.0))).collect(), a.first().cloned().unwrap_or(json!({}))),
        Some(o @ Value::Object(_)) => {
            let inset = o.get("corners").map(|c| if c.is_object() { num(c, "inset", 4.0) } else { num(o, "inset", 4.0) }).unwrap_or(4.0);
            (corners(&st, inset), o.clone())
        }
        _ => (vec![], json!({})),
    };
    let mut hole_list = Vec::new();
    for (i, (x, y)) in hole_pts.iter().enumerate() {
        let h = match holes { Some(Value::Array(a)) => a[i].clone(), _ => hole_spec.clone() };
        let drill = num(&h, "drill", 3.2);
        let plated = h.get("plated").and_then(|b| b.as_bool()).unwrap_or(false);
        // unplated: the copper is the hole itself (no ring); plated: a ring, M3 default 6 mm
        let pad = if plated { num(&h, "pad", drill + 2.8) } else { drill };
        let net = h.get("net").and_then(|n| n.as_str()).unwrap_or("");
        if plated && !net.is_empty() && !st["nets"].as_array().map(|a| a.iter().any(|n| n.as_str().map(|s| s.eq_ignore_ascii_case(net)).unwrap_or(false))).unwrap_or(false) {
            return json!({"success": false, "errorCode": "no_such_net", "error": format!("{net} is not a net on this board"), "nets": st["nets"]});
        }
        ops.push(format!("P|{}|{}|{}|{}|{}|{}|{}|MH{}|", raw(*x), raw(*y), raw(pad), raw(drill), if plated { 1 } else { 0 }, MULTI, net, i + 1));
        hole_list.push(json!({"x": x, "y": y, "drill": drill, "pad": pad, "plated": plated, "net": net}));
    }
    if !hole_list.is_empty() { planned.insert("mountingHoles".into(), json!(hole_list.clone())); }
    // fiducials: bare copper dots with a wider mask opening
    let mut fid_list = Vec::new();
    for (i, fd) in args.get("fiducials").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().enumerate() {
        let (x, y) = (num(fd, "x", 0.0), num(fd, "y", 0.0));
        let size = num(fd, "size", 1.0);
        let opening = num(fd, "opening", size * 2.0);
        let layer = if fd.get("side").and_then(|s| s.as_str()) == Some("bottom") { BOTTOM } else { TOP };
        ops.push(format!("P|{}|{}|{}|0|0|{}||FID{}|{}", raw(x), raw(y), raw(size), layer, i + 1, raw((opening - size) / 2.0)));
        fid_list.push(json!({"x": x, "y": y, "size": size, "opening": opening, "side": if layer == BOTTOM { "bottom" } else { "top" }}));
    }
    if !fid_list.is_empty() { planned.insert("fiducials".into(), json!(fid_list.clone())); }
    // keepouts: rectangles where nothing goes, on every layer (Keep-Out layer) or one copper layer
    let mut ko_list = Vec::new();
    let mut ko_rects: Vec<(f64, f64, f64, f64)> = Vec::new();
    for k in args.get("keepouts").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let Some(r) = k.get("rect").and_then(|r| r.as_array()).filter(|a| a.len() == 4) else {
            return json!({"success": false, "errorCode": "bad_args", "error": "each keepout needs rect: [x1, y1, x2, y2] (mm)"});
        };
        let v: Vec<f64> = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();
        let (x1, y1, x2, y2) = (v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3]));
        let layer_name = k.get("layer").and_then(|l| l.as_str()).unwrap_or("all").to_string();
        let layer = if layer_name.eq_ignore_ascii_case("all") { 0 } else { match crate::routing::layer_id(&json!(layer_name)) { Some(l) => l, None => return json!({"success": false, "errorCode": "bad_args", "error": format!("keepout layer {layer_name} is not all, F.Cu, B.Cu or In<n>.Cu")}) } };
        ops.push(format!("K|{}|{}|{}|{}|{}", raw(x1), raw(y1), raw(x2), raw(y2), layer));
        ko_rects.push((x1, y1, x2, y2));
        ko_list.push(json!({"rect": [x1, y1, x2, y2], "layer": layer_name}));
    }
    if !ko_list.is_empty() { planned.insert("keepouts".into(), json!(ko_list)); }
    // stitching: a via grid on one net, clear of everything else
    if let Some(sv) = args.get("stitching") {
        let Some(net) = sv.get("net").and_then(|n| n.as_str()) else {
            return json!({"success": false, "errorCode": "bad_args", "error": "stitching needs net (e.g. GND)"});
        };
        if !st["nets"].as_array().map(|a| a.iter().any(|n| n.as_str().map(|s| s.eq_ignore_ascii_case(net)).unwrap_or(false))).unwrap_or(false) {
            return json!({"success": false, "errorCode": "no_such_net", "error": format!("{net} is not a net on this board"), "nets": st["nets"],
                "_hint": "Stitching ties copper of a net that already has pads on the board (its pours connect through the vias)."});
        }
        let (pitch, size, drill) = (num(sv, "pitch", 5.0), num(sv, "size", 0.6), num(sv, "drill", 0.3));
        let (clearance, edge, max) = (num(sv, "clearance", 0.3), num(sv, "edge", 1.0), num(sv, "max", 400.0) as usize);
        let region = region_of(sv.get("region"));
        // the holes and fiducials of this same call (a fiducial's whole mask opening stays bare)
        let mut extra: Vec<(f64, f64, f64)> = hole_list.iter().map(|h| (num(h, "x", 0.0), num(h, "y", 0.0), num(h, "pad", 3.2) / 2.0)).collect();
        extra.extend(fid_list.iter().map(|fd| (num(fd, "x", 0.0), num(fd, "y", 0.0), num(fd, "opening", 2.0) / 2.0)));
        let avoid_parts = sv.get("underParts").and_then(|b| b.as_bool()) != Some(true);
        let pts = plan_stitching_with(&st, net, pitch, size, clearance, edge, region.as_deref(), max, &extra, avoid_parts, &ko_rects);
        for (x, y) in &pts { ops.push(format!("V|{}|{}|{}|{}|{}|{}|{}", raw(*x), raw(*y), raw(size), raw(drill), TOP, BOTTOM, net)); }
        planned.insert("stitching".into(), json!({"net": net, "pitch": pitch, "size": size, "drill": drill, "clearance": clearance, "edge": edge, "count": pts.len(), "points": summary(&pts)}));
    }
    if ops.is_empty() {
        return json!({"success": false, "errorCode": "nothing_to_do", "error": "pass mountingHoles, fiducials, keepouts and/or stitching",
            "_hint": "mountingHoles: [{x,y,drill?,plated?,pad?,net?}] or {corners:{inset:4}, drill:3.2}; fiducials: [{x,y,size?:1,opening?:2,side?}]; stitching: {net, pitch?:5, size?:0.6, drill?:0.3, clearance?:0.3, edge?:1, region?:[[x,y]..], max?:400}"});
    }
    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {
        return json!({"success": true, "dryRun": true, "planned": planned, "_hint": "Nothing placed. Call again without dryRun to place exactly this."});
    }
    let mut r = apply(&ops, &st, "board_features");
    if let Some(maxd) = hole_list.iter().map(|h| num(h, "drill", 0.0)).reduce(f64::max) {
        // a fab's hole-size rule usually stops below a mounting hole (the battery board's flagged 3.2 mm, 2026-10-23)
        r["holeRule"] = json!(format!("Mounting holes are {maxd} mm. If altium_run_drc reports HoleSize on them, widen the rule: altium_set_design_rules {{hole: {{min: <your fab's min>, max: {maxd}}}}}."));
    }
    r["planned"] = json!(planned);
    if r.get("success").and_then(|b| b.as_bool()) == Some(true) {
        r["_hint"] = json!("Placed as one undo step. Pours on the stitched net connect through the vias after altium_repour; run altium_run_drc to confirm clearances.");
    }
    r
}

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

    #[test]
    fn engine_plans_become_one_via_op_each() {
        // the standard's thermal_vias plan for a 3.3 mm pad, as the engine answers it, placed through place_vias' op
        let board = json!({"outline": [[0, 0], [20, 0], [20, 20], [0, 20]], "tracks": [], "arcs": [], "vias": [], "nets": ["GND"],
                           "pads": [{"ref": "U1", "name": "EP", "x": 10.0, "y": 10.0, "sizeX": 3.3, "sizeY": 3.3, "rotation": 0.0, "net": "GND"}]});
        let rules = json!([{"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (PreferredHoleWidth=0.3mm) (PreferedWidth=0.5mm) (All)"}]);
        let r = adom_eda_checks::run("thermal_vias", &json!({"board": board, "rules": rules, "args": {"ref": "U1"}}));
        assert_eq!(r["planned"]["via"]["sizeMm"], json!(0.5));
        let ops = via_ops(&r["apply"]);
        assert_eq!(ops.len(), r["planned"]["vias"].as_u64().unwrap() as usize);
        assert!(ops.iter().all(|o| o.starts_with("V|") && o.ends_with("|GND")), "{ops:?}");
        assert!(ops.contains(&format!("V|{}|{}|{}|{}|{}|{}|GND", crate::routing::raw(10.0), crate::routing::raw(10.0), crate::routing::raw(0.5), crate::routing::raw(0.3), crate::routing::TOP, crate::routing::BOTTOM)));
    }
}