main
Colby Knox 0.2.119 source: footprint verbs stop creating 1024 mechanical layers (#44); layers only when used, edit_footprint width… a86b045
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
//! Documents and projects, the EDA Bridge Standard's batch 4 and Fusion's app verbs on Altium: the document in front,
//! closing everything without a save dialog, a project at a glance, creating, renaming and snapshotting a project,
//! cross-probing between sheet and board, and one library footprint in full. Millimetres.
use crate::sch::{agent_data, st};
use crate::{agent, support};
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::time::Duration;

fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }
fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }

/// What a document is, from its file name. Pure.
pub fn kind_of(file: &str) -> &'static str {
    let l = file.to_lowercase();
    if l.ends_with(".prjpcb") || l.ends_with(".prjscr") || l.ends_with(".prjmbd") || l.ends_with(".prjhar") || l.ends_with(".libpkg") { "project" }
    else if l.ends_with(".schdoc") { "schematic" } else if l.ends_with(".pcbdoc") { "board" }
    else if l.ends_with(".schlib") || l.ends_with(".pcblib") || l.ends_with(".intlib") { "library" }
    else if l.ends_with(".step") || l.ends_with(".stp") { "model" } else { "other" }
}

/// The project beside a document that lists it.
pub fn project_of(doc: &str) -> Option<String> {
    let dir = Path::new(doc).parent()?;
    let name = Path::new(doc).file_name()?.to_string_lossy().to_lowercase();
    std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path())
        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("prjpcb")).unwrap_or(false))
        .find(|p| std::fs::read_to_string(p).map(|t| t.lines().any(|l| l.to_lowercase().starts_with("documentpath=") && l.to_lowercase().replace('/', "\\").ends_with(&name))).unwrap_or(false))
        .map(|p| p.to_string_lossy().to_string())
}

/// Documents this bridge changed and has not saved since. Altium's scripting API reads a document's changed flag back
/// as false even while its title shows the * (measured 2026-10-27), so the bridge remembers its own unsaved edits.
static UNSAVED: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());

fn norm(p: &str) -> String { p.replace('/', "\\").to_lowercase() }

/// A bridge edit left this document changed and unsaved.
pub fn mark_unsaved(path: &str) { if !path.is_empty() { if let Ok(mut g) = UNSAVED.lock() { g.insert(norm(path)); } } }

/// The document was saved or closed: nothing of ours is pending on it.
pub fn mark_clean(path: &str) { if let Ok(mut g) = UNSAVED.lock() { g.remove(&norm(path)); } }

fn unsaved(path: &str) -> bool { UNSAVED.lock().map(|g| g.contains(&norm(path))).unwrap_or(false) }

fn docs() -> Result<Value, Value> { agent_data(&agent::call("docs", &[], None, Duration::from_secs(30))) }

/// Whether a document has changes not yet saved: changed by this bridge, or flagged by Altium (which misses scripted
/// schematic edits, hence the bridge's own record). None when Altium could not be asked.
pub(crate) fn has_changes(path: &str) -> Option<bool> {
    if unsaved(path) { return Some(true); }
    let d = docs().ok()?;
    Some(d["documents"].as_array()?.iter().any(|x| norm(&st(&x["file"])) == norm(path) && x["modified"].as_bool() == Some(true)))
}

/// altium_document_info {}
pub fn document_info(_args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let d = match docs() { Ok(d) => d, Err(e) => return e };
    let cur = st(&d["current"]);
    if cur.is_empty() { return json!({"success": false, "errorCode": "no_document", "error": "no document is in front in Altium"}); }
    let entry = d["documents"].as_array().cloned().unwrap_or_default().into_iter().find(|x| st(&x["file"]).eq_ignore_ascii_case(&cur)).unwrap_or(Value::Null);
    let saved = Path::new(&cur).is_file();
    json!({"success": true, "name": Path::new(&cur).file_name().map(|n| n.to_string_lossy().to_string()), "kind": kind_of(&cur), "saved": saved,
        "modified": entry["modified"].as_bool().unwrap_or(false) || unsaved(&cur), "path": if saved { json!(cur) } else { Value::Null }, "version": Value::Null,
        "project": project_of(&cur), "openDocuments": d["documents"].as_array().cloned().unwrap_or_default().iter().map(|x| json!({"name": Path::new(&st(&x["file"])).file_name().map(|n| n.to_string_lossy().to_string()), "path": x["file"], "kind": kind_of(&st(&x["file"])), "modified": x["modified"].as_bool().unwrap_or(false) || unsaved(&st(&x["file"])), "altiumKind": x["kind"]})).collect::<Vec<_>>(),
        "_hint": "Altium keeps no version numbers for local files (version is null); Altium 365 items have revisions (altium_a365_*)."})
}

/// altium_close_all_documents {save?, discardUnsaved?, includeScratch?}
pub fn close_all_documents(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let d = match docs() { Ok(d) => d, Err(e) => return e };
    let b = |k: &str| args.get(k).and_then(|v| v.as_bool()) == Some(true);
    let (save, discard, scratch) = (b("save"), b("discardUnsaved"), b("includeScratch"));
    // under: only the documents in that folder (a project folder about to be replaced, say)
    let under = support::s(args, "under").map(|u| u.replace('/', "\\").trim_end_matches('\\').to_lowercase() + "\\");
    let (mut closed, mut saved, mut kept) = (vec![], vec![], vec![]);
    // projects last: closing a project first can take its documents with it
    let mut list = d["documents"].as_array().cloned().unwrap_or_default();
    list.sort_by_key(|x| kind_of(&st(&x["file"])) == "project");
    for x in list {
        let f = st(&x["file"]);
        if f.is_empty() { continue; }
        if let Some(u) = &under { if !f.replace('/', "\\").to_lowercase().starts_with(u.as_str()) { continue; } }
        // the bridge's own agent (its script project and script) stays: closing it stops the agent mid-verb
        if Path::new(&f).file_name().map(|n| n.to_string_lossy().starts_with("AdomAgent_")).unwrap_or(false) { continue; }
        let name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(f.clone());
        let on_disk = Path::new(&f).is_file();
        let modified = x["modified"].as_bool() == Some(true) || unsaved(&f);
        if !on_disk && !scratch { kept.push(json!({"name": name, "why": "scratch"})); continue; }
        if modified && on_disk && save {
            let r = crate::surfaces::save(&json!({"filePath": f}));
            if r.get("success").and_then(|v| v.as_bool()) == Some(false) { kept.push(json!({"name": name, "why": "save failed", "detail": r.get("error")})); continue; }
            saved.push(json!(name));
        } else if modified && !discard {
            kept.push(json!({"name": name, "why": "unsaved changes"}));
            continue;
        }
        let r = agent::call("close_document", &[("path", f.replace('/', "\\"))], None, Duration::from_secs(30));
        if r.get("data").and_then(|v| v.get("closed")).and_then(|v| v.as_bool()) == Some(true) { mark_clean(&f); closed.push(json!(name)); }
    }
    json!({"success": true, "closed": closed, "saved": saved, "keptOpen": kept,
        "_hint": "Altium closes a document without asking: a changed document stays open unless save:true (saved first) or discardUnsaved:true (its changes are lost: ask the person first). Changed means changed by this bridge and not saved since, or flagged by Altium: Altium's API does not always report edits made by hand, so ask the person before closing their work."})
}

/// A project from a path to the project, its folder or any of its documents.
fn find_project(p: &str) -> Option<String> {
    let path = Path::new(p);
    if p.to_lowercase().ends_with(".prjpcb") && path.is_file() { return Some(p.to_string()); }
    if path.is_dir() {
        return std::fs::read_dir(path).ok()?.filter_map(|e| e.ok()).map(|e| e.path())
            .find(|x| x.extension().map(|e| e.eq_ignore_ascii_case("prjpcb")).unwrap_or(false)).map(|x| x.to_string_lossy().to_string());
    }
    project_of(p)
}

