main
Colby Knox altium-bridge 0.2.90: eleven new verbs, license never answers success for a press that didn't happen, update_pcb opens… dd28f04
//! sch_batch: a list of the standard's schematic edits on one sheet, all or nothing (EDA Bridge Standard #29). Altium
//! edits the open sheet live, not a file, so "nothing" is built from its undo: the ops run in order, each one seeing the
//! sheet as the earlier ones left it; when one fails, Altium's Undo runs once for every op already applied and the
//! sheet's fingerprint (its parts and wiring) must match the one taken before the batch. If it does not, the batch
//! answers partial with the ops that ran, as the standard allows for a tool that cannot take a batch back.
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::time::Duration;

/// The schematic verbs a batch may run: they each edit one sheet, named by `sheet`, and leave it unsaved.
pub const OPS: &[&str] = &["sch_place_part", "sch_connect_pins", "sch_connect", "sch_edit", "sch_edit_label", "sch_junction", "sch_no_connect", "sch_label", "sch_wire", "sch_bus",
    "sch_bus_entry", "sch_connect_to_bus", "sch_text", "sch_delete_wire", "sch_split_wire", "sch_move_region", "sch_reset_fields",
    "sch_update_from_library", "sch_swap_part", "sch_fix_connectivity", "annotate"];

/// Each op's verb and its arguments, with the batch's sheet (and project, for annotate) filled in. Pure.
pub fn plan(ops: &[Value], sheet: &str, project: Option<&str>) -> Result<Vec<(String, Value)>, (usize, String)> {
    let mut out = Vec::new();
    for (i, o) in ops.iter().enumerate() {
        let Some(name) = o["op"].as_str() else { return Err((i, "every op needs op: the name of a schematic verb".into())) };
        let name = name.strip_prefix("altium_").unwrap_or(name);
        if !OPS.contains(&name) { return Err((i, format!("{name} is not a schematic edit a batch runs (one of {})", OPS.join(", ")))); }
        let mut a = o.clone();
        if let Some(m) = a.as_object_mut() {
            m.remove("op");
            if name == "annotate" {
                match project { Some(p) => { m.entry("projectPath").or_insert(json!(p)); } None => return Err((i, "annotate needs the sheet's project: none beside the sheet lists it".into())) }
            } else {
                // an op names the batch's sheet or none; another sheet would escape the rollback
                if let Some(s) = m.get("sheet").and_then(|v| v.as_str()) {
                    if crate::agent::win_path(s).to_lowercase() != crate::agent::win_path(sheet).to_lowercase() { return Err((i, format!("op {i} names another sheet ({s}): a batch edits one sheet"))); }
                }
                m.insert("sheet".into(), json!(sheet));
            }
            m.insert("save".into(), json!(false));
        }
        out.push((name.to_string(), a));
    }
    Ok(out)
}

/// The sheet's fingerprint, by what it holds: its parts (designator, symbol, place, turn, parameters) and each kind of
/// wiring item, ids included. None when the sheet could not be read.
fn fingerprint(sheet: &str) -> Option<BTreeMap<String, String>> {
    let parts = crate::verbs::dispatch("schematic_data", &json!({"filePath": sheet}), &[]);
    let items = crate::verbs::dispatch("sch_items", &json!({"sheet": sheet}), &[]);
    if items.get("success").and_then(|b| b.as_bool()) == Some(false) || parts.get("success").and_then(|b| b.as_bool()) == Some(false) { return None; }
    let comps: Vec<Value> = parts.get("data").and_then(|d| d["components"].as_array()).or(parts["components"].as_array()).cloned().unwrap_or_default().iter()
        .map(|c| json!([c["designator"], c["libReference"], c["xMil"], c["yMil"], c["orientation"], c["params"]])).collect();
    let mut out = BTreeMap::new();
    out.insert("parts".to_string(), crate::routing::fnv(&json!(comps).to_string()));
    // as sets: Undo can put a sheet's items back in another order, which changes nothing on the sheet. Wires and buses
    // by the path they take: Undo can also leave an extra vertex on a straight run (measured 2026-11-03), which changes
    // the wire's id and nothing else.
    for k in ["wires", "buses"] {
        let paths: Vec<Value> = items[k].as_array().cloned().unwrap_or_default().iter().map(wire_path).collect();
        out.insert(k.to_string(), crate::routing::fnv(&as_set(&json!(paths))));
    }
    for k in ["busEntries", "labels", "powerPorts", "junctions", "noConnects", "texts", "sheets"] { out.insert(k.to_string(), crate::routing::fnv(&as_set(&items[k]))); }
    Some(out)
}

