main
Colby Knox 0.2.122 source: add_dimensions replace, format echo and style read-back 93ab59b
//! altium_add_dimensions (#43): anchored linear dimensions on a library footprint, whose ends are bound to the
//! footprint's pads and assembly-outline corners and follow them when they move. Altium will not anchor a dimension a
//! script makes (its reference setters do not stick), so this takes the route the reporter proved (2026-12-02): the
//! footprint is copied onto a work board saved as Altium's ASCII PcbDoc, the dimensions are written into that file
//! pointing at those primitives, Altium opens it and validates them, and the footprint is rebuilt from the work board's
//! own instances (agent dim_work / dim_apply). The library is then saved, closed and reopened, and every dimension's
//! references are read back: `validAfterReopen` is the proof.
use serde_json::{json, Map, Value};

const MIL_PER_MM: f64 = 1.0 / 0.0254;

/// A primitive of the work board a dimension can be bound to.
#[derive(Clone, Debug, PartialEq)]
pub struct Anchor { pub kind: &'static str, pub prim: i64, pub anchor: i64, pub x: f64, pub y: f64 }

/// The work board's pads and tracks (mil, from the board's origin), its dimension count and its layer names.
#[derive(Default, Debug)]
pub struct Work { pub pads: Vec<(i64, String, f64, f64)>, pub tracks: Vec<(i64, String, f64, f64, f64, f64)>, pub dims: usize }

fn fields(l: &str) -> Map<String, Value> {
    let mut m = Map::new();
    for part in l.split('|') {
        if let Some((k, v)) = part.split_once('=') { m.entry(k.to_string()).or_insert(json!(v)); }
    }
    m
}

fn mil(v: Option<&Value>) -> f64 { v.and_then(|v| v.as_str()).map(|s| s.trim().trim_end_matches("mil")).and_then(|s| s.trim().parse().ok()).unwrap_or(0.0) }

/// Reads the work board's ASCII text.
pub fn parse_work(text: &str) -> Work {
    let mut w = Work::default();
    for l in text.lines() {
        if l.starts_with("|RECORD=Pad|") {
            let f = fields(l);
            w.pads.push((f["INDEXFORSAVE"].as_str().and_then(|s| s.parse().ok()).unwrap_or(-1), f.get("NAME").and_then(|v| v.as_str()).unwrap_or("").to_string(), mil(f.get("X")), mil(f.get("Y"))));
        } else if l.starts_with("|RECORD=Track|") {
            let f = fields(l);
            // a layer above Mechanical 16 is in LAYER_V7; LAYER holds the old name, capped at MECHANICAL16
            let layer = f.get("LAYER_V7").or_else(|| f.get("LAYER")).and_then(|v| v.as_str()).unwrap_or("").to_string();
            w.tracks.push((f["INDEXFORSAVE"].as_str().and_then(|s| s.parse().ok()).unwrap_or(-1), layer,
                mil(f.get("X1")), mil(f.get("Y1")), mil(f.get("X2")), mil(f.get("Y2"))));
        } else if l.starts_with("|RECORD=Embedded|") && l.contains("DIMENSIONKIND=") {
            w.dims += 1;
        }
    }
    w
}

/// The bounding corners (TL, TR, BR, BL) of a layer's tracks.
fn corners(w: &Work, layer: &str) -> Option<[(f64, f64); 4]> {
    let t: Vec<_> = w.tracks.iter().filter(|t| t.1.eq_ignore_ascii_case(layer)).collect();
    if t.is_empty() { return None; }
    let xs = t.iter().flat_map(|t| [t.2, t.4]);
    let ys = t.iter().flat_map(|t| [t.3, t.5]);
    let (x0, x1) = xs.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));
    let (y0, y1) = ys.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));
    Some([(x0, y1), (x1, y1), (x1, y0), (x0, y0)])
}

/// A track end at (x, y) mil: (index, anchor 1 for X1/Y1 or 2 for X2/Y2), on `layer` when given.
fn track_end(w: &Work, x: f64, y: f64, layer: Option<&str>) -> Option<(i64, i64)> {
    let near = |a: f64, b: f64| (a - b).abs() < 0.02;
    w.tracks.iter().filter(|t| layer.is_none_or(|l| t.1.eq_ignore_ascii_case(l))).find_map(|t| {
        if near(t.2, x) && near(t.3, y) { Some((t.0, 1)) } else if near(t.4, x) && near(t.5, y) { Some((t.0, 2)) } else { None }
    })
}