fn project_docs(prj: &str) -> Vec<String> {
    let dir = Path::new(prj).parent().unwrap_or(Path::new(".")).to_path_buf();
    let text = std::fs::read(prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
    text.lines().filter_map(|l| l.trim().strip_prefix("DocumentPath=")).map(|d| {
        let p = Path::new(d);
        if p.is_absolute() || d.contains(':') { d.to_string() } else { dir.join(d.replace('\\', "/").replace('/', std::path::MAIN_SEPARATOR_STR)).to_string_lossy().to_string() }
    }).collect()
}

fn modified_of(p: &Path) -> Value {
    std::fs::metadata(p).ok().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| json!(crate::report::iso_utc(d.as_secs() as i64))).unwrap_or(Value::Null)
}

/// The project file's [Parameter] text variables: Name=, Value= pairs. Pure.
pub fn text_variables(prj_text: &str) -> serde_json::Map<String, Value> {
    let mut out = serde_json::Map::new();
    let mut name: Option<String> = None;
    let mut in_param = false;
    for l in prj_text.lines().map(str::trim) {
        if l.starts_with('[') { in_param = l.to_lowercase().starts_with("[parameter"); name = None; continue; }
        if !in_param { continue; }
        if let Some(n) = l.strip_prefix("Name=") { name = Some(n.to_string()); }
        if let (Some(v), Some(n)) = (l.strip_prefix("Value="), name.as_ref()) { out.insert(n.clone(), json!(v)); }
    }
    out
}

/// altium_project_info {project}
pub fn project_info(args: &Value) -> Value {
    let Some(p) = support::s(args, "project").or_else(|| support::s(args, "projectPath")) else { return bad("project: the project file, its folder or any of its documents") };
    let Some(prj) = find_project(&p) else { return json!({"success": false, "errorCode": "project_not_found", "error": format!("no .PrjPcb found for {p}")}) };
    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
    let docs_list = project_docs(&prj);
    let mut files = vec![json!({"path": prj, "bytes": std::fs::metadata(&prj).map(|m| m.len()).unwrap_or(0), "modified": modified_of(Path::new(&prj))})];
    for d in &docs_list { files.push(json!({"path": d, "bytes": std::fs::metadata(d).map(|m| m.len()).ok(), "modified": modified_of(Path::new(d)), "kind": kind_of(d), "exists": Path::new(d).is_file()})); }
    let sheets = crate::schsheet::hierarchy(&json!({"project": prj}));
    // the board: from Altium when it has it open, else its file size only
    let mut open = false;
    let mut board = Value::Null;
    if support::need_licensed().is_none() {
        if let Ok(d) = docs() {
            let open_files: Vec<String> = d["documents"].as_array().cloned().unwrap_or_default().iter().map(|x| st(&x["file"]).to_lowercase()).collect();
            open = docs_list.iter().chain(std::iter::once(&prj)).any(|f| open_files.contains(&f.to_lowercase()));
            if let Some(pcb) = docs_list.iter().find(|f| kind_of(f) == "board" && open_files.contains(&f.to_lowercase())) {
                if support::must_open(pcb, 30).is_none() {
                    let s = crate::routing::routing_state(&json!({}));
                    let bb = crate::fab::outline_bbox(&s);
                    let stack = agent::call("layer_stack", &[], None, Duration::from_secs(60));
                    board = json!({"file": pcb, "layers": stack.get("data").and_then(|d| d["copperLayers"].as_i64()), "parts": s["components"].as_array().map(|a| a.len()),
                        "nets": s["nets"].as_array().map(|a| a.len()), "sizeMm": bb.map(|b| json!([r3(b.2 - b.0), r3(b.3 - b.1)]))});
                }
            }
        }
    }
    if board.is_null() { if let Some(pcb) = docs_list.iter().find(|f| kind_of(f) == "board") { board = json!({"file": pcb, "note": "not open in Altium: open it for layers, parts, nets and size"}); } }
    let classes: Vec<Value> = Vec::new();
    json!({"success": true, "name": Path::new(&prj).file_stem().map(|s| s.to_string_lossy().to_string()), "project": prj, "files": files, "sheets": sheets["tree"], "sheetProblems": sheets["problems"],
        "board": board, "textVariables": text_variables(&text), "netClasses": classes, "modified": modified_of(Path::new(&prj)), "open": open,
        "_hint": "Read from the files, plus the board from Altium when it has it open. Net classes live in the board: altium_net_classes lists them."})
}

/// A new project's .PrjPcb text: the sheet and the board, and text variables as project parameters. Pure.
pub fn project_text(name: &str, vars: &serde_json::Map<String, Value>) -> String {
    let mut t = String::from("[Design]\r\nVersion=1.0\r\nHierarchyMode=0\r\nChannelRoomNamingStyle=0\r\nOutputPath=Project Outputs for ");
    t.push_str(name);
    t.push_str("\r\n\r\n");
    t.push_str(&format!("[Document1]\r\nDocumentPath={name}.SchDoc\r\nAnnotationEnabled=1\r\n\r\n[Document2]\r\nDocumentPath={name}.PcbDoc\r\nAnnotationEnabled=1\r\n\r\n"));
    for (i, (k, v)) in vars.iter().enumerate() { t.push_str(&format!("[Parameter{}]\r\nName={k}\r\nValue={}\r\n\r\n", i + 1, st(v))); }
    t
}

/// altium_project_create {parentDir, name, title?, layers?, fabRules?, textVariables?, dryRun?}
pub fn project_create(args: &Value) -> Value {
    let (Some(parent), Some(name)) = (support::s(args, "parentDir"), support::s(args, "name")) else { return bad("parentDir and name are required") };
    if name.contains(['\\', '/', ':', '*', '?', '"', '<', '>', '|']) { return bad(format!("{name} is not a usable file name")); }
    let dir = PathBuf::from(&parent).join(&name);
    if dir.is_dir() && std::fs::read_dir(&dir).map(|rd| rd.filter_map(|e| e.ok()).any(|e| e.path().extension().map(|x| x.eq_ignore_ascii_case("prjpcb")).unwrap_or(false))).unwrap_or(false) {
        return json!({"success": false, "errorCode": "exists", "error": format!("{} already holds a project", dir.display())});
    }
    let mut vars = args.get("textVariables").and_then(|v| v.as_object()).cloned().unwrap_or_default();
    if let Some(f) = support::s(args, "fabRules") { vars.insert("FabRules".into(), json!(f)); }
    let prj = dir.join(format!("{name}.PrjPcb"));
    let (sch, pcb) = (dir.join(format!("{name}.SchDoc")), dir.join(format!("{name}.PcbDoc")));
    let layers = args.get("layers").and_then(|v| v.as_i64()).unwrap_or(2);
    if ![2, 4, 6, 8].contains(&layers) { return bad("layers: 2, 4, 6 or 8"); }
    let files = vec![prj.to_string_lossy().to_string(), sch.to_string_lossy().to_string(), pcb.to_string_lossy().to_string()];
    if dry(args) { return json!({"success": true, "dryRun": true, "project": files[0], "files": files, "layers": layers, "textVariables": vars}); }
    if let Some(g) = support::need_licensed() { return g; }
    if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&prj, project_text(&name, &vars))) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    // the sheet from Altium's template, titled; the board as Altium makes a new one, with its layer count
    let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}) };
    if let Err(e) = support::copy_template(&tpl, &sch.to_string_lossy()) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }
    let mut steps = Vec::new();
    if let Some(t) = support::s(args, "title") {
        let r = crate::schsheet::page(&json!({"sheet": sch.to_string_lossy(), "title": t}));
        steps.push(json!({"title": r.get("success")}));
    }
    let nb = agent::call("new_pcb", &[("path", pcb.to_string_lossy().to_string())], None, Duration::from_secs(90));
    if let Err(e) = agent_data(&nb) { return json!({"success": false, "errorCode": "board_failed", "error": "Altium did not make the board", "reply": e, "project": files[0]}); }
    if layers > 2 {
        let r = crate::boardedit::set_layer_count(&json!({"filePath": pcb.to_string_lossy(), "count": layers}));
        steps.push(json!({"layers": r.get("layers"), "success": r.get("success")}));
        let _ = crate::surfaces::save(&json!({"filePath": pcb.to_string_lossy()}));
    }
    // the new documents leave Altium: Altium may have attached the new board to whatever project was in front
    for f in [&pcb, &sch] { let _ = agent::call("close_document", &[("path", f.to_string_lossy().to_string())], None, Duration::from_secs(30)); }
    json!({"success": true, "project": files[0], "files": files, "layers": layers, "textVariables": vars, "steps": steps,
        "_hint": "Altium's new board has its default shape: set the outline (altium_set_outline) before routing or exporting. Open the project with altium_open_project."})
}

