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
//! The checks the EDA Bridge Standard's shared engine answers (vendor/adom-eda-checks): copper balance, return paths,
//! fab limits, impedance and current capacity. This bridge gathers the board model and its companions from Altium,
//! the engine computes, and the reply names Altium's own verbs. Fab limits come from adom/pcb-design-rules' records,
//! bundled in vendor/pcb-design-rules, never from a table of our own.
use serde_json::{json, Value};
use std::time::Duration;

/// adom/pcb-design-rules' vendor records, bundled at build time (vendor/README.md).
const RECORDS: &[(&str, &str)] = &[
    ("adom-3rdpartyfab", include_str!("../vendor/pcb-design-rules/records/adom-3rdpartyfab.json")),
    ("advanced-circuits-4pcb", include_str!("../vendor/pcb-design-rules/records/advanced-circuits-4pcb.json")),
    ("aisler", include_str!("../vendor/pcb-design-rules/records/aisler.json")),
    ("allpcb", include_str!("../vendor/pcb-design-rules/records/allpcb.json")),
    ("elecrow", include_str!("../vendor/pcb-design-rules/records/elecrow.json")),
    ("eurocircuits", include_str!("../vendor/pcb-design-rules/records/eurocircuits.json")),
    ("jlcpcb", include_str!("../vendor/pcb-design-rules/records/jlcpcb.json")),
    ("macrofab", include_str!("../vendor/pcb-design-rules/records/macrofab.json")),
    ("nextpcb", include_str!("../vendor/pcb-design-rules/records/nextpcb.json")),
    ("osh-park", include_str!("../vendor/pcb-design-rules/records/osh-park.json")),
    ("pcbway", include_str!("../vendor/pcb-design-rules/records/pcbway.json")),
    ("seeed-fusion", include_str!("../vendor/pcb-design-rules/records/seeed-fusion.json")),
    ("sierra-circuits", include_str!("../vendor/pcb-design-rules/records/sierra-circuits.json")),
];

/// One fab's record for a board: the vendor (slug or name, "jlc" for JLCPCB), the process (standard unless named) and
/// the record whose layer count is the board's (else the nearest above it). Pure.
pub fn fab_record(vendor: &str, layers: Option<i64>, process: Option<&str>) -> Result<Value, String> {
    let want = vendor.to_lowercase().replace([' ', '_'], "-");
    let want = if want == "jlc" { "jlcpcb".to_string() } else { want };
    let Some((slug, text)) = RECORDS.iter().find(|(s, t)| *s == want || serde_json::from_str::<Value>(t).ok().and_then(|v| v["vendor"].as_str().map(|n| n.to_lowercase() == vendor.to_lowercase())).unwrap_or(false)) else {
        return Err(format!("no record for {vendor}: the bundled vendors are {}", RECORDS.iter().map(|r| r.0).collect::<Vec<_>>().join(", ")));
    };
    let file: Value = serde_json::from_str(text).map_err(|e| format!("{slug}: {e}"))?;
    let recs = file["records"].as_array().cloned().unwrap_or_default();
    let proc_ok = |r: &Value| process.map(|p| r["process"].as_str().map(|x| x.eq_ignore_ascii_case(p)).unwrap_or(false)).unwrap_or(r["process"].as_str().map(|x| x == "standard").unwrap_or(true));
    let mut cands: Vec<&Value> = recs.iter().filter(|r| proc_ok(r)).collect();
    if cands.is_empty() { cands = recs.iter().collect(); }
    let n = layers.unwrap_or(2);
    let pick = cands.iter().filter(|r| r["layerCount"].as_i64() == Some(n)).next()
        .or_else(|| cands.iter().filter(|r| r["layerCount"].as_i64().map(|c| c >= n).unwrap_or(false)).min_by_key(|r| r["layerCount"].as_i64().unwrap_or(99)))
        .or_else(|| cands.first()).ok_or_else(|| format!("{slug} has no records"))?;
    let mut rec = (*pick).clone();
    rec["vendor"] = file["vendor"].clone();
    Ok(rec)
}

/// Prefix the standard verbs a reply names (apply_pours, add_rule ...) with altium_, so the next step is callable as
/// written. Only words with an underscore that this bridge serves are touched. Pure.
pub fn prefix_verbs(v: &mut Value) {
    match v {
        Value::String(s) => *s = prefix_text(s),
        Value::Array(a) => a.iter_mut().for_each(prefix_verbs),
        Value::Object(o) => o.values_mut().for_each(prefix_verbs),
        _ => {}
    }
}

