main
Colby Knox 0.2.118 source: simulating leaves the design clean (copy sheets renamed _sim, bridge-written projects and simcfg saved) 8eb52bd
//! altium_sim_copy: a simulation copy of a project's sheets with sources and loads on it, so a design drawn for the
//! board (no stimulus, no load) simulates in Altium without being touched. The copy lives in its own folder beside the
//! project; each source or load is a two-pin part drawn on the copy with a built-in SIM model whose netlist line is the
//! SPICE element itself (Altium's Kind/SubKind for it, as its Simulation Generic Components library has them), joined
//! to its nets by net labels or power ports; R, C and L parts with no model get Altium's generic one. The netlist of the
//! copy is read back to prove every source pin landed on the net it was meant for.
use crate::support::{self, s};
use crate::{agent, sch};
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::time::Duration;

/// One source or load to draw.
#[derive(Clone, Debug, PartialEq)]
pub struct Elem {
    pub designator: String,
    pub prefix: &'static str,
    pub kind: &'static str,
    pub subkind: &'static str,
    /// the SPICE text after the nodes: `DC 12 AC 1 0 PULSE(0 5 0 10n 10n 5u 10u)`, `10k`
    pub tail: String,
    pub plus: String,
    pub minus: String,
}

impl Elem {
    /// The SPICE element as Altium netlists it: its prefix before the designator (VVSIM1, RRSIM1, as it writes RR1 for
    /// R1) and GND as node 0 (measured in the .nsx, AD 26.11, 2026-12-01).
    pub fn spice(&self) -> String { format!("{}{} {} {} {}", self.prefix, self.designator, node(&self.plus), node(&self.minus), self.tail) }
    /// The model's netlist template: the designator and the two pins, then the literal tail.
    pub fn template(&self) -> String { format!("@DESIGNATOR %1 %2 {}", self.tail) }
}

/// A net as a SPICE node in Altium's netlist: GND is node 0.
pub fn node(n: &str) -> String { if n.eq_ignore_ascii_case("GND") { "0".into() } else { n.to_string() } }

/// A SPICE number from a JSON number or a string such as `10k`, `4.7u`, `1meg`, `100nF`. Template characters and
/// spaces are refused: the text goes into Altium's netlist line as it is.
pub fn num(v: &Value) -> Result<String, String> {
    if let Some(f) = v.as_f64() {
        if !f.is_finite() { return Err(format!("{v} is not a number")); }
        let a = f.abs();
        return Ok(if a != 0.0 && !(1e-3..1e6).contains(&a) { format!("{f:e}") } else { format!("{f}") });
    }
    let Some(t) = v.as_str().map(str::trim) else { return Err(format!("{v}: a number, or a SPICE value such as 10k or 4.7u")) };
    let b = t.as_bytes();
    let mut i = 0;
    if i < b.len() && (b[i] == b'+' || b[i] == b'-') { i += 1; }
    let digits_start = i;
    while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') { i += 1; }
    if i == digits_start || t[digits_start..i].chars().filter(|c| *c == '.').count() > 1 || &t[digits_start..i] == "." {
        return Err(format!("{t}: a SPICE value such as 10k, 4.7u or 1e-6"));
    }
    if i < b.len() && (b[i] == b'e' || b[i] == b'E') && b.get(i + 1).map(|c| c.is_ascii_digit() || *c == b'+' || *c == b'-').unwrap_or(false) {
        i += 2;
        while i < b.len() && b[i].is_ascii_digit() { i += 1; }
    }
    if !t[i..].chars().all(|c| c.is_ascii_alphabetic()) { return Err(format!("{t}: a SPICE value such as 10k, 4.7u or 1e-6 (no spaces or symbols)")); }
    Ok(t.to_string())
}

fn field<'a>(o: &'a Value, keys: &[&str]) -> Option<&'a Value> { keys.iter().find_map(|k| o.get(*k)).filter(|v| !v.is_null()) }

fn nums(o: &Value, keys: &[(&[&str], Option<&str>)], what: &str) -> Result<Vec<String>, String> {
    keys.iter().map(|(names, dflt)| match field(o, names) {
        Some(v) => num(v).map_err(|e| format!("{what}.{}: {e}", names[0])),
        None => dflt.map(str::to_string).ok_or_else(|| format!("{what}.{} is required", names[0])),
    }).collect()
}