/// The renames for a project: the documents named after it. Pure: (from, to) file names.
pub fn rename_plan(old: &str, new: &str, docs: &[String]) -> Vec<(String, String)> {
    let mut out = Vec::new();
    for d in docs {
        let f = Path::new(d).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
        let (stem, ext) = f.rsplit_once('.').map(|(a, b)| (a.to_string(), format!(".{b}"))).unwrap_or((f.clone(), String::new()));
        if stem.eq_ignore_ascii_case(old) { out.push((f.clone(), format!("{new}{ext}"))); }
        else if let Some(rest) = stem.strip_prefix(&format!("{old}.")) { out.push((f.clone(), format!("{new}.{rest}{ext}"))); } // lane.Manufacturing.OutJob
    }
    out
}

/// altium_project_rename {project, newName, dryRun?}
pub fn project_rename(args: &Value) -> Value {
    let (Some(p), Some(new)) = (support::s(args, "project").or_else(|| support::s(args, "projectPath")), support::s(args, "newName")) else { return bad("project and newName are required") };
    let Some(prj) = find_project(&p) else { return json!({"success": false, "errorCode": "project_not_found", "error": format!("no .PrjPcb found for {p}")}) };
    let old = Path::new(&prj).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
    let dir = Path::new(&prj).parent().unwrap_or(Path::new(".")).to_path_buf();
    let docs_list = project_docs(&prj);
    let mut plan = rename_plan(&old, &new, &docs_list);
    plan.insert(0, (format!("{old}.PrjPcb"), format!("{new}.PrjPcb")));
    for (_, to) in &plan { if dir.join(to).exists() { return json!({"success": false, "errorCode": "exists", "error": format!("{to} exists already")}); } }
    if support::need_licensed().is_none() {
        if let Ok(d) = docs() {
            let open: Vec<String> = d["documents"].as_array().cloned().unwrap_or_default().iter().map(|x| st(&x["file"]).to_lowercase()).collect();
            if docs_list.iter().chain(std::iter::once(&prj)).any(|f| open.contains(&f.to_lowercase())) {
                return json!({"success": false, "errorCode": "project_open", "error": "Altium has this project open: close it first (altium_close_all_documents or altium_close_document)"});
            }
        }
    }
    let renamed: Vec<Value> = plan.iter().map(|(a, b)| json!({"from": a, "to": b})).collect();
    // inside the project file: each renamed document's DocumentPath, and the output folder's name
    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
    let mut new_text = text.clone();
    let mut changed = Vec::new();
    for (a, b) in plan.iter().skip(1) {
        let before = new_text.clone();
        new_text = new_text.lines().map(|l| if l.trim().strip_prefix("DocumentPath=").map(|d| d.eq_ignore_ascii_case(a)).unwrap_or(false) { format!("DocumentPath={b}") } else { l.to_string() }).collect::<Vec<_>>().join("\r\n");
        if new_text != before { changed.push(json!({"file": format!("{new}.PrjPcb"), "what": format!("DocumentPath {a} -> {b}")})); }
    }
    if new_text.contains(&format!("Project Outputs for {old}")) { new_text = new_text.replace(&format!("Project Outputs for {old}"), &format!("Project Outputs for {new}")); changed.push(json!({"file": format!("{new}.PrjPcb"), "what": "OutputPath"})); }
    if dry(args) { return json!({"success": true, "dryRun": true, "renamed": renamed, "changed": changed}); }
    if let Err(e) = std::fs::write(&prj, new_text.as_bytes()) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    for (a, b) in &plan { if let Err(e) = std::fs::rename(dir.join(a), dir.join(b)) { return json!({"success": false, "errorCode": "rename_failed", "error": format!("{a} -> {b}: {e}"), "renamed": renamed}); } }
    json!({"success": true, "renamed": renamed, "changed": changed, "project": dir.join(format!("{new}.PrjPcb")).to_string_lossy(),
        "_hint": "Child sheets keep their names; the folder keeps its name. Open the renamed project with altium_open_project."})
}

/// altium_project_snapshot {project, label?, pdfs?}
pub fn project_snapshot(args: &Value) -> Value {
    let Some(p) = support::s(args, "project").or_else(|| support::s(args, "projectPath")) else { return bad("project is required") };
    let Some(prj) = find_project(&p) else { return json!({"success": false, "errorCode": "project_not_found", "error": format!("no .PrjPcb found for {p}")}) };
    let dir = Path::new(&prj).parent().unwrap_or(Path::new(".")).to_path_buf();
    let stamp = crate::report::iso_utc(support::now() as i64).replace([':', '-'], "").replace('T', "-").trim_end_matches('Z').to_string();
    let label = support::s(args, "label").map(|l| format!("-{}", l.replace(['\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '], "_"))).unwrap_or_default();
    let folder = dir.join("snapshots").join(format!("{stamp}{label}"));
    if let Err(e) = std::fs::create_dir_all(&folder) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    let mut files = Vec::new();
    for f in std::iter::once(prj.clone()).chain(project_docs(&prj)) {
        let src = Path::new(&f);
        if !src.is_file() { continue; }
        let to = folder.join(src.file_name().unwrap_or_default());
        if std::fs::copy(src, &to).is_ok() { files.push(to.to_string_lossy().to_string()); }
    }
    let mut pdfs = json!({"made": [], "skipped": Value::Null});
    if args.get("pdfs").and_then(|v| v.as_bool()) != Some(false) {
        if support::need_licensed().is_some() { pdfs["skipped"] = json!("Altium is not running with a licence: the files are copied, no PDFs"); }
        else {
            let out = folder.join("schematic-and-board.pdf");
            let r = crate::sch::export_pdf(&json!({"projectPath": prj, "output": out.to_string_lossy(), "board": true}));
            if r.get("success").and_then(|v| v.as_bool()) == Some(true) { pdfs["made"] = json!([out.to_string_lossy()]); } else { pdfs["skipped"] = json!(format!("the PDF failed: {}", r.get("error").map(|e| e.to_string()).unwrap_or_default())); }
        }
    }
    json!({"success": true, "folder": folder.to_string_lossy(), "files": files, "pdfs": pdfs,
        "_hint": "A copy of what is saved on disk: unsaved edits in Altium are not in it (save first). The PDF holds every sheet and the board's composite print."})
}