fn prefix_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 16);
    let mut word = String::new();
    let flush = |w: &mut String, out: &mut String, prev: Option<char>| {
        if w.contains('_') && crate::verbs::KNOWN.contains(&w.as_str()) && !matches!(prev, Some(c) if c.is_alphanumeric() || c == '_') { out.push_str("altium_"); }
        out.push_str(w);
        w.clear();
    };
    let mut prev_of_word: Option<char> = None;
    let mut last: Option<char> = None;
    for c in s.chars() {
        if c.is_ascii_alphanumeric() || c == '_' {
            if word.is_empty() { prev_of_word = last; }
            word.push(c);
        } else {
            if !word.is_empty() { flush(&mut word, &mut out, prev_of_word); }
            out.push(c);
        }
        last = Some(c);
    }
    if !word.is_empty() { flush(&mut word, &mut out, prev_of_word); }
    out
}

/// The engine's answer, its verbs prefixed. The reply names the engine version itself (`engine`, from 0.3.0).
pub fn engine(check: &str, input: &Value) -> Value {
    let mut r = adom_eda_checks::run(check, input);
    prefix_verbs(&mut r);
    r
}

fn open(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))
}

fn board() -> Result<Value, Value> {
    let st = crate::routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return Err(st); }
    Ok(st)
}

fn stack() -> Value {
    let mut d = crate::agent::call("layer_stack", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);
    crate::routing::name_stack(&mut d);
    d
}

fn without(args: &Value, keys: &[&str]) -> Value {
    let mut a = args.clone();
    if let Some(o) = a.as_object_mut() { for k in keys { o.remove(*k); } }
    a
}

/// altium_plan_route {net, from, to, widthMm?, layers?, allowVias?, viaSizeMm?, viaDrillMm?, gridMm?, viaCost?, clearanceMm?,
/// edgeClearanceMm?, maxNodes?, apply?, filePath?}: the engine plans a path between two pads, clear of other nets' copper by the
/// board's clearance rule (#21); apply:true routes it here with route_net, guarded by the revision it was planned on.
pub fn plan_route(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);
    let mut r = engine("plan_route", &json!({"board": st, "stack": stack(), "rules": rules, "args": without(args, &["filePath", "apply"])}));
    if args.get("apply").and_then(|b| b.as_bool()) != Some(true) || r["found"] != json!(true) { return r; }
    let mut rn = r["routeNet"].clone();
    rn["expectedRevision"] = r["revision"].clone();
    let a = crate::routing::route_net(&rn);
    r["applied"] = json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "results": a["results"], "unconnected": a["unconnected"], "errorCode": a["errorCode"], "error": a["error"]});
    r["revision"] = a["revision"].clone();
    if a["success"] != json!(true) { r["success"] = json!(false); r["errorCode"] = a["errorCode"].clone(); }
    r["_hint"] = json!("Routed as one undo step (Ctrl+Z in Altium takes it back; altium_ripup_nets clears the net). Pours were not obstacles: repour (altium_repour), then altium_routing_drc.");
    r
}

/// altium_place_decoupling {ic, caps?, gapMm?, apply?, filePath?}: the engine places each of an IC's decoupling caps beside the
/// power pin it serves, power pad facing the pin, and checks the moved board with placement_check (#22); apply:true moves
/// them here with move_parts, guarded by the revision it was planned on.
pub fn place_decoupling(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    // the parts' 3D bodies make the boxes honest (a tall cap overhangs its pads); without them the engine uses pads
    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 r = engine("place_decoupling", &json!({"board": st, "bodies": b, "args": without(args, &["filePath", "apply"])}));
    if args.get("apply").and_then(|b| b.as_bool()) != Some(true) || r["success"] != json!(true) { return r; }
    if r["moveArgs"]["parts"].as_array().map(|a| a.is_empty()).unwrap_or(true) { return r; }
    let a = crate::routing::move_parts(&r["moveArgs"]);
    r["applied"] = json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "mismatches": a["mismatches"], "errorCode": a["errorCode"], "error": a["error"]});
    r["revision"] = a["revision"].clone();
    if a["success"] != json!(true) { r["success"] = json!(false); r["errorCode"] = a["errorCode"].clone(); }
    r["_hint"] = json!("Moved as one undo step (Ctrl+Z in Altium takes it back; altium_move_parts with each placement's `from` puts the caps back). The tracks to the caps' old spots stayed: rip them up and route again (altium_ripup_nets, altium_plan_route), then altium_repour and altium_routing_drc.");
    r
}