fn net_of(o: &Value, keys: &[&str], dflt: Option<&str>) -> Result<String, String> {
    match field(o, keys).and_then(|v| v.as_str()).map(str::trim).filter(|v| !v.is_empty()) {
        Some(n) if n.chars().any(|c| c.is_whitespace() || "|@%?#&~".contains(c)) => Err(format!("{}: {n} is not a net name", keys[0])),
        Some(n) => Ok(n.to_string()),
        None => dflt.map(str::to_string).ok_or_else(|| format!("{} is required: the net (or Ref.Pin) the part's first pin goes to", keys[0])),
    }
}

/// A source: {type: voltage|current, plus, minus (GND), dc?, ac?: magnitude | {magnitude, phase}, sin? | pulse? | pwl?}.
pub fn source(o: &Value, designator: String) -> Result<Elem, String> {
    let ty = o.get("type").and_then(|v| v.as_str()).unwrap_or("voltage").to_ascii_lowercase();
    let (prefix, kind) = match ty.as_str() { "voltage" | "v" => ("V", "Voltage Source"), "current" | "i" => ("I", "Current Source"), t => return Err(format!("source type {t}: voltage or current")) };
    let mut tail = Vec::new();
    if let Some(v) = field(o, &["dc"]) { tail.push(format!("DC {}", num(v).map_err(|e| format!("dc: {e}"))?)); }
    let mut subkind = "DC Source";
    let waves = ["sin", "pulse", "pwl"].iter().filter(|k| field(o, &[k]).is_some()).count();
    if waves > 1 { return Err("give one of sin, pulse or pwl".into()); }
    if let Some(w) = field(o, &["sin"]) {
        let n = nums(w, &[(&["offset"], Some("0")), (&["amplitude"], None), (&["frequency"], None), (&["delay"], Some("0")), (&["damping"], Some("0")), (&["phase"], Some("0"))], "sin")?;
        tail.push(format!("SIN({})", n.join(" ")));
        subkind = "Sinusoidal";
    } else if let Some(w) = field(o, &["pulse"]) {
        let n = nums(w, &[(&["initial", "v1", "i1"], Some("0")), (&["pulsed", "v2", "i2"], None), (&["delay"], Some("0")), (&["rise"], Some("1n")), (&["fall"], Some("1n")), (&["width"], None), (&["period"], None)], "pulse")?;
        tail.push(format!("PULSE({})", n.join(" ")));
        subkind = "Pulse";
    } else if let Some(w) = field(o, &["pwl"]) {
        let pts = w.as_array().filter(|a| !a.is_empty()).ok_or("pwl: [[time, value], ...]")?;
        let mut ps = Vec::new();
        for p in pts {
            let (Some(t), Some(v)) = (p.get(0), p.get(1)) else { return Err("pwl: each point is [time, value]".into()) };
            ps.push(format!("{} {}", num(t)?, num(v)?));
        }
        tail.push(format!("PWL({})", ps.join(" ")));
        subkind = "Piecewise Linear";
    }
    if let Some(a) = field(o, &["ac"]) {
        let (m, p) = if a.is_object() { (field(a, &["magnitude"]).cloned().unwrap_or(json!(1)), field(a, &["phase"]).cloned().unwrap_or(json!(0))) } else { (a.clone(), json!(0)) };
        tail.push(format!("AC {} {}", num(&m).map_err(|e| format!("ac: {e}"))?, num(&p).map_err(|e| format!("ac phase: {e}"))?));
    }
    if tail.is_empty() { return Err("a source needs dc, ac, sin, pulse or pwl".into()); }
    Ok(Elem { designator, prefix, kind, subkind, tail: tail.join(" "), plus: net_of(o, &["plus", "net", "pos"], None)?, minus: net_of(o, &["minus", "neg"], Some("GND"))? })
}

/// A load: {type: resistor|capacitor|inductor, value, plus, minus (GND), ic?}.
pub fn load(o: &Value, designator: String) -> Result<Elem, String> {
    let ty = o.get("type").and_then(|v| v.as_str()).unwrap_or("resistor");
    let Some((sub, prefix)) = crate::simmodel::generic_kind(ty) else { return Err(format!("load type {ty}: resistor, capacitor or inductor")) };
    let v = field(o, &["value"]).ok_or("value is required: 10, 4.7u, 1k ...")?;
    let mut tail = num(v).map_err(|e| format!("value: {e}"))?;
    if let Some(ic) = field(o, &["ic"]) { tail.push_str(&format!(" IC={}", num(ic).map_err(|e| format!("ic: {e}"))?)); }
    Ok(Elem { designator, prefix, kind: "General", subkind: sub, tail, plus: net_of(o, &["plus", "net", "pos"], None)?, minus: net_of(o, &["minus", "neg"], Some("GND"))? })
}