/// altium_cross_probe {filePath?, ref?, symbolId?, schematic?, select?}
pub fn cross_probe(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    if let Some(p) = support::s(args, "filePath") { if let Some(e) = support::must_open(&p, 60) { return e; } }
    let st_board = crate::routing::routing_state(&json!({}));
    if st_board.get("success").and_then(|b| b.as_bool()) != Some(true) { return st_board; }
    let pcb = st(&st_board["file"]);
    let cd = agent::call("component_data", &[("designator", String::new()), ("limit", "2000".into())], None, Duration::from_secs(90));
    let parts = cd.get("data").and_then(|d| d["components"].as_array().cloned()).unwrap_or_default();
    // the project's sheets, read from their files
    let sheets: Vec<String> = match support::s(args, "schematic") { Some(s) => vec![s], None => project_of(&pcb).map(|p| project_docs(&p).into_iter().filter(|d| kind_of(d) == "schematic").collect()).unwrap_or_default() };
    let mut syms = Vec::new();
    for sh in &sheets {
        let r = crate::schdoc::read_sheet_file(&json!({"path": sh, "pins": false}));
        for c in r["components"].as_array().cloned().unwrap_or_default() { syms.push((sh.clone(), c)); }
    }
    let want_ref = support::s(args, "ref").map(|r| r.to_uppercase());
    let want_id = support::s(args, "symbolId");
    let mut matches = Vec::new();
    for p in &parts {
        let r = st(&p["designator"]);
        let src = st(&p["sourceUniqueId"]);
        let id_tail = src.rsplit('\\').next().unwrap_or("").to_string();
        let sym = syms.iter().find(|(_, c)| !id_tail.is_empty() && st(&c["uniqueId"]) == id_tail).or_else(|| syms.iter().find(|(_, c)| st(&c["designator"]).eq_ignore_ascii_case(&r)));
        let hit = want_ref.as_ref().map(|w| r.to_uppercase() == *w).unwrap_or(true) && want_id.as_ref().map(|w| sym.map(|(_, c)| st(&c["uniqueId"]) == *w).unwrap_or(false)).unwrap_or(true);
        if !hit { continue; }
        // the exact placement from the board model (component_data rounds to whole mils)
        let c = st_board["components"].as_array().and_then(|a| a.iter().find(|c| st(&c["ref"]).eq_ignore_ascii_case(&r)).cloned()).unwrap_or(Value::Null);
        matches.push(json!({"board": {"ref": r, "id": src, "side": c["side"], "x": c["x"], "y": c["y"], "rotation": c["rotation"]},
            "schematic": sym.map(|(sh, c)| json!({"sheet": sh, "id": c["uniqueId"], "ref": c["designator"], "symbol": c["libReference"], "value": c["comment"]})),
            "linked": !id_tail.is_empty() && sym.map(|(_, c)| st(&c["uniqueId"]) == id_tail).unwrap_or(false)}));
    }
    let board_refs: Vec<String> = parts.iter().map(|p| st(&p["designator"]).to_uppercase()).collect();
    let orphans: Vec<Value> = syms.iter().filter(|(_, c)| !board_refs.contains(&st(&c["designator"]).to_uppercase()) && want_ref.as_ref().map(|w| st(&c["designator"]).to_uppercase() == *w).unwrap_or(true)).map(|(_, c)| c["designator"].clone()).collect();
    if args.get("select").and_then(|v| v.as_bool()) == Some(true) && !matches.is_empty() {
        let refs: Vec<Value> = matches.iter().map(|m| m["board"]["ref"].clone()).collect();
        let _ = crate::design::selection(&json!({"select": refs}));
    }
    if matches.is_empty() && want_ref.is_some() { return json!({"success": false, "errorCode": "part_not_found", "error": "no board part matches", "symbolWithoutPart": orphans}); }
    json!({"success": true, "matches": matches, "symbolWithoutPart": orphans, "sheets": sheets,
        "_hint": "linked:true means the board part carries its symbol's UniqueId (update_pcb put it there); a match by designator alone is linked:false. Sheets are read from their saved files."})
}