/// One end of a dimension: a pad's number ("1"), an assembly-outline corner ("TL", "TR", "BR", "BL", or "corner:TL"),
/// or a point {x, y} (mm, from the footprint's origin) where a track ends.
pub fn resolve(w: &Work, v: &Value, fab_layer: &str) -> Result<Anchor, String> {
    if let Some(o) = v.as_object() {
        let (x, y) = (o.get("x").and_then(|v| v.as_f64()).ok_or("a point anchor is {x, y} in mm")? * MIL_PER_MM, o.get("y").and_then(|v| v.as_f64()).ok_or("a point anchor is {x, y} in mm")? * MIL_PER_MM);
        if let Some((i, a)) = track_end(w, x, y, None) { return Ok(Anchor { kind: "Track", prim: i, anchor: a, x, y }); }
        if let Some(p) = w.pads.iter().find(|p| (p.2 - x).abs() < 0.02 && (p.3 - y).abs() < 0.02) { return Ok(Anchor { kind: "Pad", prim: p.0, anchor: 1, x: p.2, y: p.3 }); }
        return Err(format!("no track end or pad centre at ({:.4}, {:.4}) mm", x / MIL_PER_MM, y / MIL_PER_MM));
    }
    let s = v.as_str().map(str::to_string).or_else(|| v.as_i64().map(|n| n.to_string())).ok_or("an anchor is a pad number, a corner (TL, TR, BR, BL) or {x, y}")?;
    let c = s.trim().trim_start_matches("corner:").to_ascii_uppercase();
    if let Some(k) = ["TL", "TR", "BR", "BL"].iter().position(|n| *n == c) {
        let cs = corners(w, fab_layer).ok_or_else(|| format!("{s}: the footprint has no outline on its assembly layer ({fab_layer}) to take a corner from"))?;
        let (x, y) = cs[k];
        let (i, a) = track_end(w, x, y, Some(fab_layer)).ok_or_else(|| format!("{s}: no outline line ends at that corner (a chamfered corner has none: build the footprint with fabOutline: \"edges\")"))?;
        return Ok(Anchor { kind: "Track", prim: i, anchor: a, x, y });
    }
    let p = w.pads.iter().find(|p| p.1 == s.trim()).ok_or_else(|| format!("{s}: no pad of that number, and not a corner (TL, TR, BR, BL)"))?;
    Ok(Anchor { kind: "Pad", prim: p.0, anchor: 1, x: p.2, y: p.3 })
}

/// How a dimension reads: millimetres to `precision` decimals, or with `units: auto` whole mils when the length is a
/// whole multiple of 5 mil (the reporter's house rule), else millimetres to 2 decimals.
pub fn units_for(length_mil: f64, units: &str, precision: Option<i64>) -> (&'static str, i64) {
    match units {
        "mil" => ("Mils", precision.unwrap_or(0)),
        "mm" => ("Millimeters", precision.unwrap_or(2)),
        _ => {
            let r = (length_mil / 5.0).round() * 5.0;
            if (length_mil - r).abs() < 0.01 { ("Mils", precision.unwrap_or(0)) } else { ("Millimeters", precision.unwrap_or(2)) }
        }
    }
}

/// The text a dimension shows for `length_mil` in those units.
pub fn label(length_mil: f64, unit: &str, precision: i64) -> String {
    if unit == "Mils" { format!("{:.*} mil", precision as usize, length_mil) } else { format!("{:.*} mm", precision as usize, length_mil / MIL_PER_MM) }
}