/// The sources and loads of a call, each with its designator (given, or VSIM1, ISIM1, RSIM1, ... in order).
pub fn elems(args: &Value) -> Result<Vec<Elem>, String> {
    let mut out: Vec<Elem> = Vec::new();
    let next = |prefix: &str, given: Option<&str>, out: &Vec<Elem>| -> Result<String, String> {
        if let Some(g) = given.map(str::trim).filter(|g| !g.is_empty()) {
            if g.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_') { return Err(format!("designator {g}: letters, digits and _ only")); }
            if !g.to_ascii_uppercase().starts_with(prefix) { return Err(format!("designator {g}: SPICE names a {prefix} element by its first letter, so start it with {prefix}")); }
            return Ok(g.to_string());
        }
        let mut n = 1;
        loop {
            let d = format!("{prefix}SIM{n}");
            if !out.iter().any(|e| e.designator.eq_ignore_ascii_case(&d)) { return Ok(d); }
            n += 1;
        }
    };
    for (key, is_src) in [("sources", true), ("loads", false)] {
        for (i, o) in args.get(key).and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().enumerate() {
            let prefix = if is_src { if o.get("type").and_then(|v| v.as_str()).map(|t| t.eq_ignore_ascii_case("current") || t.eq_ignore_ascii_case("i")).unwrap_or(false) { "I" } else { "V" } }
                else { crate::simmodel::generic_kind(o.get("type").and_then(|v| v.as_str()).unwrap_or("resistor")).map(|g| g.1).unwrap_or("R") };
            let d = next(prefix, o.get("designator").and_then(|v| v.as_str()), &out).map_err(|e| format!("{key}[{i}]: {e}"))?;
            let e = if is_src { source(o, d) } else { load(o, d) }.map_err(|e| format!("{key}[{i}]: {e}"))?;
            if out.iter().any(|x| x.designator.eq_ignore_ascii_case(&e.designator)) { return Err(format!("{key}[{i}]: designator {} is used twice", e.designator)); }
            out.push(e);
        }
    }
    Ok(out)
}

/// A net that is ground: its pin gets a ground power port.
pub fn ground_like(n: &str) -> bool { matches!(n.to_ascii_uppercase().as_str(), "GND" | "0" | "AGND" | "DGND" | "PGND" | "GNDA" | "GNDD" | "VSS") }

/// `R1.2` -> (R1, 2) when it reads as a part's pin.
pub fn pin_ref(n: &str) -> Option<(String, String)> {
    let (d, p) = n.split_once('.')?;
    (d.chars().next().map(|c| c.is_ascii_alphabetic()).unwrap_or(false) && d.chars().any(|c| c.is_ascii_digit()) && !p.is_empty()).then(|| (d.to_string(), p.to_string()))
}

/// The copy's project file: the original's text with only its sheets (at their new relative paths) and its schematic
/// libraries (absolute, for the models they hold) as documents, renumbered; everything else of the project (its
/// options, its net identifier scope, its variants) kept.
pub fn copy_project_text(text: &str, dir: &Path, sheets_rel: &[(String, String)]) -> String {
    let mut out: Vec<String> = Vec::new();
    let mut docs: Vec<String> = Vec::new();
    let mut skip = false;
    for raw in text.lines() {
        let l = raw.trim_end();
        let t = l.trim();
        if t.starts_with('[') && t.ends_with(']') {
            let low = t[1..t.len() - 1].to_ascii_lowercase();
            skip = low.starts_with("document") || low.starts_with("devicesheet") || low.starts_with("generateddocument");
            if !skip { out.push(l.to_string()); }
            continue;
        }
        if skip {
            if let Some(d) = t.strip_prefix("DocumentPath=") {
                let low = d.to_ascii_lowercase();
                if low.ends_with(".schlib") || low.ends_with(".intlib") {
                    let p = if Path::new(d).is_absolute() || d.contains(':') { d.to_string() } else { dir.join(d.replace('\\', "/")).to_string_lossy().replace('/', "\\") };
                    docs.push(p);
                }
            }
            continue;
        }
        out.push(l.to_string());
    }
    let mut text = out.join("\r\n");
    while text.ends_with("\r\n\r\n") { text.truncate(text.len() - 2); }
    if !text.ends_with("\r\n") { text.push_str("\r\n"); }
    let mut n = 0;
    for (_, rel) in sheets_rel { n += 1; text.push_str(&format!("\r\n[Document{n}]\r\nDocumentPath={rel}\r\nAnnotationEnabled=1\r\n")); }
    for p in docs { n += 1; text.push_str(&format!("\r\n[Document{n}]\r\nDocumentPath={p}\r\n")); }
    text
}