/// altium_plan_fanout {ref, style?, escapeLayer?, viaMm?, viaDrillMm?, widthMm?, clearanceMm?, pitchMm?, stubMm?,
/// surfaceOuterRing?, viaPerimeter?, apply?, filePath?}: the engine plans a BGA's or a QFN/QFP's escape (#22): stubs, dogbone
/// vias, an exposed pad's via grid, as route_net calls, each via and stub measured against other nets' pads. apply:true
/// routes the calls here, one after another, each guarded by the revision the one before left; never over a conflict.
pub fn plan_fanout(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);
    let mut r = engine("plan_fanout", &json!({"board": st, "stack": stack(), "rules": rules, "args": without(args, &["filePath", "apply"])}));
    if args.get("apply").and_then(|b| b.as_bool()) != Some(true) || r["success"] != json!(true) { return r; }
    if r["conflicts"].as_array().map(|c| !c.is_empty()).unwrap_or(false) {
        r["success"] = json!(false);
        r["errorCode"] = json!("fanout_conflicts");
        r["error"] = json!("the plan has vias or stubs too close to another net's pad: nothing was routed");
        r["_hint"] = json!("Read conflicts: change viaMm, pitchMm, stubMm or style and plan again, or route the clean calls yourself with altium_route_net.");
        return r;
    }
    // every call's tracks and vias from the board read once, applied as one undo step, guarded by the planned revision
    let cur = match crate::routing::guarded(&json!({"expectedRevision": r["revision"]})) { Ok(s) => s, Err(e) => return e };
    let mut ops = Vec::new();
    for call in r["calls"].as_array().cloned().unwrap_or_default() {
        match crate::routing::route_ops(&cur, &call) {
            Ok(o) => ops.extend(o),
            Err(e) => { r["success"] = json!(false); r["errorCode"] = json!("fanout_call_refused"); r["error"] = json!(format!("{}: {}", call["net"].as_str().unwrap_or(""), e["error"].as_str().unwrap_or(""))); return r; }
        }
    }
    let a = crate::routing::apply(&ops, &cur, "plan_fanout");
    r["applied"] = json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "calls": r["callCount"], "errorCode": a["errorCode"], "error": a["error"]});
    r["revision"] = a["revision"].clone();
    if a["success"] != json!(true) { r["success"] = json!(false); r["errorCode"] = a["errorCode"].clone(); }
    r["_hint"] = json!("Routed as one undo step (Ctrl+Z in Altium takes it back; altium_ripup_nets clears the nets). Tracks and pours were not checked: altium_repour, then altium_routing_drc.");
    r
}

/// altium_estimate_cost {quantities?, assembly?, basicParts?, prices?, filePath?}: the numbers a fab quote needs, from the
/// board (#22), priced only from a price record the caller passes (`prices`, read from the fab's page with its date):
/// the engine has no rates, and none is made up here.
pub fn estimate_cost(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);
    engine("estimate_cost", &json!({"board": st, "stack": stack(), "rules": rules, "prices": args.get("prices").cloned().unwrap_or(Value::Null), "args": without(args, &["filePath", "prices"])}))
}

/// altium_copper_balance {filePath?, resolutionMm?}
pub fn copper_balance(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    let pours = crate::routing::pour_state(&json!({}));
    engine("copper_balance", &json!({"board": st, "stack": stack(), "pours": pours, "args": without(args, &["filePath"])}))
}

/// altium_return_path {filePath?, nets?, referenceNets?, resolutionMm?, fixMarginMm?}
pub fn return_path(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    let pours = crate::routing::pour_state(&json!({}));
    engine("return_path", &json!({"board": st, "stack": stack(), "pours": pours, "args": without(args, &["filePath"])}))
}

/// altium_current_capacity {nets: {net: amps}, riseC?, platingUm?, filePath?}
pub fn current_capacity(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    engine("current_capacity", &json!({"board": st, "stack": stack(), "args": without(args, &["filePath"])}))
}