/// The path a wire takes: its corners only, the same whichever end it was drawn from. Pure.
pub fn wire_path(w: &Value) -> Value {
    let pts: Vec<(f64, f64)> = w["points"].as_array().cloned().unwrap_or_default().iter().filter_map(|p| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?))).collect();
    let mut out: Vec<(f64, f64)> = Vec::new();
    for p in pts {
        if out.last() == Some(&p) { continue; }
        // a vertex between two legs on one straight line is no corner
        if out.len() >= 2 {
            let (a, b) = (out[out.len() - 2], out[out.len() - 1]);
            let cross = (b.0 - a.0) * (p.1 - b.1) - (b.1 - a.1) * (p.0 - b.0);
            let onward = (b.0 - a.0) * (p.0 - b.0) + (b.1 - a.1) * (p.1 - b.1);
            if cross.abs() < 1e-6 && onward > 0.0 { out.pop(); }
        }
        out.push(p);
    }
    let back: Vec<(f64, f64)> = out.iter().rev().cloned().collect();
    let key = |v: &[(f64, f64)]| v.iter().map(|p| format!("{:.4},{:.4}", p.0, p.1)).collect::<Vec<_>>().join(" ");
    json!(key(&out).min(key(&back)))
}

/// A list's rows in an order of their own, so two lists holding the same rows read the same. Pure.
pub fn as_set(list: &Value) -> String {
    let mut rows: Vec<String> = list.as_array().map(|a| a.iter().map(|x| x.to_string()).collect()).unwrap_or_default();
    rows.sort();
    rows.join("\n")
}

/// What differs between two fingerprints. Pure.
pub fn differs(a: &BTreeMap<String, String>, b: &BTreeMap<String, String>) -> Vec<String> { a.iter().filter(|(k, v)| b.get(*k) != Some(*v)).map(|(k, _)| k.clone()).collect() }

/// Compile the project and count the Messages for this sheet by class.
fn erc_counts(project: &str, sheet: &str) -> Value {
    let r = crate::outputs::compile(&json!({"projectPath": project, "limit": 2000}));
    let name = std::path::Path::new(&sheet.replace('\\', "/")).file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
    let mut by = serde_json::Map::new();
    for m in r["messages"].as_array().cloned().unwrap_or_default() {
        if !m["document"].as_str().unwrap_or("").to_lowercase().ends_with(&name) { continue; }
        let k = m["class"].as_str().unwrap_or("?").to_string();
        let n = by.get(&k).and_then(|v| v.as_i64()).unwrap_or(0) + 1;
        by.insert(k, json!(n));
    }
    json!(by)
}

/// The project beside the sheet that lists it.
fn project_of(sheet: &str) -> Option<String> {
    let p = std::path::PathBuf::from(sheet.replace('\\', "/"));
    let name = p.file_name()?.to_string_lossy().to_lowercase();
    std::fs::read_dir(p.parent()?).ok()?.flatten().map(|e| e.path())
        .filter(|f| f.extension().map(|x| x.eq_ignore_ascii_case("PrjPcb")).unwrap_or(false))
        .find(|f| std::fs::read_to_string(f).map(|t| t.to_lowercase().lines().any(|l| l.starts_with("documentpath=") && l.ends_with(&name))).unwrap_or(false))
        .map(|f| f.to_string_lossy().to_string())
}

fn ok(r: &Value) -> bool { r.get("success").and_then(|b| b.as_bool()) == Some(true) && r.get("data").map(|d| d["ok"] != json!(false)).unwrap_or(true) }