/// Where a sheet goes in the copy: its path under the project folder kept, a sheet from elsewhere by its name, and
/// `_sim` added to its name (Main.SchDoc -> Main_sim.SchDoc). With the design's own name the copy's sheet shared a file
/// name with an open sheet of the design, and compiling the copy left the design's sheets asking to be saved (measured
/// 2026-12-01: Altium matches open documents by file name).
pub fn rel_in_copy(prj_dir: &Path, sheet: &str) -> String {
    let r = crate::routing::rel_to(&prj_dir.to_string_lossy(), sheet);
    let r = if r.contains(':') || r.starts_with("..") || r.starts_with('\\') { Path::new(&sheet.replace('\\', "/")).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or(r) } else { r };
    match r.rfind('.') {
        Some(i) if !r[i..].contains('\\') => format!("{}_sim{}", &r[..i], &r[i..]),
        _ => format!("{r}_sim"),
    }
}

/// A path's file name, either separator.
fn base(p: &str) -> String { p.rsplit(['\\', '/']).next().unwrap_or(p).to_string() }

const MARKER: &str = "adom-sim-copy.json";

/// The parts stand in one column, this far apart: a part spans 800 mil pin end to pin end and each pin's stub adds 200,
/// so 2000 leaves 800 between one part's top stub and the next one's bottom stub, room for the ground symbol and the
/// label. At 1000 the stubs overlapped and joined every net to GND (measured 2026-12-01; the netlist check caught it);
/// at 1600 they were apart but the ground symbol touched the next label.
const PITCH_MIL: i64 = 2000;

fn fail(code: &str, msg: String) -> Value { json!({"success": false, "errorCode": code, "error": msg}) }

/// Close the copy's documents in Altium (they are ours) and remove its folder, which must be one this verb made.
fn clear_copy(dir: &Path, prj: &Path) -> Result<(), Value> {
    if !dir.exists() { return Ok(()); }
    if !dir.join(MARKER).exists() && std::fs::read_dir(dir).map(|mut r| r.next().is_some()).unwrap_or(false) {
        return Err(json!({"success": false, "errorCode": "copy_dir_not_ours", "error": format!("{} exists and is not a simulation copy this verb made", dir.display()),
            "_hint": "Give copyDir a new or empty folder."}));
    }
    if prj.exists() {
        let (open, _) = crate::routing::project_members(prj);
        crate::routing::close_project_saved(&prj.to_string_lossy(), &open);
    }
    std::fs::remove_dir_all(dir).map_err(|e| fail("write_failed", format!("{}: {e} (a document of the copy may still be open)", dir.display())))
}

/// Close the other simulation copies this verb made that Altium still holds (it reopens projects at launch): their sheets
/// share names with this copy's when the designs did, and Altium then asked to save them at close (measured 2026-12-01).
/// Only folders with this verb's marker are touched; their documents are saved first.
fn close_other_copies(keep: &Path) -> Vec<String> {
    let d = agent::call("docs", &[], None, Duration::from_secs(30));
    let keep_s = keep.to_string_lossy().replace('/', "\\").to_ascii_lowercase();
    let mut closed = Vec::new();
    for x in d.pointer("/data/documents").and_then(|a| a.as_array()).cloned().unwrap_or_default() {
        let f = x["file"].as_str().unwrap_or("").to_string();
        if !f.to_ascii_lowercase().ends_with(".prjpcb") || f.eq_ignore_ascii_case(&keep_s) { continue; }
        let p = PathBuf::from(&f);
        if !p.parent().map(|d| d.join(MARKER).exists()).unwrap_or(false) { continue; }
        let (open, _) = crate::routing::project_members(&p);
        crate::routing::close_project_saved(&f, &open);
        closed.push(f);
    }
    closed
}

