main
Colby Knox 0.2.87: schematic_review reads each sheet's drawing (engine 0.23.0 drawing checks); one document per path spelling kept f350e2d
//! A schematic review before Update PCB: every placed pin from the project's sheet files (with its electrical type)
//! against Altium's compiled netlist. Unconnected pins (power pins as errors), nets with one pin, outputs driving each
//! other, inputs nothing drives, and IC power pins with no decoupling capacitor to ground.
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};

/// Altium's pin electrical types (the ELECTRICAL field).
pub fn electrical(n: i64) -> &'static str {
    match n { 0 => "input", 1 => "io", 2 => "output", 3 => "open_collector", 4 => "passive", 5 => "hiz", 6 => "open_emitter", 7 => "power", _ => "unknown" }
}

pub fn is_ground(net: &str) -> bool {
    let n = net.to_ascii_uppercase();
    n == "GND" || n == "0V" || n == "VSS" || n == "AGND" || n == "DGND" || n == "PGND" || n == "GNDA" || n == "GNDD" || n.starts_with("GND_") || n.ends_with("_GND")
}

/// altium_schematic_review {projectPath}
pub fn schematic_review(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let Some(prj) = crate::support::s(args, "projectPath") else { return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) is required"}) };
    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
    if text.is_empty() { return json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj} could not be read")}); }
    let dir = std::path::Path::new(&prj).parent().map(|p| p.to_path_buf()).unwrap_or_default();
    let sheets: Vec<String> = crate::routing::listed_documents(&text, &dir).into_iter().map(|p| p.to_string_lossy().to_string()).filter(|p| p.to_lowercase().ends_with(".schdoc")).collect();
    let mut parts = Vec::new();
    let mut unread = Vec::new();
    for s in &sheets {
        let r = crate::schdoc::read_sheet_file(&json!({"path": s, "pins": true}));
        match r["components"].as_array() { Some(a) => parts.extend(a.iter().cloned()), None => unread.push(json!({"sheet": s, "error": r.get("error").cloned().unwrap_or(Value::Null)})) }
    }
    // each sheet's drawing (the open sheet, read live), for the standard's drawing checks: dangling wire ends, labels
    // off their wire, symbols drawn over each other. drawing:false keeps to the files.
    let mut drawing = Vec::new();
    if args.get("drawing").and_then(|v| v.as_bool()) != Some(false) {
        for s in &sheets {
            let name = std::path::Path::new(&s.replace('\\', "/")).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
            match crate::schwire::load(&json!({"sheet": s})) {
                Ok((_, sh)) => drawing.push(crate::schwire::drawing(&name, &sh)),
                Err(e) => unread.push(json!({"sheet": s, "drawing": e.get("error").cloned().unwrap_or(Value::Null)})),
            }
        }
    }
    let n = crate::hier::netlist(&json!({"projectPath": prj}));
    if n.get("success").and_then(|b| b.as_bool()) != Some(true) { return n; }
    // the standard's review (adom-eda-checks schematic_review): the pin checks, decoupling, and the design checks
    // (floating reset or enable, I2C pull-ups, LED resistors, regulator capacitors) that read each part's value and libRef
    let mut input = json!({"sheetParts": parts, "netlist": {"nets": n["nets"], "names": n.get("names").cloned().unwrap_or(Value::Null)}});
    if !drawing.is_empty() { input["sheetDrawing"] = json!(drawing); }
    let mut out = adom_eda_checks::schreview::schematic_review(&input);
    if out.get("success").and_then(|b| b.as_bool()) != Some(true) { return out; }
    out["sheets"] = json!(sheets);
    out["unreadSheets"] = json!(unread);
    out["compileErrors"] = n["compileErrors"].clone();
    out
}