/// The dimension's record in Altium's ASCII PcbDoc, as Altium itself writes a linear dimension (AD 26.11), bound to
/// `a` and `b`.
#[allow(clippy::too_many_arguments)]
pub fn record(index: usize, mech: i64, horizontal: bool, at_mil: f64, a: &Anchor, b: &Anchor, f: &Format, unit: &str, precision: i64) -> String {
    // as Altium writes it: a layer above Mechanical 16 is LAYER_V7 / DIMENSIONLAYER_V7, the plain names capped at 16
    // (a plain MECHANICAL21 was read as Mechanical 16, measured 2026-12-02)
    let (layer, v7, dv7) = if mech > 16 { ("MECHANICAL16".to_string(), format!("|LAYER_V7=MECHANICAL{mech}"), format!("|DIMENSIONLAYER_V7=MECHANICAL{mech}")) }
        else { (format!("MECHANICAL{mech}"), String::new(), String::new()) };
    let m = |v: f64| format!("{v:.4}mil");
    let (x1, y1, x2, y2) = if horizontal { (a.x, at_mil, b.x, at_mil) } else { (at_mil, a.y, at_mil, b.y) };
    let angle = if horizontal { " 0.00000000000000E+0000" } else { " 9.00000000000000E+0001" };
    let oid = |k: &str| if k == "Pad" { 2 } else { 4 };
    let r = |n: usize, x: &Anchor| format!("REFERENCE{n}PRIM={}|REFERENCE{n}OBJECTID={}|REFERENCE{n}OBJECTSTRING={}|REFERENCE{n}POINTX={}|REFERENCE{n}POINTY={}|REFERENCE{n}ANCHOR={}",
        x.prim, oid(x.kind), x.kind, m(x.x), m(x.y), x.anchor);
    format!("|RECORD=Embedded|INDEXFORSAVE={index}|SELECTION=FALSE|LAYER={layer}|LOCKED=FALSE|POLYGONOUTLINE=FALSE|USERROUTED=TRUE|UNIONINDEX=0|NAME=|SELECTION=FALSE|LAYER={layer}|LOCKED=FALSE|POLYGONOUTLINE=FALSE|USERROUTED=TRUE|UNIONINDEX=0{v7}|PRIMITIVELOCK=TRUE{dv7}|DIMENSIONLAYER={layer}|DIMENSIONLOCKED=FALSE|OBJECTID=13|DIMENSIONKIND=1|DRCERROR=FALSE|VINDEXFORSAVE={index}|X1={}|Y1={}|X2={}|Y2={}|TEXTX={}|TEXTY={}|HEIGHT=0mil|LINEWIDTH={}|TEXTHEIGHT={}|TEXTWIDTH={}|FONT=DEFAULT|STYLE=None|TEXTLINEWIDTH={}|TEXTPOSITION=Auto|TEXTGAP={}|TEXTFORMAT=10|TEXTDIMENSIONUNIT={unit}|TEXTPRECISION={precision}|TEXTPREFIX=|TEXTSUFFIX=|TEXTPREFIXUNIV=|TEXTSUFFIXUNIV=|ARROWSIZE={}|ARROWLINEWIDTH={}|ARROWLENGTH={}|ARROWPOSITION=Inside|EXTENSIONOFFSET={}|EXTENSIONLINEWIDTH={}|EXTENSIONPICKGAP={}|REFERENCES_COUNT=2|{}|{}|TEXT1MIRROR=FALSE|USETTFONTS={}|BOLD=FALSE|ITALIC=FALSE|FONTNAME={}|ANGLE={angle}",
        m(x1), m(y1), m(x2), m(y2), m((x1 + x2) / 2.0), m((y1 + y2) / 2.0), m(f.line), m(f.text_height), m(f.line), m(f.text_line), m(f.text_gap),
        m(f.arrow_size), m(f.line), m(f.arrow_length), m(f.extension_offset), m(f.line), m(f.extension_offset), r(0, a), r(1, b),
        if f.font.is_some() { "TRUE" } else { "FALSE" }, f.font.as_deref().unwrap_or("Arial"))
}

/// The look of the dimensions (mil). Defaults are Altium's own for a new linear dimension, scaled to a footprint.
#[derive(Clone, Debug)]
pub struct Format { pub text_height: f64, pub text_line: f64, pub text_gap: f64, pub line: f64, pub arrow_size: f64, pub arrow_length: f64, pub extension_offset: f64, pub units: String, pub precision: Option<i64>, pub font: Option<String> }

/// The `format` keys this verb reads; anything else is reported as ignored.
pub const FORMAT_KEYS: &[&str] = &["textHeightMm", "textLineWidthMm", "textGapMm", "lineWidthMm", "arrowSizeMm", "arrowLengthMm", "extensionOffsetMm", "units", "precision", "font"];

/// What the call's `format` set: each key read with the value used (mm), the defaults that filled the rest, and the keys
/// it did not know (AI Flow passed textHeight and could not tell it was not read, 2026-12-02).
pub fn format_echo(v: Option<&Value>, f: &Format) -> Value {
    let given: Vec<String> = v.and_then(|o| o.as_object()).map(|o| o.keys().cloned().collect()).unwrap_or_default();
    let r4 = |x: f64| (x / MIL_PER_MM * 10000.0).round() / 10000.0;
    let all = json!({"textHeightMm": r4(f.text_height), "textLineWidthMm": r4(f.text_line), "textGapMm": r4(f.text_gap), "lineWidthMm": r4(f.line),
        "arrowSizeMm": r4(f.arrow_size), "arrowLengthMm": r4(f.arrow_length), "extensionOffsetMm": r4(f.extension_offset), "units": f.units, "precision": f.precision, "font": f.font});
    let mut applied = Map::new();
    let mut defaults = Map::new();
    for k in FORMAT_KEYS { if given.iter().any(|g| g == k) { applied.insert(k.to_string(), all[*k].clone()); } else { defaults.insert(k.to_string(), all[*k].clone()); } }
    let ignored: Vec<String> = given.into_iter().filter(|g| !FORMAT_KEYS.contains(&g.as_str())).collect();
    json!({"applied": applied, "defaults": defaults, "ignored": ignored, "keys": FORMAT_KEYS})
}