/// altium_sim_copy {schematic, sources?, loads?, genericPassives? (true), copyDir?}
pub fn sim_copy(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let (sheet, prj) = match crate::sim::sheet_and_project(args) { Ok(x) => x, Err(e) => return e };
    let elems = match elems(args) { Ok(e) => e, Err(m) => return fail("bad_args", m) };
    let generic = args.get("genericPassives").and_then(|b| b.as_bool()).unwrap_or(true);
    if elems.is_empty() && !generic { return fail("bad_args", "nothing to do: give sources, loads or genericPassives".into()); }
    let sheet_s = sheet.to_string_lossy().to_string();
    if crate::project::has_changes(&sheet_s) == Some(true) {
        return json!({"success": false, "errorCode": "unsaved_changes", "error": format!("{sheet_s} has unsaved changes: the copy is made from the file"), "_hint": "altium_save it first."});
    }
    let prj_dir = prj.parent().unwrap_or(Path::new(".")).to_path_buf();
    let stem = prj.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "Project".into());
    let copy_dir = s(args, "copyDir").map(|d| PathBuf::from(d.replace('/', "\\"))).unwrap_or_else(|| prj_dir.join("AdomSim").join(&stem));
    let copy_prj = copy_dir.join(format!("{stem}_sim.PrjPcb"));
    if let Err(e) = clear_copy(&copy_dir, &copy_prj) { return e; }
    let closed_copies = close_other_copies(&copy_prj);
    let text = match std::fs::read(&prj) { Ok(b) => String::from_utf8_lossy(&b).to_string(), Err(e) => return fail("file_not_found", format!("{}: {e}", prj.display())) };
    let sheets = crate::bom::parse_project(&text, &prj_dir).sheets;
    let rels: Vec<(String, String)> = sheets.iter().map(|s| (s.clone(), rel_in_copy(&prj_dir, s))).collect();
    let norm = |p: &str| p.replace('/', "\\").to_ascii_lowercase();
    let mut target: Option<String> = None;
    for (src, rel) in &rels {
        let dst = copy_dir.join(rel.replace('\\', "/"));
        if let Some(p) = dst.parent() { let _ = std::fs::create_dir_all(p); }
        if let Err(e) = std::fs::copy(src, &dst) { return fail("write_failed", format!("{src} -> {}: {e}", dst.display())); }
        if norm(src) == norm(&sheet_s) { target = Some(dst.to_string_lossy().replace('/', "\\")); }
    }
    let Some(target) = target else {
        return fail("sheet_not_in_project", format!("{} does not list {}", prj.display(), sheet.display()));
    };
    if let Err(e) = std::fs::write(&copy_prj, copy_project_text(&text, &prj_dir, &rels)) { return fail("write_failed", format!("{}: {e}", copy_prj.display())); }
    let _ = std::fs::write(copy_dir.join(MARKER), serde_json::to_string_pretty(&json!({"source": prj.to_string_lossy(), "sheet": sheet_s, "made": crate::report::iso_utc(chrono_now())})).unwrap_or_default());
    let copy_prj_s = copy_prj.to_string_lossy().replace('/', "\\");
    agent::call("open", &[("path", copy_prj_s.clone())], None, Duration::from_secs(120));

    // the copy's sheet symbols name the renamed sheets
    if rels.len() > 1 {
        let map: Vec<String> = rels.iter().map(|(src, rel)| format!("{}|{}", base(src), base(rel))).collect();
        for (_, rel) in &rels {
            let p = copy_dir.join(rel.replace('\\', "/")).to_string_lossy().replace('/', "\\");
            if let Some(e) = support::must_open(&p, 60) { return e; }
            let r = agent::call("sim_refs", &[], Some(&map.join("\n")), Duration::from_secs(60));
            let d = match sch::agent_data(&r) { Ok(d) => d, Err(e) => return e };
            if d["renamed"].as_i64().unwrap_or(0) > 0 { sch::maybe_save(&json!({}), &p); }
        }
    }

    // R, C and L with no model get Altium's generic one, on every sheet of the copy
    let mut passives: Vec<Value> = Vec::new();
    if generic {
        for (_, rel) in &rels {
            let p = copy_dir.join(rel.replace('\\', "/")).to_string_lossy().replace('/', "\\");
            if let Some(e) = support::must_open(&p, 60) { return e; }
            let r = agent::call("sim_generic", &[], None, Duration::from_secs(90));
            match sch::agent_data(&r) { Ok(d) => passives.extend(d["parts"].as_array().cloned().unwrap_or_default()), Err(e) => return e }
            sch::maybe_save(&json!({}), &p);
        }
    }

    // nets named by a part's pin (R1.2): their compiled names
    let mut nets_before: Option<serde_json::Map<String, Value>> = None;
    let mut resolve = |n: &str| -> Result<String, Value> {
        let Some((d, p)) = pin_ref(n) else { return Ok(n.to_string()) };
        if nets_before.is_none() {
            let r = crate::hier::netlist(&json!({"projectPath": copy_prj_s}));
            nets_before = Some(r["nets"].as_object().cloned().unwrap_or_default());
        }
        let want = format!("{d}.{p}").to_ascii_uppercase();
        nets_before.as_ref().unwrap().iter().find(|(_, pins)| pins.as_array().map(|a| a.iter().any(|x| x.as_str().map(|s| s.to_ascii_uppercase() == want).unwrap_or(false))).unwrap_or(false))
            .map(|(k, _)| k.clone()).map(Ok).unwrap_or_else(|| if nets_before.as_ref().unwrap().contains_key(n) { Ok(n.to_string()) } else {
                Err(json!({"success": false, "errorCode": "net_not_found", "error": format!("{n}: no pin {d}.{p} in the copy's netlist (and no net of that name)"), "copy": {"project": copy_prj_s}}))
            })
    };
    let mut placed: Vec<Elem> = Vec::new();
    for e in &elems {
        let mut r = e.clone();
        r.plus = match resolve(&e.plus) { Ok(n) => n, Err(v) => return v };
        r.minus = match resolve(&e.minus) { Ok(n) => n, Err(v) => return v };
        placed.push(r);
    }

    let mut out_parts: Vec<Value> = Vec::new();
    let mut checks: Vec<Value> = Vec::new();
    if !placed.is_empty() {
        if let Some(e) = support::must_open(&target, 60) { return e; }
        // a net a power port names on this sheet joins by a power port; any other by a net label
        let items = crate::schwire::items(&json!({"sheet": target, "kinds": ["powerPorts"]}));
        let ports: Vec<String> = items["powerPorts"].as_array().cloned().unwrap_or_default().iter().filter_map(|p| p["net"].as_str().map(|s| s.to_ascii_uppercase())).collect();
        let kind = |n: &str| if ground_like(n) || ports.contains(&n.to_ascii_uppercase()) { "power" } else { "label" };
        let mut conns = Vec::new();
        let mut col = "auto".to_string();
        for (i, e) in placed.iter().enumerate() {
            let (plus, minus) = (&e.plus, &e.minus);
            let (pn1, pn2) = if e.prefix == "V" || e.prefix == "I" { ("+", "-") } else { ("1", "2") };
            let r = agent::call("sim_part", &[("des", e.designator.clone()), ("x", col.clone()), ("y", (1000 + PITCH_MIL * i as i64).to_string()),
                ("comment", e.tail.clone()), ("name", format!("ADOM_{}", e.designator)), ("desc", format!("{} (altium_sim_copy)", e.subkind)),
                ("kind", e.kind.into()), ("subkind", e.subkind.into()), ("prefix", e.prefix.into()), ("netlist", e.template()), ("pn1", pn1.into()), ("pn2", pn2.into())],
                None, Duration::from_secs(60));
            let d = match sch::agent_data(&r) { Ok(d) => d, Err(v) => return v };
            // the rest in one column under the first
            if let Some(x) = d["atMil"].get(0).and_then(|x| x.as_i64()) { col = x.to_string(); }
            conns.push(json!({"designator": e.designator, "pin": "1", "net": plus, "kind": kind(plus)}));
            conns.push(json!({"designator": e.designator, "pin": "2", "net": minus, "kind": kind(minus)}));
            out_parts.push(json!({"designator": e.designator, "kind": e.kind, "subKind": e.subkind, "plus": plus, "minus": minus,
                "spice": e.spice(), "atMil": d["atMil"]}));
        }
        let c = sch::connect(&json!({"sheet": target, "connections": conns, "save": true}));
        if c["success"] != json!(true) {
            let mut v = c.clone();
            v["copy"] = json!({"project": copy_prj_s, "schematic": target});
            return v;
        }
        // proof: every pin of every source and load on the net it was meant for, with other pins beside it
        let n = crate::hier::netlist(&json!({"projectPath": copy_prj_s}));
        let nets = n["nets"].as_object().cloned().unwrap_or_default();
        for e in &placed {
            for (pin, want) in [("1", &e.plus), ("2", &e.minus)] {
                let key = format!("{}.{}", e.designator, pin).to_ascii_uppercase();
                let hit = nets.iter().find(|(_, ps)| ps.as_array().map(|a| a.iter().any(|x| x.as_str().map(|s| s.to_ascii_uppercase() == key).unwrap_or(false))).unwrap_or(false));
                let (net, others) = hit.map(|(k, ps)| (k.clone(), ps.as_array().map(|a| a.len().saturating_sub(1)).unwrap_or(0))).unwrap_or_default();
                let ok = !net.is_empty() && others > 0 && (net.eq_ignore_ascii_case(want) || (ground_like(want) && ground_like(&net)));
                checks.push(json!({"pin": format!("{}.{}", e.designator, pin), "want": want, "net": if net.is_empty() { Value::Null } else { json!(net) }, "otherPins": others, "ok": ok}));
            }
        }
    }
    // the copy's project file, written here, is saved by Altium once so it closes without asking
    let _ = crate::surfaces::save(&json!({"filePath": copy_prj_s}));
    let bad: Vec<&Value> = checks.iter().filter(|c| c["ok"] != json!(true)).collect();
    let no_value: Vec<Value> = passives.iter().filter(|p| p["result"] == json!("no_value") || p["result"] == json!("not_two_pins")).cloned().collect();
    json!({"success": bad.is_empty(), "errorCode": if bad.is_empty() { Value::Null } else { json!("not_connected") },
        "copy": {"project": copy_prj_s, "schematic": target, "dir": copy_dir.to_string_lossy().replace('/', "\\")},
        "parts": out_parts, "checks": checks, "genericPassives": passives, "closedCopies": closed_copies, "passivesWithoutValue": no_value,
        "_hint": if bad.is_empty() {
            "The copy is ready: altium_simulate {schematic: copy.schematic, analysis: ...} runs it (probe nets by name; GND is SPICE's node 0). The design itself is untouched. Calling again rebuilds the copy from the design."
        } else {
            "A source or load pin is not on the net it was meant for (checks): the net may be named only on another sheet, or by a port. Name it on this sheet, or pass Ref.Pin (R1.2) as plus/minus."
        }})
}