/// Symbol pins against footprint pads, part by part: pins with no pad (a net that can never reach copper), pads with no
/// pin (copper no net reaches: fine for mounting and mechanical pads), and parts on only one side. Pure.
pub fn pin_pad(parts: &[Value], pads: &[Value], board_refs: &[String]) -> Value {
    let mut pins: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for c in parts {
        let des = c["designator"].as_str().unwrap_or("").to_string();
        if des.is_empty() || des.contains('?') { continue; }
        let e = pins.entry(des).or_default();
        for p in c["pins"].as_array().cloned().unwrap_or_default() { if let Some(n) = p["number"].as_str() { e.insert(n.to_ascii_uppercase()); } }
    }
    let mut padset: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for p in pads {
        let (Some(r), Some(n)) = (p["ref"].as_str().filter(|r| !r.is_empty()), p["name"].as_str()) else { continue };
        padset.entry(r.to_string()).or_default().insert(n.to_ascii_uppercase());
    }
    let mut mismatches = Vec::new();
    let mut ok = 0;
    for (des, ps) in &pins {
        let Some(pd) = padset.get(des) else { continue };
        let no_pad: Vec<&String> = ps.iter().filter(|n| !pd.contains(*n)).collect();
        // unnamed or '0' pads and mounting pads (MH*, EP*, SH*, MP*) carry no pin by design
        let no_pin: Vec<&String> = pd.iter().filter(|n| !ps.contains(*n) && !n.is_empty() && *n != "0" && !["MH", "MP", "SH", "EP", "PAD", "TAB"].iter().any(|m| n.starts_with(m))).collect();
        if no_pad.is_empty() && no_pin.is_empty() { ok += 1; continue; }
        mismatches.push(json!({"ref": des, "pinsWithoutPad": no_pad, "padsWithoutPin": no_pin, "pins": ps.len(), "pads": pd.len()}));
    }
    let on_board: BTreeSet<String> = board_refs.iter().cloned().collect();
    let sheet_only: Vec<&String> = pins.keys().filter(|d| !on_board.contains(*d) && !padset.contains_key(*d)).collect();
    let board_only: Vec<&String> = on_board.iter().filter(|d| !pins.contains_key(*d)).collect();
    json!({"partsChecked": ok + mismatches.len(), "matching": ok, "mismatches": mismatches, "onSheetsOnly": sheet_only, "onBoardOnly": board_only,
           "ok": mismatches.iter().all(|m| m["pinsWithoutPad"].as_array().map(|a| a.is_empty()).unwrap_or(true))})
}