/// altium_read_footprint {libraryPath, name}
pub fn read_footprint(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let (Some(lib), Some(name)) = (support::s(args, "libraryPath"), support::s(args, "name")) else { return bad("libraryPath (.PcbLib) and name are required (Altium has no library table: libId is not used)") };
    if let Some(e) = support::must_open(&lib, 60) { return e; }
    let d = match agent_data(&agent::call("lib_fp", &[("name", name.clone()), ("path", lib.replace('/', "\\"))], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };
    let k = d["k"].as_f64().filter(|k| *k > 0.0).unwrap_or(10_000_000.0);
    let mm = |v: &Value| r3(v.as_f64().unwrap_or(0.0) * 25.4 / k);
    // Altium's pad shapes (TShape): 9 is the rounded rectangle of newer libraries
    let shape = |s: i64| match s { 1 => "round", 2 => "rect", 3 => "octagonal", 4 => "circle", 7 | 9 => "roundrect", 8 => "rotated-rect", _ => "other" };
    let pads: Vec<Value> = d["pads"].as_array().cloned().unwrap_or_default().iter().map(|p| {
        let hole = mm(&p[5]);
        let layer = crate::routing::layer_name(p[6].as_i64().unwrap_or(0));
        json!({"number": p[0], "type": if hole > 0.0 { if p[9].as_bool() == Some(false) { "npth" } else { "pth" } } else { "smd" }, "shape": shape(p[7].as_i64().unwrap_or(0)),
            "at": [mm(&p[1]), mm(&p[2])], "sizeMm": [mm(&p[3]), mm(&p[4])], "drillMm": hole, "layers": [layer], "rotation": p[8].as_f64().unwrap_or(0.0) / 1000.0})
    }).collect();
    // each layer by the name the user sees (#41): a typed layer of AD 24+ as "Top Courtyard", silkscreen as F.SilkS
    let lt = crate::fplayers::table(&d["layers"]);
    let others = d["other"].as_array().cloned().unwrap_or_default();
    let mut by_id = serde_json::Map::new();
    let mut graphics = serde_json::Map::new();
    for o in &others {
        let id = o[1].as_i64().unwrap_or(0);
        let k = id.to_string(); let n = by_id.get(&k).and_then(|v| v.as_i64()).unwrap_or(0); by_id.insert(k, json!(n + 1));
        let name = crate::fplayers::display_name(id, &lt); let n = graphics.get(&name).and_then(|v| v.as_i64()).unwrap_or(0); graphics.insert(name, json!(n + 1));
    }
    let mut layers: Vec<String> = pads.iter().filter_map(|p| p["layers"][0].as_str().map(str::to_string)).chain(graphics.keys().cloned()).collect();
    layers.sort(); layers.dedup();
    // the courtyard: the extent of the courtyard layer's graphics (a Courtyard Top layer, else Mechanical 15 as this
    // bridge's footprints and IPC wizards put it), else of everything but the pads; the library footprint itself has no
    // extent in Altium
    let ext = |rows: Vec<&Value>| -> Option<[f64; 4]> {
        let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
        for o in rows { if o.as_array().map(|a| a.len() >= 6).unwrap_or(false) { b[0] = b[0].min(mm(&o[2])); b[1] = b[1].min(mm(&o[3])); b[2] = b[2].max(mm(&o[4])); b[3] = b[3].max(mm(&o[5])); } }
        if b[0] <= b[2] { Some(b) } else { None }
    };
    let cy = crate::fplayers::courtyard_layers(&lt);
    let court = ext(others.iter().filter(|o| o[1].as_i64().is_some_and(|i| cy.contains(&i))).collect()).or_else(|| ext(others.iter().collect()));
    let b = court.map(|c| json!(c)).unwrap_or(d["box"].clone());
    let texts: Vec<Value> = others.iter().filter(|o| o[6].is_string()).map(|o| json!({"text": o[6], "layer": crate::fplayers::display_name(o[1].as_i64().unwrap_or(0), &lt),
        "boxMm": [mm(&o[2]), mm(&o[3]), mm(&o[4]), mm(&o[5])]})).collect();
    let layer_details = crate::fplayers::details(&lt, |id| others.iter().filter(|o| o[1].as_i64() == Some(id)).count());
    let models: Vec<Value> = d["bodies"].as_array().cloned().unwrap_or_default().iter().map(|x| {
        let mut m = json!({"path": x["model"], "heightMm": mm(&x["overallHeight"]), "standoffMm": mm(&x["standoff"])});
        if let Some(l) = x["layer"].as_i64() { m["layer"] = json!(crate::fplayers::display_name(l, &lt)); }
        m
    }).collect();
    json!({"success": true, "name": d["name"], "library": lib, "description": d["description"], "pads": pads, "layers": layers, "courtyardMm": if court.is_some() { b.clone() } else { json!([mm(&b[0]), mm(&b[1]), mm(&b[2]), mm(&b[3])]) },
        "graphics": graphics, "graphicsLayerIds": by_id, "layerDetails": layer_details, "texts": texts, "attributes": {"mount": if pads.iter().any(|p| p["type"] == "pth") { "through_hole" } else { "smd" }},
        "properties": {"description": d["description"], "heightMm": mm(&d["height"])}, "models": models,
        "_hint": "Positions from the footprint's origin, mm. Graphics are counted per layer by the name Altium shows (typed layers of AD 24+ as Top Courtyard, Top Assembly); layerDetails gives each layer's id and kind, texts the strings (the .Designator). courtyardMm is the extent of the courtyard layer's graphics, else of all graphics. altium_footprint_primitives reads a placed part."})
}

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

    #[test]
    fn footprint_edits_become_agent_operations_in_order() {
        let args = json!({"pads": [{"number": "1", "set": {"sizeMm": [1.0, 0.6], "at": [-2.7, 1.905]}}, {"number": "8", "delete": true}],
            "addPads": [{"number": "9", "at": [0, 0], "sizeMm": [2, 2], "shape": "rect"}, {"number": "MH", "at": [3, 3], "sizeMm": [1, 1], "drillMm": 1.0, "type": "npth"}],
            "renumber": {"map": {"1": "2", "2": "1"}},
            "graphics": [{"layer": "F.SilkS", "mode": "replace", "widthMm": 0.15, "shapes": [{"type": "rect", "start": [-1, -1], "end": [1, 1]}]}],
            "metadata": {"description": "edited", "tags": "x"}, "models": {"mode": "delete"}});
        let (ops, na) = fp_ops(&args, &[]).unwrap();
        assert_eq!(ops[0], "PS|1|size|1|0.6");
        assert_eq!(ops[1], "PS|1|at|-2.7|1.905");
        assert_eq!(ops[2], "PD|8");
        assert_eq!(ops[3], "PA|9|0|0|2|2|rect|0|top|0|");
        assert_eq!(ops[4], "PA|MH|3|3|1|1|rect|1|multi|0|npth");
        // 1 and 2 swap through temporary names
        assert_eq!(&ops[5..9], &["PS|1|number|__adom0", "PS|2|number|__adom1", "PS|__adom0|number|2", "PS|__adom1|number|1"]);
        assert_eq!(ops[9], "GD|33");
        assert_eq!(ops.iter().filter(|o| o.starts_with("GL|33|")).count(), 4);
        assert!(ops.contains(&"MD|edited".to_string()) && ops.last() == Some(&"BD".to_string()));
        assert_eq!(na, vec!["metadata.tags".to_string()]);
        let (seq, _) = fp_ops(&json!({"renumber": {"sequential": true, "start": 1}}), &["A".into(), "B".into()]).unwrap();
        assert_eq!(seq, ["PS|A|number|__adom0", "PS|B|number|__adom1", "PS|__adom0|number|1", "PS|__adom1|number|2"]);
        assert!(fp_ops(&json!({"graphics": [{"layer": "Dwgs.User"}]}), &[]).is_err());
        // #42: a replace with its shapes under another key cleared the layer and drew nothing
        let e = fp_ops(&json!({"graphics": [{"layer": "F.SilkS", "mode": "replace", "lines": [[0, 0, 1, 1]]}]}), &[]).unwrap_err();
        assert!(e["error"].as_str().unwrap().contains("lines"), "{e}");
        assert!(fp_ops(&json!({"graphics": [{"layer": "F.SilkS", "mode": "delete"}]}), &[]).is_ok(), "delete needs no shapes");
    }


    #[test]
    fn graphics_layers_follow_the_layer_map_and_shapes_keep_their_width() {
        // #43: with a map, F.Fab is the map's fab layer (B. the bottom of its pair); without one, Mechanical 13
        let map = vec![("fab".to_string(), "k1".to_string()), ("courtyard".to_string(), "k11".to_string())];
        assert_eq!(fp_graphics_layer("F.Fab", &map).as_deref(), Some("k1"));
        assert_eq!(fp_graphics_layer("B.Fab", &map).as_deref(), Some("k2"));
        assert_eq!(fp_graphics_layer("B.CrtYd", &map).as_deref(), Some("k12"));
        assert_eq!(fp_graphics_layer("F.Fab", &[]).as_deref(), Some("69"));
        assert_eq!(fp_graphics_layer("F.SilkS", &map).as_deref(), Some("33"));
        assert_eq!(fp_graphics_layer("AssemblyTop", &[]).as_deref(), Some("k1"));
        assert_eq!(fp_graphics_layer("Mechanical 13", &[]).as_deref(), Some("69"));
        assert_eq!(fp_graphics_layer("Mechanical20", &[]).as_deref(), Some("m20"));
        assert_eq!(fp_graphics_layer("L67108881", &[]).as_deref(), Some("67108881"));
        let (ops, _) = fp_ops(&json!({"graphics": [{"layer": "F.SilkS", "widthMm": 0.15, "shapes": [
            {"type": "line", "start": [0, 0], "end": [1, 0], "widthMm": 0.3}, {"type": "line", "start": [0, 1], "end": [1, 1]},
            {"type": "circle", "center": [0, 0], "radius": 0.2, "filled": true}]}]}), &[]).unwrap();
        assert_eq!(ops, ["GL|33|0|0|1|0|0.3", "GL|33|0|1|1|1|0.15", "GA|33|0|0|0.1|0.2|0|360"]);
    }

    #[test]
    fn kinds_by_extension() {
        assert_eq!(kind_of("a.PrjPcb"), "project");
        assert_eq!(kind_of("C:/x/Main.SchDoc"), "schematic");
        assert_eq!(kind_of("b.PcbDoc"), "board");
        assert_eq!(kind_of("l.PcbLib"), "library");
        assert_eq!(kind_of("n.txt"), "other");
    }

    #[test]
    fn renaming_takes_the_documents_named_after_the_project() {
        let docs = vec!["C:/p/lane.SchDoc".to_string(), "C:/p/LaneSub.SchDoc".to_string(), "C:/p/lane.PcbDoc".to_string(), "C:/p/lane.Manufacturing.OutJob".to_string()];
        let plan = rename_plan("lane", "road", &docs);
        assert_eq!(plan, vec![("lane.SchDoc".into(), "road.SchDoc".into()), ("lane.PcbDoc".into(), "road.PcbDoc".into()), ("lane.Manufacturing.OutJob".into(), "road.Manufacturing.OutJob".into())]);
    }

    #[test]
    fn a_new_project_lists_its_sheet_board_and_variables() {
        let mut v = serde_json::Map::new();
        v.insert("REV".into(), json!("A"));
        let t = project_text("Buck", &v);
        assert!(t.contains("DocumentPath=Buck.SchDoc") && t.contains("DocumentPath=Buck.PcbDoc"));
        assert_eq!(text_variables(&t).get("REV"), Some(&json!("A")));
    }
}