fn chrono_now() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) }

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

    #[test]
    fn spice_numbers_are_kept_or_refused() {
        assert_eq!(num(&json!(12)).unwrap(), "12");
        assert_eq!(num(&json!(4.7e-6)).unwrap(), "4.7e-6");
        assert_eq!(num(&json!(1e6)).unwrap(), "1e6");
        assert_eq!(num(&json!("10k")).unwrap(), "10k");
        assert_eq!(num(&json!("100nF")).unwrap(), "100nF");
        assert_eq!(num(&json!("1e-3")).unwrap(), "1e-3");
        assert_eq!(num(&json!("-2.5meg")).unwrap(), "-2.5meg");
        for bad in ["10 k", "@VALUE", "1|2", "", ".", "k10", "1.2.3"] { assert!(num(&json!(bad)).is_err(), "{bad}"); }
    }

    #[test]
    fn a_source_is_written_as_spice_writes_it() {
        let e = source(&json!({"plus": "VIN", "dc": 12, "ac": 1}), "VSIM1".into()).unwrap();
        assert_eq!(e.spice(), "VVSIM1 VIN 0 DC 12 AC 1 0");
        assert_eq!((e.prefix, e.kind, e.subkind), ("V", "Voltage Source", "DC Source"));
        assert_eq!(e.template(), "@DESIGNATOR %1 %2 DC 12 AC 1 0");
        let p = source(&json!({"plus": "SW", "minus": "0", "pulse": {"v2": 5, "width": "5u", "period": "10u"}}), "V2".into()).unwrap();
        assert_eq!(p.tail, "PULSE(0 5 0 1n 1n 5u 10u)");
        assert_eq!(p.subkind, "Pulse");
        let s = source(&json!({"type": "current", "plus": "OUT", "sin": {"amplitude": "1m", "frequency": "1k"}}), "I1".into()).unwrap();
        assert_eq!((s.prefix, s.tail.as_str()), ("I", "SIN(0 1m 1k 0 0 0)"));
        let w = source(&json!({"plus": "A", "pwl": [[0, 0], ["1u", 5]]}), "V3".into()).unwrap();
        assert_eq!(w.tail, "PWL(0 0 1u 5)");
        assert!(source(&json!({"plus": "A"}), "V4".into()).is_err(), "no value");
        assert!(source(&json!({"dc": 1}), "V4".into()).is_err(), "no net");
        assert!(source(&json!({"plus": "A", "sin": {"amplitude": 1, "frequency": 1}, "pulse": {}}), "V4".into()).is_err());
    }

    #[test]
    fn loads_and_designators() {
        let l = load(&json!({"type": "capacitor", "plus": "OUT", "value": "10u", "ic": 0}), "CSIM1".into()).unwrap();
        assert_eq!(l.spice(), "CCSIM1 OUT 0 10u IC=0");
        assert_eq!((l.prefix, l.kind, l.subkind), ("C", "General", "Capacitor"));
        let es = elems(&json!({"sources": [{"plus": "VIN", "dc": 5}, {"plus": "EN", "dc": 1}, {"type": "current", "plus": "X", "dc": "1m"}], "loads": [{"plus": "OUT", "value": 10}]})).unwrap();
        assert_eq!(es.iter().map(|e| e.designator.as_str()).collect::<Vec<_>>(), vec!["VSIM1", "VSIM2", "ISIM1", "RSIM1"]);
        assert!(elems(&json!({"sources": [{"designator": "U9", "plus": "A", "dc": 1}]})).is_err(), "a V element named U");
        assert!(elems(&json!({"sources": [{"designator": "V1", "plus": "A", "dc": 1}, {"designator": "v1", "plus": "B", "dc": 1}]})).is_err());
    }

    #[test]
    fn pin_refs_and_ground() {
        assert_eq!(pin_ref("R1.2"), Some(("R1".into(), "2".into())));
        assert_eq!(pin_ref("U3.VIN"), Some(("U3".into(), "VIN".into())));
        assert_eq!(pin_ref("VIN"), None);
        assert_eq!(pin_ref("NET.A"), None, "no digit: a net name");
        assert!(ground_like("gnd") && ground_like("0") && !ground_like("VIN"));
    }

    #[test]
    fn the_copy_project_lists_its_sheets_and_libraries_only() {
        let prj = "[Design]\r\nVersion=1.0\r\nHierarchyMode=0\r\n\r\n[Document1]\r\nDocumentPath=Main.SchDoc\r\nAnnotationEnabled=1\r\n\r\n[Document2]\r\nDocumentPath=Board.PcbDoc\r\n\r\n[Document3]\r\nDocumentPath=Lib\\Parts.SchLib\r\n\r\n[Document4]\r\nDocumentPath=Sub\\Power.SchDoc\r\n\r\n[GeneratedDocument1]\r\nDocumentPath=Out\\x.csv\r\n\r\n[ProjectVariant1]\r\nDescription=Lite\r\n";
        let rels = vec![("C:\\p\\Main.SchDoc".to_string(), "Main.SchDoc".to_string()), ("C:\\p\\Sub\\Power.SchDoc".to_string(), "Sub\\Power.SchDoc".to_string())];
        let t = copy_project_text(prj, Path::new("C:/p"), &rels);
        assert!(t.contains("HierarchyMode=0") && t.contains("[ProjectVariant1]\r\nDescription=Lite"), "{t}");
        assert!(t.contains("[Document1]\r\nDocumentPath=Main.SchDoc") && t.contains("[Document2]\r\nDocumentPath=Sub\\Power.SchDoc"), "{t}");
        assert!(t.contains("[Document3]\r\nDocumentPath=C:") && t.contains("Parts.SchLib"), "{t}");
        assert!(!t.contains("PcbDoc") && !t.contains("GeneratedDocument") && !t.contains("[Document4]"), "{t}");
        assert_eq!(rel_in_copy(Path::new("C:\\p"), "C:\\p\\Sub\\Power.SchDoc"), "Sub\\Power_sim.SchDoc");
        assert_eq!(rel_in_copy(Path::new("C:\\p"), "D:\\shared\\Io.SchDoc"), "Io_sim.SchDoc");
        assert_eq!(base("Sub\\Power_sim.SchDoc"), "Power_sim.SchDoc");
    }
}