/// altium_pin_pad_check {projectPath, pcbPath}
pub fn pin_pad_check(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let (Some(prj), Some(pcb)) = (crate::support::s(args, "projectPath"), crate::support::s(args, "pcbPath")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) and pcbPath (.PcbDoc) are required"});
    };
    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
    if text.is_empty() { return json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj} could not be read")}); }
    let dir = std::path::Path::new(&prj).parent().map(|p| p.to_path_buf()).unwrap_or_default();
    let mut parts = Vec::new();
    for s in crate::routing::listed_documents(&text, &dir).into_iter().map(|p| p.to_string_lossy().to_string()).filter(|p| p.to_lowercase().ends_with(".schdoc")) {
        if let Some(a) = crate::schdoc::read_sheet_file(&json!({"path": s, "pins": true}))["components"].as_array() { parts.extend(a.iter().cloned()); }
    }
    if let Some(e) = crate::support::must_open(&pcb, 60) { return e; }
    let st = crate::routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
    let refs: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(String::from)).collect();
    let mut out = pin_pad(&parts, st["pads"].as_array().map(|a| a.as_slice()).unwrap_or(&[]), &refs);
    out["success"] = json!(true);
    out["_hint"] = json!("pinsWithoutPad is a part whose footprint cannot carry every pin's net (a wrong footprint or a pin numbering that does not match): fix the footprint or the symbol (altium_swap_footprint, altium_build_footprint) before routing. padsWithoutPin is copper no net reaches. onSheetsOnly / onBoardOnly differ until altium_update_pcb.");
    out
}

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

    fn part(des: &str, pins: &[(&str, &str, i64)]) -> Value {
        json!({"designator": des, "pins": pins.iter().map(|(n, nm, e)| json!({"number": n, "name": nm, "electrical": e})).collect::<Vec<_>>()})
    }

    #[test]
    fn pin_types_come_as_codes_or_names() {
        assert_eq!(adom_eda_checks::schreview::pin_type(&json!(7)), "power");
        assert_eq!(adom_eda_checks::schreview::pin_type(&json!("Bidirectional")), "io");
        assert_eq!(adom_eda_checks::schreview::pin_type(&json!("sup")), "supply");
        let parts = vec![json!({"designator": "U1", "pins": [
            {"number": "1", "name": "IN", "electrical": "input"}, {"number": "2", "name": "X", "electrical": "not_connected"}]}),
            json!({"designator": "P1", "pins": [{"number": "1", "name": "VCC", "electrical": "supply"}]})];
        let nets = json!({"VCC": ["U1.1", "P1.1"]});
        let r = adom_eda_checks::schreview::review(&parts, nets.as_object().unwrap());
        assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");
    }

    #[test]
    fn the_review_finds_each_kind_of_problem() {
        let parts = vec![
            part("U1", &[("1", "VCC", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "NC", 0), ("5", "EN", 0)]),
            part("U2", &[("1", "VDD", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "IN", 0)]),
            part("C1", &[("1", "", 4), ("2", "", 4)]),
            part("R1", &[("1", "", 4), ("2", "", 4)]),
            part("U3", &[("1", "SW", 7)]), part("L1", &[("1", "", 4), ("2", "", 4)]),
        ];
        let nets = json!({"3V3": ["U1.1", "C1.1"], "VDD": ["U2.1"], "LX": ["U3.1", "L1.1"], "GND": ["U1.2", "U2.2", "C1.2"], "BUS": ["U1.3", "U2.3"], "SENSE": ["U2.4"], "R": ["R1.1", "R1.2"]});
        let r = adom_eda_checks::schreview::review(&parts, nets.as_object().unwrap());
        let checks = |k: &str| r[k].as_array().unwrap().iter().map(|f| f["check"].as_str().unwrap().to_string()).collect::<Vec<_>>();
        // U1.5 EN floats (input, warning); NC is skipped; two outputs share BUS (error)
        assert!(checks("errors").contains(&"outputs_together".to_string()));
        assert!(checks("warnings").contains(&"unconnected_pin".to_string()));
        assert!(!r["warnings"].as_array().unwrap().iter().any(|f| f["pin"] == "U1.4"));
        // VDD has one pin and no capacitor; SENSE is an input nothing drives
        assert!(checks("warnings").contains(&"single_pin_net".to_string()));
        assert!(checks("warnings").contains(&"no_decoupling".to_string()));
        assert!(checks("warnings").contains(&"undriven_input".to_string()));
        let dec = r["decoupling"].as_array().unwrap();
        assert!(dec.iter().any(|d| d["net"] == "3V3" && d["ok"] == json!(true)));
        assert!(dec.iter().any(|d| d["net"] == "VDD" && d["ok"] == json!(false)));
        // a regulator's switch pin on an inductor is not a missing capacitor
        assert!(dec.iter().any(|d| d["net"] == "LX" && d["switchNode"] == json!(true) && d["ok"] == json!(true)));
    }
    #[test]
    fn pin_pad_finds_footprints_that_do_not_fit_their_symbols() {
        let parts = vec![part("U1", &[("1", "A", 0), ("2", "B", 0), ("3", "C", 0)]), part("R1", &[("1", "", 4), ("2", "", 4)]), part("C9", &[("1", "", 4), ("2", "", 4)])];
        let pad = |r: &str, n: &str| json!({"ref": r, "name": n});
        let pads = vec![pad("U1", "1"), pad("U1", "2"), pad("U1", "4"), pad("U1", "EP"), pad("R1", "1"), pad("R1", "2"), pad("J9", "1")];
        let r = pin_pad(&parts, &pads, &["U1".into(), "R1".into(), "J9".into()]);
        assert_eq!(r["matching"], 1);
        let m = &r["mismatches"][0];
        assert_eq!(m["ref"], "U1");
        assert_eq!(m["pinsWithoutPad"], json!(["3"]));
        assert_eq!(m["padsWithoutPin"], json!(["4"]));
        assert_eq!(r["onSheetsOnly"], json!(["C9"]));
        assert_eq!(r["onBoardOnly"], json!(["J9"]));
        assert_eq!(r["ok"], json!(false));
    }
}