/// The library part's pieces: its symbol library, the footprint name and the footprint library. From a .SchLib, the
/// footprint is the symbol's PCB model, found in a .PcbLib beside it (or the ones named).
fn part_pieces(args: &Value) -> Result<(String, String, Option<String>, Option<String>), Value> {
    let Some(part) = support::s(args, "part") else { return Err(bad("part (the symbol's name) is required")) };
    let Some(lib) = support::s(args, "libraryPath").filter(|l| l.to_lowercase().ends_with(".schlib")) else {
        return Err(bad("libraryPath (the .SchLib that holds the part) is required: Altium has no global library table to resolve a library id"));
    };
    let streams = std::fs::read(&lib).ok().and_then(|b| crate::schdoc::cfb_streams(&b).ok());
    let Some(st) = streams else { return Err(json!({"success": false, "errorCode": "library_unreadable", "error": format!("{lib} could not be read")})) };
    if !st.iter().any(|(n, d)| n.ends_with("Data") && crate::schdoc::records(d).iter().any(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1") && r.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(&part)).unwrap_or(false))) {
        return Err(json!({"success": false, "errorCode": "symbol_not_found", "error": format!("{part} is not in {lib}")}));
    }
    let fp = support::s(args, "footprint").or_else(|| crate::render::symbol_footprint(&st, &part));
    let dir = Path::new(&lib).parent().unwrap_or(Path::new(".")).to_path_buf();
    let fp_lib = support::s(args, "footprintLibrary").or_else(|| fp.as_ref().and_then(|f| crate::render::pcblib_with(&dir, f)));
    Ok((part, lib, fp, fp_lib))
}

/// A footprint graphics layer by the standard's name, as the agent's layer field: an Altium layer id, or a layer-map
/// code (`k1` a typed layer, made if the library has none). F.Fab and F.CrtYd follow the library's layer map (its
/// `fab` and `courtyard` keys, the B. side taking the bottom layer of a typed pair), as the footprint builders do;
/// without a map they stay on Mechanical 13 and 15, where this bridge builds them. A layer kind's name (AssemblyTop,
/// CourtyardTop) or a layer's name works too (#43: F.Fab drew on Mechanical 13 though the map said Top Assembly).
fn fp_graphics_layer(l: &str, map: &[(String, String)]) -> Option<String> {
    let mapped = |key: &str, bottom: bool| map.iter().find(|(k, _)| k == key).map(|(_, c)| {
        match c.strip_prefix('k').and_then(|k| k.parse::<i64>().ok()).and_then(crate::layermap::pair_of) {
            Some((_, top, bot)) if bottom => format!("k{}", if c == &format!("k{top}") { bot } else { top }),
            _ => c.clone(),
        }
    });
    let fixed = match l {
        "F.SilkS" | "F.Silkscreen" => Some(33), "B.SilkS" | "B.Silkscreen" => Some(34), "F.Paste" => Some(35), "B.Paste" => Some(36), "F.Mask" => Some(37), "B.Mask" => Some(38),
        "F.Cu" => Some(1), "B.Cu" => Some(32),
        _ => None,
    };
    if let Some(id) = fixed { return Some(id.to_string()); }
    match l {
        "F.Fab" => return Some(mapped("fab", false).unwrap_or_else(|| "69".into())),
        "B.Fab" => return Some(mapped("fab", true).unwrap_or_else(|| "69".into())),
        "F.CrtYd" | "F.Courtyard" => return Some(mapped("courtyard", false).unwrap_or_else(|| "71".into())),
        "B.CrtYd" | "B.Courtyard" => return Some(mapped("courtyard", true).unwrap_or_else(|| "71".into())),
        _ => {}
    }
    if let Some(n) = l.strip_prefix("Mechanical").and_then(|n| n.trim().parse::<i64>().ok()).filter(|n| (1..=1024).contains(n)) {
        return Some(if n <= 16 { (56 + n).to_string() } else { format!("m{n}") });
    }
    if let Some(id) = l.strip_prefix('L').and_then(|n| n.parse::<i64>().ok()) { return Some(id.to_string()); }
    crate::layermap::encode(&json!(l)).ok()
}

fn xy(v: &Value) -> Option<(f64, f64)> { Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)) }

/// A pad's layer word for the agent: a hole or a pth/npth type is multi-layer.
fn pad_layer_word(p: &Value) -> &'static str {
    let ty = p.get("type").and_then(|v| v.as_str()).unwrap_or("");
    let drill = p.get("drillMm").and_then(|v| v.as_f64()).unwrap_or(0.0);
    let layers: Vec<&str> = p.get("layers").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).collect()).unwrap_or_default();
    if ty == "pth" || ty == "npth" || drill > 0.0 || layers.iter().any(|l| l.starts_with('*')) || (layers.contains(&"F.Cu") && layers.contains(&"B.Cu")) { "multi" }
    else if layers.contains(&"B.Cu") { "bottom" } else { "top" }
}

/// The agent's edit_fp operations for an edit_footprint request, and what was not applied. `pads_now` is the
/// footprint's pad numbers in order (for sequential renumbering).
pub(crate) fn fp_ops(args: &Value, pads_now: &[String]) -> Result<(Vec<String>, Vec<String>), Value> {
    let bad = |m: String| json!({"success": false, "errorCode": "bad_args", "error": m});
    let mut ops = Vec::new();
    let mut not_applied = Vec::new();
    let f = |v: &Value| v.as_f64().unwrap_or(0.0);
    for p in args.get("pads").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let n = p.get("number").map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).ok_or_else(|| bad("pads[].number is required".into()))?;
        if p.get("delete").and_then(|v| v.as_bool()) == Some(true) { ops.push(format!("PD|{n}")); continue; }
        let set = p.get("set").cloned().unwrap_or(json!({}));
        if let Some((w, h)) = set.get("sizeMm").and_then(xy) { ops.push(format!("PS|{n}|size|{w}|{h}")); }
        if let Some((x, y)) = set.get("at").and_then(xy) { ops.push(format!("PS|{n}|at|{x}|{y}")); }
        if let Some(sh) = set.get("shape").and_then(|v| v.as_str()) { ops.push(format!("PS|{n}|shape|{}", if sh == "circle" || sh == "oval" { "round" } else { sh })); }
        if let Some(d) = set.get("drillMm").and_then(|v| v.as_f64()) { ops.push(format!("PS|{n}|drill|{d}")); }
        if let Some(r) = set.get("rotation").and_then(|v| v.as_f64()) { ops.push(format!("PS|{n}|rotation|{r}")); }
        if let Some(t) = set.get("type").and_then(|v| v.as_str()) { ops.push(format!("PS|{n}|type|{t}")); }
        else if set.get("layers").is_some() { ops.push(format!("PS|{n}|layer|{}", pad_layer_word(&set))); }
        if let Some(nn) = set.get("newNumber").and_then(|v| v.as_str()) { ops.push(format!("PS|{n}|number|{nn}")); }
    }
    for p in args.get("addPads").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let n = p.get("number").map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).ok_or_else(|| bad("addPads[].number is required".into()))?;
        let (x, y) = p.get("at").and_then(xy).ok_or_else(|| bad(format!("addPads {n}: at [x, y] is required")))?;
        let (w, h) = p.get("sizeMm").and_then(xy).ok_or_else(|| bad(format!("addPads {n}: sizeMm [w, h] is required")))?;
        let sh = p.get("shape").and_then(|v| v.as_str()).unwrap_or("rect");
        ops.push(format!("PA|{n}|{x}|{y}|{w}|{h}|{}|{}|{}|{}|{}", if sh == "circle" || sh == "oval" { "round" } else { sh },
            p.get("drillMm").and_then(|v| v.as_f64()).unwrap_or(0.0), pad_layer_word(&p), p.get("rotation").and_then(|v| v.as_f64()).unwrap_or(0.0),
            p.get("type").and_then(|v| v.as_str()).unwrap_or("")));
    }
    if let Some(r) = args.get("renumber") {
        // two steps through temporary names, so 1->2 and 2->1 never meet
        let map: Vec<(String, String)> = if r.get("sequential").and_then(|v| v.as_bool()) == Some(true) {
            let start = r.get("start").and_then(|v| v.as_i64()).unwrap_or(1);
            pads_now.iter().enumerate().map(|(i, p)| (p.clone(), (start + i as i64).to_string())).collect()
        } else {
            r.get("map").and_then(|v| v.as_object()).map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string()))).collect()).unwrap_or_default()
        };
        for (i, (a, _)) in map.iter().enumerate() { ops.push(format!("PS|{a}|number|__adom{i}")); }
        for (i, (_, b)) in map.iter().enumerate() { ops.push(format!("PS|__adom{i}|number|{b}")); }
    }
    let lib = support::s(args, "libraryPath");
    let map: Vec<(String, String)> = if args.get("graphics").is_some() {
        crate::layermap_verb::effective(args, lib.as_deref()).entries.iter().map(|(k, _, c, _)| (k.clone(), c.clone())).collect()
    } else { Vec::new() };
    for g in args.get("graphics").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let ln = g.get("layer").and_then(|v| v.as_str()).unwrap_or("");
        let lid = fp_graphics_layer(ln, &map).ok_or_else(|| bad(format!("graphics layer {ln}: F.SilkS, F.Fab, F.CrtYd, F.Mask, F.Paste (or B.), Mechanical<n>, L<id>, or a layer kind (AssemblyTop, CourtyardTop, ...)")))?;
        let mode = g.get("mode").and_then(|v| v.as_str()).unwrap_or("append");
        if !["append", "replace", "delete"].contains(&mode) { return Err(bad(format!("graphics mode {mode}: append, replace or delete"))); }
        // shapes go in `shapes`: an entry with none drew nothing, and replace then only cleared the layer (#42)
        let unknown: Vec<String> = g.as_object().map(|o| o.keys().filter(|k| !["layer", "mode", "widthMm", "shapes"].contains(&k.as_str())).cloned().collect()).unwrap_or_default();
        let has_shapes = g.get("shapes").and_then(|v| v.as_array()).is_some_and(|a| !a.is_empty());
        if mode != "delete" && !has_shapes {
            return Err(bad(format!("graphics on {ln} has no shapes{}: give shapes: [{{type: line|arc|rect|circle|poly, ...}}] (mode delete clears the layer); nothing was changed",
                if unknown.is_empty() { String::new() } else { format!(" (not read: {})", unknown.join(", ")) })));
        }
        if !unknown.is_empty() { return Err(bad(format!("graphics on {ln}: {} not read; shapes go in shapes: [{{type, ...}}]; nothing was changed", unknown.join(", ")))); }
        if mode == "replace" || mode == "delete" { ops.push(format!("GD|{lid}")); }
        if mode == "delete" { continue; }
        let gw = g.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(0.12);
        for sh in g.get("shapes").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
            // a shape's own widthMm beats the entry's (#43: it was ignored)
            let w = sh.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(gw);
            let line = |a: (f64, f64), b: (f64, f64)| format!("GL|{lid}|{}|{}|{}|{}|{w}", a.0, a.1, b.0, b.1);
            match sh.get("type").and_then(|v| v.as_str()).unwrap_or("") {
                "line" => ops.push(line(sh.get("start").and_then(xy).ok_or_else(|| bad("a line needs start".into()))?, sh.get("end").and_then(xy).ok_or_else(|| bad("a line needs end".into()))?)),
                "rect" => {
                    let (a, b) = (sh.get("start").and_then(xy).ok_or_else(|| bad("a rect needs start".into()))?, sh.get("end").and_then(xy).ok_or_else(|| bad("a rect needs end".into()))?);
                    for (p, q) in [(a, (b.0, a.1)), ((b.0, a.1), b), (b, (a.0, b.1)), ((a.0, b.1), a)] { ops.push(line(p, q)); }
                }
                "poly" => {
                    let pts: Vec<(f64, f64)> = sh.get("points").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(xy).collect()).unwrap_or_default();
                    for i in 0..pts.len() { if pts.len() > 1 { ops.push(line(pts[i], pts[(i + 1) % pts.len()])); } }
                }
                "circle" => {
                    let c = sh.get("center").and_then(xy).ok_or_else(|| bad("a circle needs center".into()))?;
                    let r = f(sh.get("radius").unwrap_or(&json!(0)));
                    // filled: a dot, drawn as a ring of half the radius as wide as the radius
                    if sh.get("filled").and_then(|v| v.as_bool()) == Some(true) { ops.push(format!("GA|{lid}|{}|{}|{}|{}|0|360", c.0, c.1, r / 2.0, r)); }
                    else { ops.push(format!("GA|{lid}|{}|{}|{}|{w}|0|360", c.0, c.1, r)); }
                }
                "arc" => {
                    let c = sh.get("center").and_then(xy).ok_or_else(|| bad("an arc needs center, radius, startAngle, endAngle (degrees, counter-clockwise)".into()))?;
                    ops.push(format!("GA|{lid}|{}|{}|{}|{w}|{}|{}", c.0, c.1, f(sh.get("radius").unwrap_or(&json!(0))), f(sh.get("startAngle").unwrap_or(&json!(0))), f(sh.get("endAngle").unwrap_or(&json!(360)))));
                }
                other => return Err(bad(format!("graphics shape type {other}: line, arc, rect, circle or poly"))),
            }
        }
    }
    if let Some(m) = args.get("metadata") {
        if let Some(d) = m.get("description").and_then(|v| v.as_str()) { ops.push(format!("MD|{}", d.replace(['|', '\n'], " "))); }
        // an Altium footprint carries no tags or BOM flags: those live on the component (its kind) and the symbol
        if m.get("tags").is_some() { not_applied.push("metadata.tags".to_string()); }
        if m.get("attributes").is_some() { not_applied.push("metadata.attributes (set them on the placed part: edit_parts)".to_string()); }
    }
    if args.pointer("/models/mode").and_then(|v| v.as_str()) == Some("delete") { ops.push("BD".into()); }
    Ok((ops, not_applied))
}