/// altium_impedance {z0?, diff?, gapMm?, layers?, apply?: {scope, name?}, filePath?}: the engine plans; apply writes the
/// planned rules here (one width or diffpair rule per layer, scoped OnLayer by Altium's own layer name).
pub fn impedance(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = stack();
    if st.is_null() { return json!({"success": false, "errorCode": "no_stack", "error": "the layer stack could not be read (open a board first)"}); }
    let mut r = engine("impedance", &json!({"stack": st, "args": without(args, &["filePath"])}));
    if r.get("success").and_then(|b| b.as_bool()) != Some(true) { return r; }
    if let Some(scope) = args.get("apply").and_then(|a| a.get("scope")).and_then(|v| v.as_str()) {
        let mut applied = Vec::new();
        for rule in r["apply"]["rules"].as_array().cloned().unwrap_or_default() {
            let tool_layer = rule["toolLayer"].as_str().unwrap_or("");
            let mut a = rule.clone();
            if let Some(o) = a.as_object_mut() { for k in ["scope", "layer", "toolLayer"] { o.remove(k); } }
            a["scope1"] = json!(format!("({scope}) And OnLayer('{tool_layer}')"));
            let res = crate::routing::add_rule(&a);
            applied.push(json!({"layer": rule["layer"], "rule": rule["name"], "success": res.get("success").cloned().unwrap_or(json!(false)), "error": res.get("error").cloned().unwrap_or(Value::Null)}));
        }
        r["applied"] = json!(applied);
        r["_hint"] = json!("Widths are for uncoated copper: solder mask lowers an outer layer's impedance by about 1 to 3 ohm. Inner layers assume planes on both neighbours. apply wrote one width or diffpair rule per layer (OnLayer) at +/-10%: applied says which landed.");
    }
    r
}

/// altium_fab_check {fab?: vendor or record, process?, limits?, copperOz?, filePath?}
pub fn fab_check(args: &Value) -> Value {
    if let Some(e) = open(args) { return e; }
    let st = match board() { Ok(s) => s, Err(e) => return e };
    let stk = stack();
    let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);
    let layers = stk["copperLayers"].as_i64();
    let fab = match args.get("fab") {
        Some(Value::String(v)) => match fab_record(v, layers, args.get("process").and_then(|p| p.as_str())) {
            Ok(r) => r,
            Err(e) => return json!({"success": false, "errorCode": "unknown_fab", "error": e, "_hint": "Pass a vendor adom/pcb-design-rules covers (fab:\"jlcpcb\"), a record from it, or any fab's numbers as limits."}),
        },
        Some(v) => v.clone(),
        None => Value::Null,
    };
    let wants_silk = args.get("limits").map(|l| l.get("minSilkText").is_some() || l.get("minSilkLine").is_some()).unwrap_or(false) || !fab.is_null();
    let silk = if wants_silk { crate::routing::silk_state(&json!({})) } else { Value::Null };
    engine("fab_check", &json!({"board": st, "stack": stk, "rules": rules, "silk": silk, "fab": fab, "args": without(args, &["filePath", "fab", "process"])}))
}

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

    #[test]
    fn a_vendor_names_its_record_for_the_layer_count() {
        let r = fab_record("jlcpcb", Some(2), None).unwrap();
        assert_eq!(r["layerCount"], 2);
        assert_eq!(r["process"], "standard");
        assert!(r["vendor"].as_str().unwrap().to_lowercase().contains("jlc"));
        assert_eq!(fab_record("JLC", Some(4), None).unwrap()["layerCount"], 4);
        assert!(fab_record("nobody", Some(2), None).is_err());
        for (s, _) in RECORDS { assert!(fab_record(s, Some(2), None).is_ok(), "{s}"); }
    }

    #[test]
    fn standard_verbs_in_a_reply_get_the_prefix() {
        let mut v = json!({"verb": "apply_pours", "note": "Run add_rule once, then altium_run_drc and run_drc; leave apply_poursX and my_apply_pours alone", "n": 3});
        prefix_verbs(&mut v);
        assert_eq!(v["verb"], "altium_apply_pours");
        assert_eq!(v["note"], "Run altium_add_rule once, then altium_run_drc and altium_run_drc; leave apply_poursX and my_apply_pours alone");
    }

    #[test]
    fn the_engine_answers_on_the_lane_fixture() {
        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../fixtures/altium/");
        let read = |n: &str| -> Value { serde_json::from_str(&std::fs::read_to_string(format!("{dir}{n}")).unwrap()).unwrap() };
        let input = json!({"board": read("lane.routing_state.json"), "stack": read("lane.layer_stack.json"), "pours": read("lane.pour_state.json"), "args": {}});
        let got = engine("copper_balance", &input);
        let want = read("expected/lane.copper_balance.json");
        assert_eq!(got["layers"], want["layers"]);
        assert_eq!(got["balanced"], want["balanced"]);
        let rp = engine("return_path", &input);
        assert_eq!(rp["nets"], read("expected/lane.return_path.json")["nets"]);
    }
}