/// altium_sch_batch {filePath | sheet, ops, dryRun?, erc?}
pub fn sch_batch(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let Some(sheet) = crate::support::s(args, "filePath").or_else(|| crate::support::s(args, "sheet")).filter(|p| p.to_lowercase().ends_with(".schdoc")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .SchDoc) is required"});
    };
    let Some(ops) = args.get("ops").and_then(|v| v.as_array()).filter(|a| !a.is_empty()).cloned() else {
        return json!({"success": false, "errorCode": "bad_args", "error": "ops: [{op: a schematic verb, ...its arguments}] is required"});
    };
    let project = crate::support::s(args, "projectPath").or_else(|| project_of(&sheet));
    let steps = match plan(&ops, &sheet, project.as_deref()) {
        Ok(p) => p,
        Err((i, why)) => return json!({"success": false, "errorCode": "bad_op", "failedOp": i, "error": why, "mutated": false}),
    };
    if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {
        return json!({"success": true, "dryRun": true, "mutated": false, "plan": steps.iter().map(|(n, a)| json!({"op": n, "args": a})).collect::<Vec<_>>(),
            "_hint": "Every op is a schematic verb this batch runs, on this sheet. Call again without dryRun to apply them."});
    }
    if let Some(e) = crate::support::must_open(&sheet, 60) { return e; }
    let erc = args.get("erc").and_then(|v| v.as_bool()).unwrap_or(true) && project.is_some();
    let erc_before = if erc { erc_counts(project.as_deref().unwrap_or(""), &sheet) } else { Value::Null };
    let Some(before) = fingerprint(&sheet) else { return json!({"success": false, "errorCode": "sheet_unread", "error": "the sheet's items could not be read, so a failed batch could not be checked back: nothing was run"}) };
    let mut results = Vec::new();
    let _run = crate::runs::begin("sch_batch");
    for (i, (name, a)) in steps.iter().enumerate() {
        crate::runs::stage(&format!("op {i}: {name}"));
        let stop = crate::runs::cancelled();
        let r = if stop { json!({"success": false, "errorCode": "cancelled", "error": "cancelled by cancel_run"}) } else { crate::verbs::dispatch(name, a, &[]) };
        if ok(&r) { results.push(json!({"op": name, "output": r})); continue; }
        // take the batch back: Undo once per op applied, then the sheet must be as it was
        let applied = i;
        for _ in 0..applied {
            crate::agent::call("run_process", &[("process", "Sch:Undo".into()), ("params", "".into())], None, Duration::from_secs(30));
        }
        // a read that fails or lands while Altium is still settling is not proof the sheet differs: PARTIAL is a strong
        // thing to tell a caller, so look again before saying it
        let (mut restored, mut left) = (false, vec!["unread".to_string()]);
        for attempt in 0..4 {
            if attempt > 0 { std::thread::sleep(Duration::from_millis(1500)); }
            if let Some(now) = fingerprint(&sheet) { left = differs(&before, &now); if left.is_empty() { restored = true; break; } }
        }
        let mut out = json!({"success": false, "errorCode": if !restored { "partial" } else if stop { "cancelled" } else { "op_failed" }, "failedOp": i, "op": name,
            "error": r.get("error").cloned().unwrap_or(json!("the op failed")), "reply": r, "results": results,
            "mutated": !restored, "undone": applied, "restored": restored, "differs": left});
        out["_hint"] = json!(if restored { "The batch was taken back: the sheet is as it was before it. Fix failedOp and run the batch again." }
            else { "PARTIAL: the ops in results ran and Undo did not bring the sheet back to where it was: differs names what is not as it was. Read it (schematic_data, sch_items) before going on; Altium's Edit > Undo can step further back by hand." });
        return out;
    }
    let after = fingerprint(&sheet);
    let erc_after = if erc { erc_counts(project.as_deref().unwrap_or(""), &sheet) } else { Value::Null };
    json!({"success": true, "results": results, "mutated": after.as_ref() != Some(&before), "ercBefore": erc_before, "ercAfter": erc_after,
        "undoSteps": steps.len(),
        "_hint": "Applied in order on the open sheet, unsaved: altium_save {filePath} keeps it. Each op is one of Altium's undo steps (undoSteps). ercBefore and ercAfter are the sheet's Messages by class from a compile before and after (erc:false skips both)."})
}

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

    #[test]
    fn a_wire_is_the_path_it_takes() {
        let w = |p: Value| wire_path(&json!({"id": "x", "points": p}));
        assert_eq!(w(json!([[0.0, 0.0], [2.5, 0.0], [5.0, 0.0]])), w(json!([[0.0, 0.0], [5.0, 0.0]])), "a vertex on a straight run");
        assert_eq!(w(json!([[0.0, 0.0], [5.0, 0.0]])), w(json!([[5.0, 0.0], [0.0, 0.0]])), "either way round");
        assert_ne!(w(json!([[0.0, 0.0], [5.0, 0.0]])), w(json!([[0.0, 0.0], [5.0, 1.0]])), "moved");
        assert_ne!(w(json!([[0.0, 0.0], [5.0, 0.0], [5.0, 5.0]])), w(json!([[0.0, 0.0], [5.0, 5.0]])), "a real corner");
        assert_ne!(w(json!([[0.0, 0.0], [5.0, 0.0], [2.0, 0.0]])), w(json!([[0.0, 0.0], [2.0, 0.0]])), "doubling back is not straight on");
    }

    #[test]
    fn order_on_the_sheet_means_nothing() {
        assert_eq!(as_set(&json!([{"id": "a"}, {"id": "b"}])), as_set(&json!([{"id": "b"}, {"id": "a"}])));
        assert_ne!(as_set(&json!([{"id": "a"}, {"id": "b"}])), as_set(&json!([{"id": "a"}, {"id": "c"}])));
        assert_ne!(as_set(&json!([{"id": "a"}])), as_set(&json!([{"id": "a"}, {"id": "a"}])), "two of the same is not one");
    }

    #[test]
    fn a_fingerprint_says_what_differs() {
        let m = |v: &[(&str, &str)]| v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect::<BTreeMap<_, _>>();
        assert!(differs(&m(&[("wires", "1"), ("parts", "2")]), &m(&[("wires", "1"), ("parts", "2")])).is_empty());
        assert_eq!(differs(&m(&[("wires", "1"), ("parts", "2")]), &m(&[("wires", "9"), ("parts", "2")])), ["wires"]);
    }

    #[test]
    fn a_plan_fills_the_sheet_and_refuses_what_it_cannot_take_back() {
        let ops = vec![json!({"op": "sch_place_part", "libReference": "RES"}), json!({"op": "altium_sch_connect_pins", "pairs": [{"from": "R9.1", "to": "U1.3"}]})];
        let p = plan(&ops, "C:/p/Main.SchDoc", None).unwrap();
        assert_eq!(p[0].0, "sch_place_part");
        assert_eq!(p[1].0, "sch_connect_pins");
        assert_eq!(p[1].1["sheet"], "C:/p/Main.SchDoc");
        assert_eq!(p[1].1["save"], false);
        assert!(p[1].1.get("op").is_none());
        assert_eq!(plan(&[json!({"op": "run_drc"})], "C:/p/Main.SchDoc", None).unwrap_err().0, 0);
        assert_eq!(plan(&[json!({"op": "sch_text", "sheet": "C:/p/Other.SchDoc"})], "C:/p/Main.SchDoc", None).unwrap_err().0, 0);
        assert!(plan(&[json!({"op": "sch_text", "sheet": "C:\\p\\main.SchDoc"})], "C:/p/Main.SchDoc", None).is_ok(), "the same sheet in another spelling");
        assert!(plan(&[json!({"op": "annotate"})], "C:/p/Main.SchDoc", None).is_err());
        assert_eq!(plan(&[json!({"op": "annotate"})], "C:/p/Main.SchDoc", Some("C:/p/P.PrjPcb")).unwrap()[0].1["projectPath"], "C:/p/P.PrjPcb");
    }
}