/// altium_edit_footprint {libraryPath, name, pads?, addPads?, renumber?, graphics?, metadata?, models?, dryRun?}
pub fn edit_footprint(args: &Value) -> Value {
    let (Some(lib), Some(name)) = (support::s(args, "libraryPath"), support::s(args, "name")) else { return bad("libraryPath (.PcbLib) and name are required") };
    let dry = args.get("dryRun").and_then(|v| v.as_bool()) == Some(true);
    if let Some(g) = support::need_licensed() { return g; }
    if let Some(e) = support::must_open(&lib, 60) { return e; }
    // the pads as they are, for sequential renumbering and to refuse an unknown footprint before any change
    let now = read_footprint(&json!({"libraryPath": lib, "name": name}));
    if now.get("success").and_then(|v| v.as_bool()) != Some(true) { return now; }
    let pads_now: Vec<String> = now["pads"].as_array().cloned().unwrap_or_default().iter().filter_map(|p| p["number"].as_str().map(str::to_string)).collect();
    let (ops, mut not_applied) = match fp_ops(args, &pads_now) { Ok(x) => x, Err(e) => return e };
    let models = args.get("models").cloned().unwrap_or(Value::Null);
    let model_list: Vec<Value> = models.get("list").and_then(|v| v.as_array()).cloned().unwrap_or_default();
    let model_mode = models.get("mode").and_then(|v| v.as_str()).unwrap_or("");
    for m in &model_list {
        for k in ["offset", "scale", "rotate"] { if m.get(k).is_some() { not_applied.push(format!("models.{k} (the body is aligned onto the pads)")); } }
    }
    not_applied.dedup();
    if ops.is_empty() && model_list.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no edits in the request"}); }
    if dry {
        return json!({"success": true, "dryRun": true, "operations": ops, "models": model_list, "notApplied": not_applied,
            "_hint": "Nothing changed. The operations run in this order: pads, addPads, renumber, graphics, metadata, models."});
    }
    let mut changes: Vec<Value> = Vec::new();
    let mut failed = 0;
    if !ops.is_empty() {
        let d = match agent_data(&agent::call("edit_fp", &[("name", name.clone()), ("path", lib.replace('/', "\\"))], Some(&ops.join("\n")), Duration::from_secs(120))) { Ok(d) => d, Err(e) => return e };
        failed += d["failed"].as_i64().unwrap_or(0);
        changes.extend(d["results"].as_array().cloned().unwrap_or_default());
    }
    for (i, m) in model_list.iter().enumerate() {
        let Some(step) = m.get("path").and_then(|v| v.as_str()) else { continue };
        let keep = model_mode == "append" || i > 0;
        let r = crate::library::add_body(&json!({"libraryPath": lib, "footprintName": name, "step": step, "keepExisting": keep}));
        let ok = r.get("success").and_then(|v| v.as_bool()) != Some(false);
        if !ok { failed += 1; }
        changes.push(json!(if ok { format!("ok:model {step}") } else { format!("err:model {step}: {}", r.get("error").and_then(|v| v.as_str()).unwrap_or("not added")) }));
    }
    let _ = support::must_open(&lib, 60);
    let saved = crate::surfaces::save(&json!({"filePath": lib}));
    let after = read_footprint(&json!({"libraryPath": lib, "name": name}));
    json!({"success": failed == 0, "changes": changes, "failed": failed, "notApplied": not_applied, "saved": saved.get("success"),
        "footprint": {"pads": after["pads"].as_array().map(|a| a.len()), "graphics": after["graphics"], "courtyardMm": after["courtyardMm"]},
        "_hint": "changes[] answers each operation in order (err: ones did not land). Boards that already use the footprint keep their own copy: update them with altium_swap_footprint."})
}