pub fn format_of(v: Option<&Value>) -> Format {
    // a number or a numeric string ("0.15"): a string value was skipped without a word (AI Flow, 2026-12-02)
    let num = |x: &Value| x.as_f64().or_else(|| x.as_str().and_then(|s| s.trim().trim_end_matches("mm").trim().parse().ok()));
    let mm = |k: &str, d: f64| v.and_then(|o| o.get(k)).and_then(num).map(|x| x * MIL_PER_MM).unwrap_or(d);
    Format {
        text_height: mm("textHeightMm", 40.0), text_line: mm("textLineWidthMm", 4.0), text_gap: mm("textGapMm", 8.0), line: mm("lineWidthMm", 4.0),
        arrow_size: mm("arrowSizeMm", 20.0), arrow_length: mm("arrowLengthMm", 40.0), extension_offset: mm("extensionOffsetMm", 8.0),
        units: v.and_then(|o| o.get("units")).and_then(|x| x.as_str()).unwrap_or("auto").to_string(),
        precision: v.and_then(|o| o.get("precision")).and_then(|x| x.as_i64().or_else(|| x.as_str().and_then(|s| s.trim().parse().ok()))),
        font: v.and_then(|o| o.get("font")).and_then(|x| x.as_str()).map(str::to_string),
    }
}

/// The footprint's existing dimensions, bound again: copying a dimension onto the work board drops its references to bare
/// points (a dimension added by an earlier call stopped following its pad after a second call, measured 2026-12-02), so
/// each reference point is looked up again, a pad centre first, else a track end, and written back bound. Returns the
/// text and how many references were bound.
pub fn rebind(text: &str, w: &Work, off: (f64, f64)) -> (String, usize) {
    let mut n = 0;
    let set = |l: &str, k: &str, v: &str| -> String {
        let key = format!("|{k}=");
        match l.find(&key) {
            Some(i) => { let rest = &l[i + key.len()..]; let end = rest.find('|').map(|e| i + key.len() + e).unwrap_or(l.len()); format!("{}{}{}", &l[..i + key.len()], v, &l[end..]) }
            None => format!("{l}|{k}={v}"),
        }
    };
    let lines: Vec<String> = text.split('\n').map(|l| {
        if !(l.starts_with("|RECORD=Embedded|") && l.contains("DIMENSIONKIND=")) { return l.to_string(); }
        let f = fields(l);
        let mut out = l.to_string();
        // a copied dimension keeps some of its points in the library's own coordinates, the library origin away (50000
        // mil): those are brought back from the work board's origin
        let far = |x: f64, y: f64| x.abs() > 25_000.0 || y.abs() > 25_000.0;
        let fix = |x: f64, y: f64| if far(x, y) { (x - off.0, y - off.1) } else { (x, y) };
        for (kx, ky) in [("X1", "Y1"), ("X2", "Y2")] {
            let (x, y) = (mil(f.get(kx)), mil(f.get(ky)));
            if far(x, 0.0) { out = set(&out, kx, &format!("{:.4}mil", x - off.0)); }
            if far(0.0, y) { out = set(&out, ky, &format!("{:.4}mil", y - off.1)); }
        }
        for r in 0..2 {
            let (x, y) = fix(mil(f.get(&format!("REFERENCE{r}POINTX"))), mil(f.get(&format!("REFERENCE{r}POINTY"))));
            let hit = w.pads.iter().find(|p| (p.2 - x).abs() < 0.02 && (p.3 - y).abs() < 0.02).map(|p| ("Pad", p.0, 1))
                .or_else(|| track_end(w, x, y, None).map(|(i, a)| ("Track", i, a)));
            out = set(&out, &format!("REFERENCE{r}POINTX"), &format!("{x:.4}mil"));
            out = set(&out, &format!("REFERENCE{r}POINTY"), &format!("{y:.4}mil"));
            if let Some((kind, prim, a)) = hit {
                out = set(&out, &format!("REFERENCE{r}PRIM"), &prim.to_string());
                out = set(&out, &format!("REFERENCE{r}OBJECTID"), if kind == "Pad" { "2" } else { "4" });
                out = set(&out, &format!("REFERENCE{r}OBJECTSTRING"), kind);
                out = set(&out, &format!("REFERENCE{r}ANCHOR"), &a.to_string());
                n += 1;
            }
        }
        out
    }).collect();
    (lines.join("\n"), n)
}

/// The work board's text with the dimension records added after its last primitive.
pub fn insert(text: &str, records: &[String]) -> String {
    let lines: Vec<&str> = text.split('\n').collect();
    let prim = |l: &str| ["|RECORD=Pad|", "|RECORD=Track|", "|RECORD=Arc|", "|RECORD=Text|", "|RECORD=Fill|", "|RECORD=Region|", "|RECORD=Embedded|", "|RECORD=ComponentBody|"].iter().any(|p| l.starts_with(p));
    let at = lines.iter().rposition(|l| prim(l)).map(|i| i + 1).unwrap_or(lines.len());
    let mut out: Vec<String> = lines[..at].iter().map(|s| s.to_string()).collect();
    out.extend(records.iter().cloned());
    out.extend(lines[at..].iter().map(|s| s.to_string()));
    out.join("\n")
}

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

/// altium_add_dimensions {libraryPath, footprint, dimensions: [{a, b, dir: H|V, at, expect?, toleranceMm?}], format?, layerMap?}
pub fn add_dimensions(args: &Value) -> Value {
    let s = |k: &str| crate::support::s(args, k);
    let Some(lib) = s("libraryPath").filter(|l| l.to_lowercase().ends_with(".pcblib")) else { return fail("bad_args", "libraryPath (.PcbLib) is required".into()) };
    let Some(name) = s("footprint").or_else(|| s("name")) else { return fail("bad_args", "footprint is required".into()) };
    // replace: true drops the footprint's existing dimensions first (a rerun after a re-import stacked duplicates,
    // AI Flow 2026-12-02); with an empty list it only removes them
    let replace = args.get("replace").and_then(|v| v.as_bool()).unwrap_or(false);
    let Some(list) = args.get("dimensions").and_then(|v| v.as_array()).filter(|a| replace || !a.is_empty()).cloned() else {
        return fail("bad_args", "dimensions is required: [{a, b, dir: H|V, at}] (a, b: a pad number, a corner TL/TR/BR/BL, or {x, y}; at: the dimension line's y (H) or x (V), mm)".into());
    };
    for (i, d) in list.iter().enumerate() {
        let dir = d.get("dir").and_then(|v| v.as_str()).unwrap_or("").to_ascii_uppercase();
        if dir != "H" && dir != "V" { return fail("bad_args", format!("dimensions[{i}].dir: H (measures along x) or V (along y)")); }
        if d.get("at").and_then(|v| v.as_f64()).is_none() { return fail("bad_args", format!("dimensions[{i}].at: where the dimension line runs, mm (its y for H, its x for V)")); }
        if d.get("a").is_none() || d.get("b").is_none() { return fail("bad_args", format!("dimensions[{i}]: a and b are required")); }
    }
    let fmt = format_of(args.get("format"));
    if let Some(g) = crate::support::need_licensed() { return g; }
    if let Some(e) = crate::support::must_open(&lib, 60) { return e; }
    let map = crate::layermap_verb::effective(args, Some(&lib));
    let code = |k: &str| map.entries.iter().find(|e| e.0 == k).map(|e| e.2.clone()).unwrap_or_default();
    let dir = crate::agent::cache_dir().join("dimensions");
    let _ = std::fs::create_dir_all(&dir);
    let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
    let work = dir.join(format!("{safe}.PcbDoc")).to_string_lossy().replace('/', "\\");
    let dur = std::time::Duration::from_secs(120);
    let w = crate::agent::call("dim_work", &[("path", lib.replace('/', "\\")), ("name", name.clone()), ("work", work.clone()), ("lcode", code("dimensions")), ("fcode", code("fab")), ("replace", if replace { "1".into() } else { "0".into() })], None, dur);
    let wd = match crate::sch::agent_data(&w) { Ok(d) => d, Err(e) => return e };
    let text = match std::fs::read(&work) { Ok(b) => String::from_utf8_lossy(&b).to_string(), Err(e) => return fail("work_board_unreadable", format!("{work}: {e}")) };
    let wb = parse_work(&text);
    let dim_mech = wd["dimMech"].as_i64().unwrap_or(13);
    let dim_layer = format!("MECHANICAL{dim_mech}");
    let fab_layer = format!("MECHANICAL{}", wd["fabMech"].as_i64().unwrap_or(13));
    let mut records = Vec::new();
    let mut planned = Vec::new();
    for (i, d) in list.iter().enumerate() {
        let a = match resolve(&wb, &d["a"], &fab_layer) { Ok(x) => x, Err(m) => return fail("anchor_not_found", format!("dimensions[{i}].a: {m}")) };
        let b = match resolve(&wb, &d["b"], &fab_layer) { Ok(x) => x, Err(m) => return fail("anchor_not_found", format!("dimensions[{i}].b: {m}")) };
        let h = d["dir"].as_str().unwrap_or("H").eq_ignore_ascii_case("H");
        let at = d["at"].as_f64().unwrap_or(0.0) * MIL_PER_MM;
        let len = if h { (b.x - a.x).abs() } else { (b.y - a.y).abs() };
        if len < 0.01 { return fail("bad_args", format!("dimensions[{i}]: a and b are level along {} (nothing to measure)", if h { "x" } else { "y" })); }
        let (unit, prec) = units_for(len, &fmt.units, fmt.precision);
        records.push(record(wb.dims + i, dim_mech, h, at, &a, &b, &fmt, unit, prec));
        planned.push(json!({"a": d["a"], "b": d["b"], "dir": if h { "H" } else { "V" }, "lengthMm": (len / MIL_PER_MM * 10000.0).round() / 10000.0, "text": label(len, unit, prec),
            "anchors": [format!("{} {} (anchor {})", a.kind, a.prim, a.anchor), format!("{} {} (anchor {})", b.kind, b.prim, b.anchor)], "expect": d.get("expect"), "toleranceMm": d.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.01)}));
    }
    if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {
        return json!({"success": true, "dryRun": true, "format": format_echo(args.get("format"), &fmt), "dimensions": planned, "layer": dim_layer, "outlineLayer": fab_layer, "_hint": "Nothing changed. Call again without dryRun to add them."});
    }
    let off = wd["offsetMil"].as_array().map(|a| (a.first().and_then(|v| v.as_f64()).unwrap_or(0.0), a.get(1).and_then(|v| v.as_f64()).unwrap_or(0.0))).unwrap_or((0.0, 0.0));
    let (text, rebound) = rebind(&text, &wb, off);
    if let Err(e) = std::fs::write(&work, insert(&text, &records)) { return fail("write_failed", format!("{work}: {e}")); }
    let a = crate::agent::call("dim_apply", &[("path", lib.replace('/', "\\")), ("name", name.clone()), ("work", work.clone()), ("skip", wd["skip"].as_str().unwrap_or("").to_string()),
        ("multiRegions", if text.lines().any(|l| l.starts_with("|RECORD=Region|") && l.contains("|LAYER=MULTILAYER|")) { "1".into() } else { "0".into() })], None, dur);
    let ad = match crate::sch::agent_data(&a) { Ok(d) => d, Err(e) => return e };
    // the proof: saved, closed and reopened, every dimension's references read back
    let saved = crate::surfaces::save(&json!({"filePath": lib}));
    if saved.get("success").and_then(|b| b.as_bool()) == Some(false) { let mut e = saved.clone(); e["errorCode"] = json!("save_failed"); return e; }
    let _ = crate::agent::call("close_document", &[("path", lib.replace('/', "\\"))], None, dur);
    if let Some(e) = crate::support::must_open(&lib, 60) { return e; }
    let r = crate::agent::call("dim_read", &[("path", lib.replace('/', "\\")), ("name", name.clone())], None, dur);
    let rd = match crate::sch::agent_data(&r) { Ok(d) => d, Err(e) => return e };
    let k = rd["k"].as_f64().unwrap_or(10_000_000.0) / 25.4;
    let found: Vec<(bool, f64)> = rd["dims"].as_array().cloned().unwrap_or_default().iter().map(|d| (d[0].as_bool().unwrap_or(false), d[1].as_f64().unwrap_or(0.0) / k)).collect();
    let styles: Vec<Value> = rd["style"].as_array().cloned().unwrap_or_default().iter().map(|s| {
        let mm = |i: usize| (s[i].as_f64().unwrap_or(0.0) / k * 10000.0).round() / 10000.0;
        json!({"textHeightMm": mm(0), "textLineWidthMm": mm(1), "lineWidthMm": mm(2), "arrowSizeMm": mm(3), "arrowLengthMm": mm(4), "extensionOffsetMm": mm(5)})
    }).collect();
    let mech_of = |id: i64| if (57..=72).contains(&id) { id - 56 } else if id > 67_108_864 { id - 67_108_864 } else { 0 };
    let layers: Vec<i64> = rd["dims"].as_array().cloned().unwrap_or_default().iter().map(|d| mech_of(d[2].as_i64().unwrap_or(0))).collect();
    let mut used = vec![false; found.len()];
    let mut out = Vec::new();
    let mut ok = true;
    for p in planned {
        let want = p["lengthMm"].as_f64().unwrap_or(0.0);
        let hit = found.iter().enumerate().filter(|(i, _)| !used[*i]).min_by(|x, y| (x.1 .1 - want).abs().partial_cmp(&(y.1 .1 - want).abs()).unwrap()).map(|(i, f)| (i, *f));
        let mut q = p.clone();
        match hit {
            Some((i, (valid, v))) if (v - want).abs() < 0.001 => {
                used[i] = true;
                q["valueMm"] = json!((v * 10000.0).round() / 10000.0);
                q["validAfterReopen"] = json!(valid);
                q["onLayer"] = json!(format!("Mechanical {}", layers[i]));
                if let Some(st) = styles.get(i) { q["style"] = st.clone(); }
                if !valid { ok = false; }
                if layers[i] != dim_mech { ok = false; q["error"] = json!(format!("landed on Mechanical {}, not {}", layers[i], dim_mech)); }
                if let Some(e) = p["expect"].as_f64() {
                    let tol = p["toleranceMm"].as_f64().unwrap_or(0.01);
                    q["check"] = json!(if (v - e).abs() <= tol { "MATCH" } else { "MISMATCH" });
                    q["deltaMm"] = json!(((v - e) * 10000.0).round() / 10000.0);
                }
            }
            _ => { ok = false; q["validAfterReopen"] = json!(false); q["error"] = json!("not found after the library was reopened"); }
        }
        out.push(q);
    }
    let mismatch = out.iter().any(|d| d["check"] == "MISMATCH");
    json!({"success": ok, "errorCode": if ok { Value::Null } else { json!("not_anchored") }, "footprint": name, "library": lib, "layer": dim_layer, "outlineLayer": fab_layer,
        "dimensions": out, "allDimensions": found.len(), "format": format_echo(args.get("format"), &fmt), "rebuilt": {"moved": ad["moved"], "bodies": ad["bodies"], "existingDimensions": wb.dims, "referencesRebound": rebound, "replaced": replace}, "anyMismatch": mismatch, "saved": true,
        "_hint": if ok { "Each dimension is bound to its pads or corners (validAfterReopen: read back after the library was saved, closed and reopened) and follows them when they move. check compares the measured length with expect." }
            else { "A dimension did not validate after the reopen: its anchor may be a corner shared by a chamfer, or a pad Altium could not rebind. Read the footprint (altium_read_footprint) and call again; a chamfered outline needs fabOutline: edges." }})
}

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

    const WORK: &str = "|RECORD=Board|X=0\n|RECORD=Track|INDEXFORSAVE=4|LAYER=MECHANICAL16|LAYER_V7=MECHANICAL19|X1=0mil|Y1=0mil|X2=10mil|Y2=0mil\n|RECORD=Pad|INDEXFORSAVE=0|LAYER=TOP|NAME=1|X=-106.2992mil|Y=75mil|XSIZE=10mil\n|RECORD=Pad|INDEXFORSAVE=1|LAYER=TOP|NAME=8|X=106.2992mil|Y=75mil\n|RECORD=Track|INDEXFORSAVE=0|LAYER=MECHANICAL13|X1=-76.7717mil|Y1=96.4567mil|X2=76.7717mil|Y2=96.4567mil|WIDTH=3.937mil\n|RECORD=Track|INDEXFORSAVE=1|LAYER=MECHANICAL13|X1=76.7717mil|Y1=-96.4567mil|X2=76.7717mil|Y2=96.4567mil\n|RECORD=Track|INDEXFORSAVE=2|LAYER=MECHANICAL13|X1=-76.7717mil|Y1=-96.4567mil|X2=76.7717mil|Y2=-96.4567mil\n|RECORD=Track|INDEXFORSAVE=3|LAYER=MECHANICAL13|X1=-76.7717mil|Y1=-96.4567mil|X2=-76.7717mil|Y2=96.4567mil\n|RECORD=Rule|NAME=x";

    #[test]
    fn anchors_are_pads_corners_and_track_ends() {
        let w = parse_work(WORK);
        assert_eq!((w.pads.len(), w.tracks.len(), w.dims), (2, 5, 0));
        assert_eq!(w.tracks[0].1, "MECHANICAL19", "LAYER_V7 is the real layer");
        assert_eq!(resolve(&w, &json!("8"), "MECHANICAL13").unwrap(), Anchor { kind: "Pad", prim: 1, anchor: 1, x: 106.2992, y: 75.0 });
        // TL is the top edge's start; TR its end; BR is where the right edge starts as Altium saved it (its X1/Y1)
        let tl = resolve(&w, &json!("TL"), "MECHANICAL13").unwrap();
        assert_eq!((tl.prim, tl.anchor), (0, 1));
        let tr = resolve(&w, &json!("corner:TR"), "MECHANICAL13").unwrap();
        assert_eq!((tr.prim, tr.anchor), (0, 2));
        let br = resolve(&w, &json!("BR"), "MECHANICAL13").unwrap();
        assert!((br.prim == 1 && br.anchor == 1) || (br.prim == 2 && br.anchor == 2), "{br:?}");
        let p = resolve(&w, &json!({"x": -1.95, "y": -2.45}), "MECHANICAL13").unwrap();
        assert_eq!(p.kind, "Track");
        assert!(resolve(&w, &json!("9"), "MECHANICAL13").is_err());
        assert!(resolve(&w, &json!("TL"), "MECHANICAL15").is_err(), "no outline on that layer");
    }

    #[test]
    fn an_existing_dimension_is_bound_again() {
        let dim = "|RECORD=Embedded|INDEXFORSAVE=0|DIMENSIONKIND=1|REFERENCE0PRIM=-1|REFERENCE0OBJECTID=-1|REFERENCE0OBJECTSTRING=NoObject|REFERENCE0POINTX=-106.2992mil|REFERENCE0POINTY=75mil|REFERENCE0ANCHOR=-1|REFERENCE1PRIM=-1|REFERENCE1OBJECTID=-1|REFERENCE1OBJECTSTRING=NoObject|REFERENCE1POINTX=76.7717mil|REFERENCE1POINTY=96.4567mil|REFERENCE1ANCHOR=-1|ANGLE=0";
        let text = format!("{WORK}\n{dim}");
        let w = parse_work(&text);
        assert_eq!(w.dims, 1);
        let (out, n) = rebind(&text, &w, (50000.0, 50000.0));
        assert_eq!(n, 2);
        let l = out.lines().last().unwrap();
        assert!(l.contains("|REFERENCE0PRIM=0|REFERENCE0OBJECTID=2|REFERENCE0OBJECTSTRING=Pad|") && l.contains("|REFERENCE0ANCHOR=1|"), "{l}");
        assert!(l.contains("|REFERENCE1OBJECTSTRING=Track|") && l.contains("|REFERENCE1ANCHOR=2|"), "the top edge's X2/Y2 end: {l}");
        // a point still in the library's coordinates (50000 mil out) is brought back
        let far = dim.replace("REFERENCE0POINTX=-106.2992mil|REFERENCE0POINTY=75mil", "REFERENCE0POINTX=49893.7008mil|REFERENCE0POINTY=50075mil");
        let (out2, n2) = rebind(&format!("{WORK}\n{far}"), &w, (50000.0, 50000.0));
        assert_eq!(n2, 2, "{out2}");
        assert!(out2.lines().last().unwrap().contains("|REFERENCE0POINTX=-106.2992mil|"));
    }

    #[test]
    fn the_format_echo_names_what_was_read() {
        let v = json!({"textHeightMm": 0.3, "textHeight": 0.3, "arrowSizeMm": 0.2});
        let e = format_echo(Some(&v), &format_of(Some(&v)));
        assert_eq!(e["applied"]["textHeightMm"], json!(0.3));
        assert_eq!(e["applied"]["arrowSizeMm"], json!(0.2));
        assert_eq!(e["ignored"], json!(["textHeight"]));
        let s = format_of(Some(&json!({"arrowSizeMm": "0.15", "lineWidthMm": "0.05mm"})));
        assert!((s.arrow_size / MIL_PER_MM - 0.15).abs() < 1e-9 && (s.line / MIL_PER_MM - 0.05).abs() < 1e-9, "numeric strings are read");
        assert!(e["defaults"].get("lineWidthMm").is_some() && e["defaults"].get("arrowSizeMm").is_none());
    }

    #[test]
    fn units_follow_the_house_rule() {
        assert_eq!(units_for(50.0, "auto", None), ("Mils", 0));
        assert_eq!(units_for(212.5984, "auto", None), ("Millimeters", 2));
        assert_eq!(label(212.5984, "Millimeters", 2), "5.40 mm");
        assert_eq!(label(50.0, "Mils", 0), "50 mil");
        assert_eq!(units_for(50.0, "mm", None), ("Millimeters", 2));
    }

    #[test]
    fn the_record_binds_both_ends() {
        let w = parse_work(WORK);
        let a = resolve(&w, &json!("1"), "MECHANICAL13").unwrap();
        let b = resolve(&w, &json!("8"), "MECHANICAL13").unwrap();
        let r = record(0, 13, true, 150.0, &a, &b, &format_of(None), "Millimeters", 2);
        assert!(r.starts_with("|RECORD=Embedded|INDEXFORSAVE=0|"));
        assert!(r.contains("|REFERENCE0PRIM=0|REFERENCE0OBJECTID=2|REFERENCE0OBJECTSTRING=Pad|") && r.contains("|REFERENCE1PRIM=1|"), "{r}");
        assert!(r.contains("|X1=-106.2992mil|Y1=150.0000mil|X2=106.2992mil|Y2=150.0000mil|"), "{r}");
        assert!(r.contains("|DIMENSIONLAYER=MECHANICAL13|") && r.contains("|TEXTDIMENSIONUNIT=Millimeters|"));
        let typed = record(1, 21, true, 150.0, &a, &b, &format_of(None), "Millimeters", 2);
        assert!(typed.contains("|LAYER=MECHANICAL16|") && typed.contains("|LAYER_V7=MECHANICAL21|") && typed.contains("|DIMENSIONLAYER_V7=MECHANICAL21|") && typed.contains("|DIMENSIONLAYER=MECHANICAL16|"), "{typed}");
        let out = insert(WORK, &[r.clone()]);
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(lines[lines.len() - 2], r, "after the last primitive, before the rules");
    }
}