/// altium_export_library_part {part, libraryPath, footprint?, footprintLibrary?, what?, outputDir?}
pub fn export_library_part(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let (part, lib, fp, fp_lib) = match part_pieces(args) { Ok(x) => x, Err(e) => return e };
    let what: Vec<String> = args.get("what").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or(vec!["symbol".into(), "footprint".into(), "model".into()]);
    let out = support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(&lib).parent().unwrap_or(Path::new(".")).join("exports").join(&part));
    if let Err(e) = std::fs::create_dir_all(&out) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    let mut exports = serde_json::Map::new();
    let mut missing = Vec::new();
    if what.iter().any(|w| w == "symbol") {
        let dst = out.join(format!("{part}.SchLib"));
        let _ = std::fs::remove_file(&dst);
        let ok = agent_data(&agent::call("ensure_lib", &[("kind", "SCHLIB".into()), ("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(90)))
            .and_then(|_| agent_data(&agent::call("xcopy_symbol", &[("fromLib", lib.clone()), ("from", part.clone())], None, Duration::from_secs(90))));
        match ok {
            Ok(_) => { let _ = crate::surfaces::save(&json!({"filePath": dst.to_string_lossy()})); let _ = agent::call("close_document", &[("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(30)); exports.insert("symbol".into(), json!(dst.to_string_lossy())); }
            Err(e) => missing.push(json!({"what": "symbol", "why": e.get("error").cloned().unwrap_or(e)})),
        }
    }
    if what.iter().any(|w| w == "footprint") {
        match (&fp, &fp_lib) {
            (Some(f), Some(l)) => {
                let dst = out.join(format!("{f}.PcbLib"));
                let _ = std::fs::remove_file(&dst);
                let ok = agent_data(&agent::call("ensure_lib", &[("kind", "PCBLIB".into()), ("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(90)))
                    .and_then(|_| agent_data(&agent::call("xcopy_footprint", &[("fromLib", l.clone()), ("from", f.clone()), ("to", f.clone())], None, Duration::from_secs(90))));
                match ok {
                    Ok(_) => { let _ = crate::surfaces::save(&json!({"filePath": dst.to_string_lossy()})); let _ = agent::call("close_document", &[("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(30)); exports.insert("footprint".into(), json!(dst.to_string_lossy())); }
                    Err(e) => missing.push(json!({"what": "footprint", "why": e.get("error").cloned().unwrap_or(e)})),
                }
            }
            _ => missing.push(json!({"what": "footprint", "why": "no footprint: the symbol has no PCB model, or no .PcbLib beside the library holds it (name footprint and footprintLibrary)"})),
        }
    }
    if what.iter().any(|w| w == "model") {
        let model = match (&fp, &fp_lib) {
            (Some(f), Some(l)) => read_footprint(&json!({"libraryPath": l, "name": f}))["models"].as_array().and_then(|m| m.first()).and_then(|m| m["path"].as_str().map(str::to_string)),
            _ => None,
        };
        match model.filter(|m| Path::new(m).is_file()) {
            Some(m) => { let dst = out.join(Path::new(&m).file_name().unwrap_or_default()); match std::fs::copy(&m, &dst) { Ok(_) => { exports.insert("model".into(), json!(dst.to_string_lossy())); } Err(e) => missing.push(json!({"what": "model", "why": e.to_string()})) } }
            None => missing.push(json!({"what": "model", "why": "no 3D model file: the footprint has no body, or its STEP is embedded in the library and its source file is gone (export the board with altium_export_step for a STEP)"})),
        }
    }
    // a footprint with no body has no model to give: that fails the export only when the caller asked for the model
    let asked_model = args.get("what").is_some();
    let ok = missing.iter().all(|m| m["what"] == "model" && !asked_model);
    json!({"success": ok, "complete": missing.is_empty(), "exports": exports, "missing": missing, "outputDir": out.to_string_lossy(), "footprint": fp,
        "_hint": "Each library holds only this part. The footprint library carries the 3D body too (Altium embeds it); model is the STEP file the body came from, when it still exists."})
}

/// altium_create_part_project {part, libraryPath, footprint?, footprintLibrary?, projectName?, outputDir?, overwrite?}
pub fn create_part_project(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let (part, lib, fp, fp_lib) = match part_pieces(args) { Ok(x) => x, Err(e) => return e };
    let (Some(fp), Some(fp_lib)) = (fp, fp_lib) else { return json!({"success": false, "errorCode": "no_footprint", "error": "the part needs a footprint: name footprint and footprintLibrary, or give the symbol a PCB model"}) };
    let name = support::s(args, "projectName").unwrap_or_else(|| format!("{}-demo", part.replace([' ', '/', '\\'], "_")));
    let parent = support::s(args, "outputDir").unwrap_or_else(|| Path::new(&lib).parent().unwrap_or(Path::new(".")).join("part-projects").to_string_lossy().to_string());
    let dir = Path::new(&parent).join(&name);
    if dir.exists() {
        if args.get("overwrite").and_then(|v| v.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "exists", "error": format!("{} exists: overwrite:true replaces it", dir.display())}); }
        // only the documents of the project being replaced: anything else open may be someone's work
        let _ = close_all_documents(&json!({"under": dir.to_string_lossy(), "discardUnsaved": true}));
        if let Err(e) = std::fs::remove_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    }
    let _ = std::fs::create_dir_all(&parent);
    let pc = project_create(&json!({"parentDir": parent, "name": name, "title": format!("{part} demo")}));
    if pc.get("success").and_then(|b| b.as_bool()) != Some(true) { return pc; }
    let prj = st(&pc["project"]);
    let sch = dir.join(format!("{name}.SchDoc")).to_string_lossy().to_string();
    let pcb = dir.join(format!("{name}.PcbDoc")).to_string_lossy().to_string();
    let mut steps = vec![json!({"project": prj})];
    // the libraries join the project, so the change order finds the footprint
    for l in [&lib, &fp_lib] { if let Err(e) = crate::hier::add_to_project(&prj, l) { return e; } }
    let _ = crate::surfaces::open_document(&json!({"filePath": prj}));
    let placed = crate::sch::place_part(&json!({"sheet": sch, "library": lib, "symbol": part, "designator": "U1", "x": 4000, "y": 4000, "footprint": fp, "pcbLib": fp_lib}));
    steps.push(json!({"symbolPlaced": placed.get("success"), "detail": placed.get("error"), "placement": placed.get("placement"), "models": placed.get("models")}));
    if placed.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "place_failed", "error": "the symbol could not be placed", "reply": placed, "project": prj}); }
    let up = crate::sch::update_pcb(&json!({"projectPath": prj, "execute": true}));
    steps.push(json!({"updatePcb": up.get("executed"), "detail": up.get("error")}));
    // a board just big enough: the part with a 5 mm margin
    if crate::support::must_open(&pcb, 60).is_none() {
        let s2 = crate::routing::routing_state(&json!({}));
        let pads = s2["pads"].as_array().cloned().unwrap_or_default();
        if !pads.is_empty() {
            let f = |p: &Value, k: &str| p[k].as_f64().unwrap_or(0.0);
            let (x0, y0, x1, y1) = pads.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(f(p, "x") - f(p, "sizeX")), b.1.min(f(p, "y") - f(p, "sizeY")), b.2.max(f(p, "x") + f(p, "sizeX")), b.3.max(f(p, "y") + f(p, "sizeY"))));
            // the change order drops a new part beside Altium's default board: it moves so the board's corner is the origin
            let m = crate::routing::move_parts(&json!({"parts": [{"ref": "U1", "dx": r3(5.0 - x0), "dy": r3(5.0 - y0)}]}));
            steps.push(json!({"moved": m.get("success")}));
            let r = crate::routing::set_outline(&json!({"outline": {"rect": [0.0, 0.0, r3(x1 - x0 + 10.0), r3(y1 - y0 + 10.0)], "cornerRadius": 1.0}}));
            steps.push(json!({"outline": r.get("success")}));
        }
        let _ = crate::surfaces::save(&json!({"filePath": pcb}));
    }
    json!({"success": up.get("success").and_then(|b| b.as_bool()) != Some(false), "project": prj, "schematic": sch, "board": pcb, "steps": steps,
        "_hint": "A real project: the symbol on the sheet as U1, the footprint on the board by Altium's own change order, a board 5 mm round the part. Show it with altium_show_schematic, altium_show_2d_board and altium_show_3d_board."})
}