main
Colby Knox 0.2.123: slots and unplated holes from KiCad (#45, #49), outline Gerber check (#46), stack region refit (#47), eval siz… 4223811
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
//! Schematic wiring as data: the EDA Bridge Standard's sch_* wiring verbs on Altium (adom/eda-bridge-standard,
//! proposed by kicad-lane, batch 1). The agent only dumps a sheet (`sch_dump`) and applies primitive steps as one undo
//! step (`sch_ops`); reading, planning and checking happen here, over plain data, so they are unit-tested.
//!
//! The standard's schematic frame: millimetres, the sheet's origin, y up (Altium's own frame, in mm instead of mils),
//! pins as Ref.Pin. Altium gives wires, labels and junctions no stable id, so an item's id is a hash of its kind and
//! geometry: valid until the item changes, and every edit answers the new ids.
use crate::sch::{agent_data, clean, maybe_save, need_sheet, st};
use crate::support::{self, timeout_of};
use crate::agent;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};

type P = (i64, i64);

#[derive(Debug, Clone, Default)]
pub struct Item {
    pub t: char,
    pub key: String,
    pub pts: Vec<P>,
    pub at: P,
    pub corner: P,
    pub text: String,
    pub rot: i64,
    pub w: i64,
    pub h: i64,
    pub file: String,
    pub entries: Vec<(String, i64, i64, i64)>,
}

#[derive(Debug, Clone, Default)]
pub struct Pin { pub r: String, pub num: String, pub name: String, pub elec: i64, pub at: P, pub dir: i64, pub hidden: bool }

#[derive(Debug, Clone, Default)]
pub struct Comp { pub r: String, pub at: P, pub lib: String, pub lib_path: String, pub rot: i64, pub mirror: bool, pub des: [i64; 4], pub cmt: [i64; 4], pub bx: Option<[i64; 4]> }

#[derive(Debug, Clone, Default)]
pub struct Sheet { pub k: f64, pub items: Vec<Item>, pub pins: Vec<Pin>, pub comps: Vec<Comp>, pub page: Value, pub document: String }

fn r4(v: f64) -> f64 { (v * 10000.0).round() / 10000.0 }

impl Sheet {
    /// raw units to mm (k is raw units per inch)
    pub fn mm(&self, v: i64) -> f64 { r4(v as f64 * 25.4 / self.k) }
    pub fn raw(&self, mm: f64) -> i64 { (mm * self.k / 25.4).round() as i64 }
    pub fn pt(&self, p: P) -> Value { json!([self.mm(p.0), self.mm(p.1)]) }
    fn tol(&self) -> i64 { ((self.k / 25.4) * 0.001).round().max(1.0) as i64 }
}

/// An item's id: its kind and a hash of its key (kind, geometry, text).
pub fn id_of(key: &str) -> String {
    let kind = match key.chars().next() {
        Some('W') => "wire", Some('B') => "bus", Some('E') => "entry", Some('J') => "junction", Some('X') => "noconnect",
        Some('N') => "label", Some('P') => "port", Some('O') => "power", Some('T') => "text", Some('S') => "sheet", _ => "item",
    };
    format!("{kind}-{}", &crate::routing::fnv(key)[..10])
}

pub fn parse(d: &Value) -> Sheet {
    let k = d["k"].as_f64().filter(|k| *k > 0.0).unwrap_or(10_000_000.0);
    let i = |v: &Value| v.as_i64().unwrap_or(0);
    let mut sh = Sheet { k, page: d["page"].clone(), document: st(&d["document"]), ..Default::default() };
    for it in d["items"].as_array().cloned().unwrap_or_default() {
        let t = st(&it["t"]).chars().next().unwrap_or('?');
        if t == 'C' {
            let f4 = |v: &Value| { let mut a = [0i64; 4]; for (k, x) in a.iter_mut().enumerate() { *x = i(&v[k]); } a };
            sh.comps.push(Comp { r: st(&it["ref"]), at: (i(&it["x"]), i(&it["y"])), lib: st(&it["lib"]), lib_path: st(&it["libPath"]),
                rot: i(&it["rot"]), mirror: it["mirror"].as_bool() == Some(true), des: f4(&it["des"]), cmt: f4(&it["cmt"]),
                bx: it["box"].as_array().filter(|b| b.len() == 4).map(|_| f4(&it["box"])) });
            continue;
        }
        let pts: Vec<P> = it["pts"].as_array().cloned().unwrap_or_default().iter().map(|p| (i(&p[0]), i(&p[1]))).collect();
        let entries = it["entries"].as_array().cloned().unwrap_or_default().iter()
            .map(|e| (st(&e[0]), i(&e[1]), i(&e[2]), i(&e[3]))).collect();
        sh.items.push(Item { t, key: st(&it["key"]), pts, at: (i(&it["x"]), i(&it["y"])), corner: (i(&it["cx"]), i(&it["cy"])),
            text: st(&it["text"]), rot: i(&it["rot"]), w: i(&it["w"]), h: i(&it["h"]), file: st(&it["file"]), entries });
    }
    for p in d["pins"].as_array().cloned().unwrap_or_default() {
        sh.pins.push(Pin { r: st(&p[0]), num: st(&p[1]), name: st(&p[2]), elec: i(&p[3]), at: (i(&p[4]), i(&p[5])), dir: i(&p[6]), hidden: p[7].as_bool() == Some(true) });
    }
    sh
}

// -- geometry -----------------------------------------------------------------------------------------------------

/// p on segment a-b (within tol), and whether strictly inside it (not at an end)
fn on_seg(p: P, a: P, b: P, tol: i64) -> (bool, bool) {
    let (dx, dy) = ((b.0 - a.0) as f64, (b.1 - a.1) as f64);
    let l2 = dx * dx + dy * dy;
    let near = |q: P| (q.0 - p.0).abs() <= tol && (q.1 - p.1).abs() <= tol;
    if near(a) || near(b) { return (true, false); }
    if l2 == 0.0 { return (false, false); }
    let t = (((p.0 - a.0) as f64) * dx + ((p.1 - a.1) as f64) * dy) / l2;
    if !(0.0..=1.0).contains(&t) { return (false, false); }
    let (qx, qy) = (a.0 as f64 + t * dx, a.1 as f64 + t * dy);
    let on = (qx - p.0 as f64).abs() <= tol as f64 && (qy - p.1 as f64).abs() <= tol as f64;
    (on, on)
}

fn same(a: P, b: P, tol: i64) -> bool { (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol }

/// The sheet's size in mm, (width, height), from its page: Altium's standard styles (A4 .. E, Letter, Legal, Tabloid,
/// OrCAD A .. E, in mil, landscape; portrait swaps them) or its custom size. None when the style is unknown.
pub fn sheet_size_mm(sh: &Sheet) -> Option<(f64, f64)> {
    let pg = &sh.page;
    let mil = |w: f64, h: f64| (w * 0.0254, h * 0.0254);
    let (w, h) = if pg["custom"].as_bool() == Some(true) {
        let (cx, cy) = (pg["cx"].as_f64()?, pg["cy"].as_f64()?);
        if cx <= 0.0 || cy <= 0.0 { return None; }
        // the API answers raw units on some builds and Altium's 10 mil units on others
        if cx > 100_000.0 { (sh.mm(cx as i64), sh.mm(cy as i64)) } else { mil(cx * 10.0, cy * 10.0) }
    } else {
        const STYLES: [(f64, f64); 18] = [(11500., 7600.), (15500., 11100.), (22300., 15700.), (31500., 22300.), (44600., 31500.),
            (9500., 7500.), (15000., 9500.), (20000., 15000.), (32000., 20000.), (42000., 32000.), (11000., 8500.), (14000., 8500.),
            (17000., 11000.), (9900., 7900.), (15400., 9900.), (20600., 15600.), (32600., 20600.), (42800., 32800.)];
        let (w, h) = *STYLES.get(pg["style"].as_u64()? as usize)?;
        mil(w, h)
    };
    Some(if pg["orientation"].as_i64() == Some(1) { (h, w) } else { (w, h) })
}

/// The sheet as the standard's sheetDrawing (docs/conventions.md, #29): mm, y down (Altium's y negated), wires split
/// into their segments. Altium's other connection points come as what they are to the checks: power ports and ports
/// as power and hierarchical labels (a port at whichever end meets the wiring), a sheet symbol's entries as
/// hierarchical labels, and a bus entry as a short wire with a junction where it meets the bus. Pure.
pub fn drawing(name: &str, sh: &Sheet) -> Value {
    // origin top left, y down: y from the sheet's top edge (Altium's own y negated when the sheet size is unknown)
    let size = sheet_size_mm(sh);
    let top = size.map(|s| s.1).unwrap_or(0.0);
    let flip = |y: i64| ((top - sh.mm(y)) * 10000.0).round() / 10000.0;
    let pt = |p: P| json!([sh.mm(p.0), flip(p.1)]);
    let tol = sh.tol();
    let (mut wires, mut buses, mut junctions, mut ncs, mut labels) = (vec![], vec![], vec![], vec![], vec![]);
    let wire_points: Vec<P> = sh.items.iter().filter(|it| it.t == 'W').flat_map(|it| it.pts.clone()).collect();
    for it in &sh.items {
        match it.t {
            'W' | 'B' => for w in it.pts.windows(2) {
                let seg = json!({"a": pt(w[0]), "b": pt(w[1])});
                if it.t == 'W' { wires.push(seg) } else { buses.push(seg) }
            },
            'E' => { wires.push(json!({"a": pt(it.at), "b": pt(it.corner)})); junctions.push(pt(it.at)); }
            'J' => junctions.push(pt(it.at)),
            'X' => ncs.push(pt(it.at)),
            'N' => labels.push(json!({"text": it.text, "kind": "local", "at": pt(it.at)})),
            'O' => labels.push(json!({"text": it.text, "kind": "power", "at": pt(it.at)})),
            'P' => {
                let ends = port_ends(it);
                let wired = ends.iter().find(|e| wire_points.iter().any(|w| same(**e, *w, tol)) || sh.pins.iter().any(|p| same(**e, p.at, tol))).copied();
                labels.push(json!({"text": it.text, "kind": "hierarchical", "at": pt(wired.unwrap_or(it.at))}));
            }
            'S' => for (n, side, dist, _) in &it.entries { labels.push(json!({"text": n, "kind": "hierarchical", "at": pt(entry_point(it, *side, *dist))})); },
            _ => {}
        }
    }
    let pins: Vec<Value> = sh.pins.iter().filter(|p| !p.hidden).map(|p| json!({"ref": p.r, "number": p.num, "at": pt(p.at)})).collect();
    let symbols: Vec<Value> = sh.comps.iter().filter_map(|c| c.bx.map(|b| json!({"ref": c.r, "box": [sh.mm(b[0]), flip(b[3]), sh.mm(b[2]), flip(b[1])]}))).collect();
    json!({"sheet": name, "sizeMm": size.map(|s| json!([((s.0 * 100.0).round() / 100.0), ((s.1 * 100.0).round() / 100.0)])), "wires": wires, "buses": buses, "junctions": junctions, "noConnects": ncs, "labels": labels, "pins": pins, "symbols": symbols})
}

/// A sheet entry's point on its symbol's edge (Altium: Side 0 left, 1 right, 2 top, 3 bottom; distance from the top
/// or the left).
pub fn entry_point(s: &Item, side: i64, dist: i64) -> P {
    match side { 1 => (s.at.0 + s.w, s.at.1 - dist), 2 => (s.at.0 + dist, s.at.1), 3 => (s.at.0 + dist, s.at.1 - s.h), _ => (s.at.0, s.at.1 - dist) }
}

/// A port's two connection ends (it is drawn from Location along its width).
fn port_ends(p: &Item) -> [P; 2] { [p.at, (p.at.0 + p.w, p.at.1)] }

fn segs(it: &Item) -> Vec<(P, P)> { it.pts.windows(2).map(|w| (w[0], w[1])).collect() }

// -- connectivity ---------------------------------------------------------------------------------------------------

/// A node of the sheet's connectivity graph.
#[derive(Debug, Clone, PartialEq)]
pub enum Node { Wire(usize), Pin(usize), Item(usize), Entry(usize, usize) }

/// Groups of electrically joined nodes on one sheet, with Altium's rules: a wire end joins another wire anywhere
/// along it (a T) and a wire end; crossing middles join only at a junction; labels, power ports, ports and junctions
/// join a wire anywhere along it; pins and sheet entries join wire ends (and each other when they touch); labels and
/// power ports with the same text are the same net.
pub struct Graph { pub nodes: Vec<Node>, pub group: Vec<usize> }

fn find(p: &mut Vec<usize>, x: usize) -> usize { let mut r = x; while p[r] != r { r = p[r]; } let mut y = x; while p[y] != r { let n = p[y]; p[y] = r; y = n; } r }

pub fn graph(sh: &Sheet) -> Graph {
    let tol = sh.tol();
    let mut nodes = Vec::new();
    for (i, it) in sh.items.iter().enumerate() { if it.t == 'W' { nodes.push(Node::Wire(i)); } }
    for i in 0..sh.pins.len() { nodes.push(Node::Pin(i)); }
    for (i, it) in sh.items.iter().enumerate() {
        match it.t { 'N' | 'O' | 'P' | 'J' | 'X' => nodes.push(Node::Item(i)), 'S' => for e in 0..it.entries.len() { nodes.push(Node::Entry(i, e)) }, _ => {} }
    }
    let n = nodes.len();
    let mut par: Vec<usize> = (0..n).collect();
    // the points each node offers, and whether it joins a wire's middle
    let pts_of = |nd: &Node| -> (Vec<P>, bool) {
        match nd {
            Node::Pin(i) => (vec![sh.pins[*i].at], false),
            Node::Item(i) => { let it = &sh.items[*i]; if it.t == 'P' { (port_ends(it).to_vec(), true) } else { (vec![it.at], it.t != 'X') } }
            Node::Entry(i, e) => { let it = &sh.items[*i]; let (_, side, dist, _) = &it.entries[*e]; (vec![entry_point(it, *side, *dist)], false) }
            Node::Wire(_) => (vec![], false),
        }
    };
    let ends = |i: usize| -> Vec<P> { let p = &sh.items[i].pts; if p.is_empty() { vec![] } else { vec![p[0], p[p.len() - 1]] } };
    for a in 0..n {
        for b in (a + 1)..n {
            let join = match (&nodes[a], &nodes[b]) {
                (Node::Wire(i), Node::Wire(j)) => {
                    let (si, sj) = (segs(&sh.items[*i]), segs(&sh.items[*j]));
                    ends(*i).iter().any(|p| sj.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0)) || ends(*j).iter().any(|p| si.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0))
                        // crossing middles joined by a junction dot
                        || sh.items.iter().filter(|it| it.t == 'J').any(|jn| si.iter().any(|(x, y)| on_seg(jn.at, *x, *y, tol).0) && sj.iter().any(|(x, y)| on_seg(jn.at, *x, *y, tol).0))
                }
                (Node::Wire(w), o) | (o, Node::Wire(w)) => {
                    let (ps, middle) = pts_of(o);
                    let s = segs(&sh.items[*w]);
                    ps.iter().any(|p| if middle { s.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0) } else { ends(*w).iter().any(|e| same(*e, *p, tol)) || s.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0 && !on_seg(*p, *x, *y, tol).1 ) })
                }
                (x, y) => {
                    let (px, _) = pts_of(x);
                    let (py, _) = pts_of(y);
                    let touch = px.iter().any(|p| py.iter().any(|q| same(*p, *q, tol)));
                    let named = |nd: &Node| match nd { Node::Item(i) if matches!(sh.items[*i].t, 'N' | 'O') => Some(sh.items[*i].text.to_uppercase()), _ => None };
                    touch || matches!((named(x), named(y)), (Some(a), Some(b)) if a == b)
                }
            };
            if join { let (ra, rb) = (find(&mut par, a), find(&mut par, b)); if ra != rb { par[ra] = rb; } }
        }
    }
    let group = (0..n).map(|i| find(&mut par, i)).collect();
    Graph { nodes, group }
}

/// The nets of a sheet: per group, its name (power port, then net label, then port, then sheet entry) and members.
pub fn nets(sh: &Sheet, g: &Graph) -> Vec<Value> {
    let mut by: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for (i, gr) in g.group.iter().enumerate() { by.entry(*gr).or_default().push(i); }
    let mut out = Vec::new();
    for (_, members) in by {
        let (mut pins, mut labels, mut power, mut ports, mut wires, mut entries) = (vec![], vec![], vec![], vec![], vec![], vec![]);
        for m in &members {
            match &g.nodes[*m] {
                Node::Pin(i) => pins.push(format!("{}.{}", sh.pins[*i].r, sh.pins[*i].num)),
                Node::Wire(i) => wires.push(id_of(&sh.items[*i].key)),
                Node::Item(i) => { let it = &sh.items[*i]; match it.t { 'N' => labels.push(it.text.clone()), 'O' => power.push(it.text.clone()), 'P' => ports.push(it.text.clone()), _ => {} } }
                Node::Entry(i, e) => entries.push(sh.items[*i].entries[*e].0.clone()),
            }
        }
        if pins.is_empty() && labels.is_empty() && power.is_empty() && ports.is_empty() && entries.is_empty() { continue; } // a lone wire or dot
        let mut names: Vec<String> = power.iter().chain(labels.iter()).chain(ports.iter()).chain(entries.iter()).cloned().collect();
        names.dedup();
        let name = names.first().cloned().unwrap_or_else(|| pins.first().map(|p| format!("Net{}", p.replace('.', "_"))).unwrap_or_default());
        labels.sort(); labels.dedup(); power.sort(); power.dedup();
        out.push(json!({"name": name, "pins": pins, "labels": labels, "powerPorts": power, "ports": ports, "sheetEntries": entries, "wires": wires,
            "leavesSheet": !power.is_empty() || !ports.is_empty() || !entries.is_empty()}));
    }
    out
}

// -- the agent round trips ------------------------------------------------------------------------------------------

pub(crate) fn load(args: &Value) -> Result<(String, Sheet), Value> {
    if let Some(g) = support::need_licensed() { return Err(g); }
    let sheet = need_sheet(args)?;
    if let Some(e) = support::must_open(&sheet, 60) { return Err(e); }
    let r = agent::call("sch_dump", &[], None, timeout_of(args, 120));
    let d = agent_data(&r)?;
    Ok((sheet, parse(&d)))
}

pub(crate) fn apply(args: &Value, ops: &[String]) -> Result<Vec<Value>, Value> {
    if ops.is_empty() { return Ok(vec![]); }
    let r = agent::call("sch_ops", &[], Some(&ops.join("\n")), timeout_of(args, 120));
    let d = agent_data(&r)?;
    Ok(d["results"].as_array().cloned().unwrap_or_default())
}

pub(crate) fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }

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

fn raw_pts(_sh: &Sheet, pts: &[P]) -> String { pts.iter().map(|p| format!("{},{}", p.0, p.1)).collect::<Vec<_>>().join(",") }

pub(crate) fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }

fn kind_name(t: char) -> &'static str {
    match t { 'W' => "wire", 'B' => "bus", 'E' => "busEntry", 'J' => "junction", 'X' => "noConnect", 'N' => "label", 'P' => "port", 'O' => "powerPort", 'T' => "text", 'S' => "sheet", _ => "item" }
}

pub(crate) fn by_id<'a>(sh: &'a Sheet, id: &str) -> Option<(usize, &'a Item)> { sh.items.iter().enumerate().find(|(_, it)| id_of(&it.key) == id) }

/// Ids of the items a step created or changed, from the agent's per-step keys.
pub(crate) fn new_ids(results: &[Value]) -> Vec<Value> { results.iter().filter_map(|r| r["key"].as_str().filter(|k| !k.is_empty()).map(|k| json!(id_of(k)))).collect() }

pub(crate) fn failed(results: &[Value]) -> Vec<Value> { results.iter().filter(|r| r["result"] != json!("ok")).cloned().collect() }

// -- verbs ----------------------------------------------------------------------------------------------------------

/// altium_sch_items {sheet, kinds?}
pub fn items(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let want: Option<Vec<String>> = args.get("kinds").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(str::to_string).collect());
    let on = |k: &str| want.as_ref().map(|w| w.iter().any(|x| x == k)).unwrap_or(true);
    let mut out = BTreeMap::new();
    for k in ["wires", "buses", "busEntries", "labels", "powerPorts", "junctions", "noConnects", "texts", "sheets"] { out.insert(k, Vec::<Value>::new()); }
    for it in &sh.items {
        let id = id_of(&it.key);
        let (k, v) = match it.t {
            'W' | 'B' => (if it.t == 'W' { "wires" } else { "buses" }, json!({"id": id, "from": sh.pt(it.pts[0]), "to": sh.pt(*it.pts.last().unwrap_or(&it.pts[0])), "points": it.pts.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>()})),
            'E' => ("busEntries", json!({"id": id, "at": sh.pt(it.at), "end": sh.pt(it.corner)})),
            'N' => ("labels", json!({"id": id, "text": it.text, "kind": "local", "at": sh.pt(it.at), "rotation": it.rot * 90})),
            'P' => ("labels", json!({"id": id, "text": it.text, "kind": "hierarchical", "at": sh.pt(it.at), "rotation": 0, "altium": "port", "widthMm": sh.mm(it.w)})),
            'O' => ("powerPorts", json!({"id": id, "net": it.text, "at": sh.pt(it.at), "rotation": it.rot * 90})),
            'J' => ("junctions", json!({"id": id, "at": sh.pt(it.at)})),
            'X' => ("noConnects", json!({"id": id, "at": sh.pt(it.at)})),
            'T' => ("texts", json!({"id": id, "text": it.text, "at": sh.pt(it.at), "rotation": it.rot * 90})),
            'S' => ("sheets", json!({"id": id, "name": it.text, "file": it.file, "at": sh.pt(it.at), "sizeMm": [sh.mm(it.w), sh.mm(it.h)],
                "pins": it.entries.iter().map(|(n, side, dist, _)| json!({"name": n, "at": sh.pt(entry_point(it, *side, *dist))})).collect::<Vec<_>>()})),
            _ => continue,
        };
        if on(k) { out.get_mut(k).unwrap().push(v); }
    }
    let counts: BTreeMap<&str, usize> = out.iter().map(|(k, v)| (*k, v.len())).collect();
    // objects stacked on one spot share an id (kind plus geometry): a net label over another one joins their nets
    // where nobody sees it (#50: 570 labels sat on the visible ones)
    let mut seen: BTreeMap<(String, String), usize> = BTreeMap::new();
    for (k, v) in &out { for it in v { if let Some(id) = it["id"].as_str() { *seen.entry((k.to_string(), id.to_string())).or_default() += 1; } } }
    let stacked: Vec<Value> = seen.into_iter().filter(|(_, n)| *n > 1).map(|((k, id), n)| json!({"kind": k, "id": id, "count": n})).collect();
    let mut r = json!({"success": true, "sheet": sheet, "units": "mm", "counts": counts, "stacked": stacked,
        "_hint": "Ids are Altium items' kind plus a hash of their geometry: valid until the item changes; every edit verb answers the new ids. stacked lists ids that more than one object shares (objects on top of each other: a label over a label joins nets unseen). Altium's ports are listed as hierarchical labels (altium: port). Parts are in altium_schematic_data; pins in altium_sch_pins."});
    for (k, v) in out { if on(k) { r[k] = json!(v); } }
    r
}

fn dir_name(d: i64) -> &'static str { match d { 0 => "right", 1 => "up", 2 => "left", _ => "down" } }

fn pin_type(e: i64) -> &'static str { crate::schreview::electrical(e) }

/// altium_sch_pins {sheet, references?, connections?}
pub fn pins(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let refs: Option<Vec<String>> = args.get("references").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(|x| x.to_uppercase()).collect());
    let conn = args.get("connections").and_then(|v| v.as_bool()) != Some(false);
    let g = if conn { Some(graph(&sh)) } else { None };
    let nets_all = g.as_ref().map(|g| nets(&sh, g)).unwrap_or_default();
    let tol = sh.tol();
    let mut out = Vec::new();
    for (pi, p) in sh.pins.iter().enumerate() {
        if let Some(rs) = &refs { if !rs.contains(&p.r.to_uppercase()) { continue; } }
        let mut v = json!({"ref": p.r, "number": p.num, "name": p.name, "type": pin_type(p.elec), "at": sh.pt(p.at), "direction": dir_name(p.dir), "hidden": p.hidden});
        if let Some(g) = &g {
            let me = g.nodes.iter().position(|n| *n == Node::Pin(pi)).unwrap();
            let grp = g.group[me];
            let touching: Vec<Value> = sh.items.iter().filter(|it| match it.t {
                'W' => it.pts.first().map(|a| same(*a, p.at, tol)).unwrap_or(false) || it.pts.last().map(|a| same(*a, p.at, tol)).unwrap_or(false),
                'N' | 'O' | 'J' | 'X' => same(it.at, p.at, tol),
                'P' => port_ends(it).iter().any(|e| same(*e, p.at, tol)),
                _ => false }).map(|it| json!({"kind": kind_name(it.t), "id": id_of(&it.key)})).collect();
            let others: Vec<String> = g.nodes.iter().enumerate().filter(|(i, n)| g.group[*i] == grp && *i != me && matches!(n, Node::Pin(_)))
                .map(|(_, n)| if let Node::Pin(j) = n { format!("{}.{}", sh.pins[*j].r, sh.pins[*j].num) } else { String::new() }).collect();
            let key = format!("{}.{}", p.r, p.num);
            let net_names: Vec<Value> = nets_all.iter().filter(|n| n["pins"].as_array().map(|a| a.iter().any(|x| x == &json!(key))).unwrap_or(false)).map(|n| n["name"].clone()).collect();
            v["touching"] = json!(touching); v["nets"] = json!(net_names); v["connectedPins"] = json!(others);
        }
        out.push(v);
    }
    json!({"success": true, "sheet": sheet, "units": "mm", "pins": out,
        "_hint": "at is the pin's outer end: where a wire or label must land. connectedPins are the other pins on the same wiring of this sheet; nets leaving the sheet continue through power ports and ports (altium_netlist has the compiled nets)."})
}

/// altium_sch_trace_point {sheet, at, toleranceMm?}
pub fn trace_point(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let Some(at) = args.get("at").and_then(pts_arg) else { return bad("at: [x, y] mm is required") };
    let p = (sh.raw(at.0), sh.raw(at.1));
    let tol = sh.raw(args.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.05)).max(1);
    let g = graph(&sh);
    let mut items = Vec::new();
    let mut groups = BTreeSet::new();
    let mut interior_wires = 0;
    for (ni, n) in g.nodes.iter().enumerate() {
        let hit = match n {
            Node::Wire(i) => { let s = segs(&sh.items[*i]); let h = s.iter().map(|(a, b)| on_seg(p, *a, *b, tol)).find(|x| x.0); if let Some((_, inside)) = h { if inside { interior_wires += 1; } true } else { false } }
            Node::Pin(i) => same(sh.pins[*i].at, p, tol),
            Node::Item(i) => { let it = &sh.items[*i]; if it.t == 'P' { port_ends(it).iter().any(|e| same(*e, p, tol)) } else { same(it.at, p, tol) } }
            Node::Entry(i, e) => { let it = &sh.items[*i]; let (_, side, dist, _) = &it.entries[*e]; same(entry_point(it, *side, *dist), p, tol) }
        };
        if !hit { continue; }
        groups.insert(g.group[ni]);
        let v = match n {
            Node::Wire(i) => json!({"kind": "wire", "id": id_of(&sh.items[*i].key), "at": sh.pt(p)}),
            Node::Pin(i) => json!({"kind": "pin", "id": format!("{}.{}", sh.pins[*i].r, sh.pins[*i].num), "at": sh.pt(sh.pins[*i].at)}),
            Node::Item(i) => json!({"kind": kind_name(sh.items[*i].t), "id": id_of(&sh.items[*i].key), "at": sh.pt(sh.items[*i].at), "text": sh.items[*i].text}),
            Node::Entry(i, e) => json!({"kind": "sheetPin", "id": format!("{}/{}", id_of(&sh.items[*i].key), sh.items[*i].entries[*e].0), "at": sh.pt(p)}),
        };
        items.push(v);
    }
    let has_junction = sh.items.iter().any(|it| it.t == 'J' && same(it.at, p, tol));
    let all = nets(&sh, &g);
    // map groups to their nets by a member pin/label, simplest by recomputing per group
    let mut out_nets = Vec::new();
    for gr in &groups {
        let members: Vec<usize> = (0..g.nodes.len()).filter(|i| g.group[*i] == *gr).collect();
        let pins: Vec<String> = members.iter().filter_map(|i| if let Node::Pin(j) = g.nodes[*i] { Some(format!("{}.{}", sh.pins[j].r, sh.pins[j].num)) } else { None }).collect();
        let wires: Vec<String> = members.iter().filter_map(|i| if let Node::Wire(j) = g.nodes[*i] { Some(id_of(&sh.items[j].key)) } else { None }).collect();
        if let Some(n) = all.iter().find(|n| n["wires"].as_array().map(|a| a.iter().any(|w| wires.contains(&st(w)))).unwrap_or(false) || n["pins"].as_array().map(|a| a.iter().any(|x| pins.contains(&st(x)))).unwrap_or(false)) {
            out_nets.push(n.clone());
        }
    }
    let mut r = json!({"success": true, "sheet": sheet, "units": "mm", "items": items, "nets": out_nets,
        "crossingWithoutJunction": interior_wires >= 2 && !has_junction,
        "_hint": "One sheet only: a net with leavesSheet:true continues through a power port, port or sheet entry (altium_netlist gives the compiled net). crossingWithoutJunction: two wires cross here without joining; add a dot with altium_sch_junction if they should."});
    if items.is_empty() {
        // the nearest connectable point
        let mut best: Option<(f64, P)> = None;
        let mut cand: Vec<P> = sh.pins.iter().map(|p| p.at).collect();
        for it in &sh.items { match it.t { 'W' => { cand.extend(it.pts.iter().cloned()); } 'N' | 'O' | 'J' | 'X' => cand.push(it.at), 'P' => cand.extend(port_ends(it)), _ => {} } }
        for c in cand { let d = (((c.0 - p.0) as f64).powi(2) + ((c.1 - p.1) as f64).powi(2)).sqrt(); if best.map(|b| d < b.0).unwrap_or(true) { best = Some((d, c)); } }
        if let Some((_, c)) = best { r["nearest"] = sh.pt(c); }
    }
    r
}

/// How many wiring arms meet at a point: a wire end counts one, a wire passing through counts two, a pin one.
fn arms(sh: &Sheet, p: P) -> usize {
    let tol = sh.tol();
    let mut n = 0;
    for it in sh.items.iter().filter(|it| it.t == 'W') {
        for (a, b) in segs(it) {
            let (on, inside) = on_seg(p, a, b, tol);
            if inside { n += 2; } else if on && (same(a, p, tol) || same(b, p, tol)) { n += 1; }
        }
        // an inner vertex of a polyline was counted twice (end of one segment, start of the next): one arm each, right
    }
    n + sh.pins.iter().filter(|q| same(q.at, p, tol)).count()
}

/// altium_sch_junction {sheet, points?, remove?, dryRun, save}
pub fn junction(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let tol = sh.tol();
    let mut ops = Vec::new();
    let (mut planned, mut skipped, mut not_needed, mut removed) = (vec![], vec![], vec![], vec![]);
    for v in args.get("points").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let Some(m) = pts_arg(&v) else { return bad("points: [[x, y], ...] mm") };
        let p = (sh.raw(m.0), sh.raw(m.1));
        if sh.items.iter().any(|it| it.t == 'J' && same(it.at, p, tol)) { skipped.push(sh.pt(p)); continue; }
        if arms(&sh, p) < 3 { not_needed.push(sh.pt(p)); }
        ops.push(format!("J|{}|{}", p.0, p.1));
        planned.push(sh.pt(p));
    }
    for v in args.get("remove").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let hit = if let Some(id) = v.as_str() { by_id(&sh, id).filter(|(_, it)| it.t == 'J').map(|(_, it)| it) }
            else { pts_arg(&v).and_then(|m| { let p = (sh.raw(m.0), sh.raw(m.1)); sh.items.iter().find(|it| it.t == 'J' && same(it.at, p, tol)) }) };
        match hit { Some(it) => { ops.push(format!("D|{}", it.key)); removed.push(json!(id_of(&it.key))); } None => return json!({"success": false, "errorCode": "not_found", "error": format!("no junction {v}")}) }
    }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "add": planned, "removed": removed, "skipped": skipped, "notNeeded": not_needed}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res[..planned.len().min(res.len())]);
    let added: Vec<Value> = ids.iter().zip(planned.iter()).map(|(i, a)| json!({"id": i, "at": a})).collect();
    let bad_steps = failed(&res);
    json!({"success": bad_steps.is_empty(), "sheet": sheet, "added": added, "removed": removed, "skipped": skipped, "notNeeded": not_needed, "failed": bad_steps, "saved": maybe_save(args, &sheet),
        "_hint": "notNeeded dots are legal but join nothing extra (fewer than three wiring arms meet there)."})
}

/// altium_sch_bus {sheet, points, label?, dryRun, save}
pub fn bus(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let pts: Vec<P> = args.get("points").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().filter_map(pts_arg).map(|m| (sh.raw(m.0), sh.raw(m.1))).collect();
    if pts.len() < 2 { return bad("points: at least two [x, y] mm"); }
    let mut ops = vec![format!("B|{}", raw_pts(&sh, &pts))];
    let label = args.get("label").and_then(|v| v.as_str()).map(clean);
    if let Some(l) = &label { ops.push(format!("N|{l}|{}|{}|{}|", pts[0].0, pts[0].1, if pts[0].0 == pts[1].0 { 1 } else { 0 })); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "points": pts.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>(), "label": label}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res);
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "ids": ids.first().cloned().into_iter().collect::<Vec<_>>(),
        "label": label.map(|t| json!({"id": ids.get(1).cloned(), "text": t})), "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Altium draws a bus as one polyline (one id). A bus carries the nets its label names; each member wire needs its own label: altium_sch_connect_to_bus does the wires, entries and labels."})
}

fn on_bus(sh: &Sheet, p: P) -> bool { let tol = sh.tol(); sh.items.iter().filter(|it| it.t == 'B').any(|b| segs(b).iter().any(|(x, y)| on_seg(p, *x, *y, tol).0)) }

/// altium_sch_bus_entry {sheet, entries:[{at, direction}], dryRun, save}
pub fn bus_entry(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let step = sh.raw(2.54);
    let mut ops = Vec::new();
    let mut plan = Vec::new();
    for e in args.get("entries").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let Some(m) = e.get("at").and_then(pts_arg) else { return bad("entries: [{at: [x, y] mm, direction}]") };
        let a = (sh.raw(m.0), sh.raw(m.1));
        let (sx, sy) = match e.get("direction").and_then(|v| v.as_str()).unwrap_or("down-right") {
            "up-right" => (1, 1), "down-right" => (1, -1), "up-left" => (-1, 1), "down-left" => (-1, -1),
            o => return bad(format!("direction {o}: up-right, down-right, up-left or down-left")),
        };
        let end = (a.0 + sx * step, a.1 + sy * step);
        ops.push(format!("E|{}|{}|{}|{}", a.0, a.1, end.0, end.1));
        plan.push((a, end));
    }
    if plan.is_empty() { return bad("entries is required"); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "entries": plan.iter().map(|(a, e)| json!({"at": sh.pt(*a), "end": sh.pt(*e), "onBus": on_bus(&sh, *e)})).collect::<Vec<_>>()}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res);
    let added: Vec<Value> = plan.iter().zip(ids.iter()).map(|((a, e), id)| json!({"id": id, "at": sh.pt(*a), "end": sh.pt(*e), "onBus": on_bus(&sh, *e)})).collect();
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "added": added, "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "end is the bus side (2.54 mm diagonal). An entry whose end is not on a bus (onBus false) is unconnected in ERC: move it or extend the bus with altium_sch_bus."})
}

/// Split a polyline at p on segment s: (first half, second half).
pub fn split_at(pts: &[P], s: usize, p: P) -> (Vec<P>, Vec<P>) {
    let mut a: Vec<P> = pts[..=s].to_vec(); a.push(p);
    let mut b = vec![p]; b.extend_from_slice(&pts[s + 1..]);
    (a, b)
}

/// altium_sch_split_wire {sheet, at, id?, junction?, dryRun, save}
pub fn split_wire(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let Some(m) = args.get("at").and_then(pts_arg) else { return bad("at: [x, y] mm is required") };
    let p = (sh.raw(m.0), sh.raw(m.1));
    let tol = sh.tol();
    let want = args.get("id").and_then(|v| v.as_str());
    let mut hits = Vec::new();
    for it in sh.items.iter().filter(|it| it.t == 'W' && want.map(|w| id_of(&it.key) == w).unwrap_or(true)) {
        let n = it.pts.len();
        if same(it.pts[0], p, tol) || same(it.pts[n - 1], p, tol) { continue; }
        if let Some(s) = segs(it).iter().position(|(a, b)| on_seg(p, *a, *b, tol).0) { hits.push((it, s)); }
    }
    let (it, s) = match hits.len() {
        0 => return json!({"success": false, "errorCode": "not_on_wire", "error": "no wire passes through that point (an end does not count: a branch can end on a wire end already)"}),
        1 => hits[0],
        _ => return json!({"success": false, "errorCode": "ambiguous", "error": "several wires pass through that point: give id", "ids": hits.iter().map(|(i, _)| id_of(&i.key)).collect::<Vec<_>>()}),
    };
    let (a, b) = split_at(&it.pts, s, p);
    let jn = args.get("junction").and_then(|v| v.as_bool()) != Some(false);
    let mut ops = vec![format!("V|{}|{}", it.key, raw_pts(&sh, &a)), format!("W|{}", raw_pts(&sh, &b))];
    if jn { ops.push(format!("J|{}|{}", p.0, p.1)); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "first": a.iter().map(|q| sh.pt(*q)).collect::<Vec<_>>(), "second": b.iter().map(|q| sh.pt(*q)).collect::<Vec<_>>()}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res);
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "ids": ids.iter().take(2).collect::<Vec<_>>(), "junction": if jn { json!({"id": ids.get(2), "at": sh.pt(p)}) } else { Value::Null },
        "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Both halves get new ids (Altium ids follow geometry). Wire the new branch to the cut point."})
}

/// altium_sch_delete_wire {sheet, ids?, from?+to?, at?, dryRun, save}
pub fn delete_wire(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let tol = sh.tol();
    let mut dead: Vec<usize> = Vec::new();
    for v in args.get("ids").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        match v.as_str().and_then(|id| by_id(&sh, id)) { Some((i, it)) if matches!(it.t, 'W' | 'B') => dead.push(i), _ => return json!({"success": false, "errorCode": "not_found", "error": format!("no wire or bus {v}: read ids with altium_sch_items")}) }
    }
    if let (Some(f), Some(t)) = (args.get("from").and_then(pts_arg), args.get("to").and_then(pts_arg)) {
        let (f, t) = ((sh.raw(f.0), sh.raw(f.1)), (sh.raw(t.0), sh.raw(t.1)));
        let hit = sh.items.iter().position(|it| matches!(it.t, 'W' | 'B') && { let (a, b) = (it.pts[0], it.pts[it.pts.len() - 1]); (same(a, f, tol) && same(b, t, tol)) || (same(a, t, tol) && same(b, f, tol)) });
        match hit { Some(i) => dead.push(i), None => return json!({"success": false, "errorCode": "not_found", "error": "no wire with exactly those two ends"}) }
    }
    if let Some(a) = args.get("at").and_then(pts_arg) {
        let p = (sh.raw(a.0), sh.raw(a.1));
        dead.extend(sh.items.iter().enumerate().filter(|(_, it)| matches!(it.t, 'W' | 'B') && segs(it).iter().any(|(x, y)| on_seg(p, *x, *y, tol).0)).map(|(i, _)| i));
    }
    dead.sort(); dead.dedup();
    if dead.is_empty() { return bad("give ids, from and to, or at"); }
    // junctions that no longer join three or more arms once these wires are gone
    let mut after = sh.clone();
    after.items = sh.items.iter().enumerate().filter(|(i, _)| !dead.contains(i)).map(|(_, it)| it.clone()).collect();
    // only dots that sat on a deleted wire: a dot left for a future branch elsewhere stays
    let on_dead = |p: P| dead.iter().any(|i| segs(&sh.items[*i]).iter().any(|(a, b)| on_seg(p, *a, *b, tol).0));
    let orphan: Vec<&Item> = after.items.iter().filter(|it| it.t == 'J' && on_dead(it.at) && arms(&after, it.at) < 3).collect();
    let mut ops: Vec<String> = dead.iter().map(|i| format!("D|{}", sh.items[*i].key)).collect();
    ops.extend(orphan.iter().map(|j| format!("D|{}", j.key)));
    let deleted: Vec<Value> = dead.iter().map(|i| { let it = &sh.items[*i]; json!({"id": id_of(&it.key), "from": sh.pt(it.pts[0]), "to": sh.pt(it.pts[it.pts.len() - 1])}) }).collect();
    let jr: Vec<Value> = orphan.iter().map(|j| sh.pt(j.at)).collect();
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "deleted": deleted, "junctionsRemoved": jr}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "deleted": deleted, "junctionsRemoved": jr, "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "An Altium wire is one polyline: deleting it removes all its segments. To cut one segment out, split it first (altium_sch_split_wire)."})
}

/// altium_sch_edit_label {sheet, edits:[{id | text (+at) | net, rotation?, to?, by?, rename?}], dryRun, save}
pub fn edit_label(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let tol = sh.tol();
    let mut ops = Vec::new();
    let mut plan = Vec::new();
    let mut failed_edits = Vec::new();
    for e in args.get("edits").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let picked: Vec<&Item> = if let Some(id) = e.get("id").and_then(|v| v.as_str()) {
            by_id(&sh, id).map(|(_, it)| it).filter(|it| it.t == 'N').into_iter().collect()
        } else if let Some(t) = e.get("text").and_then(|v| v.as_str()) {
            let at = e.get("at").and_then(pts_arg).map(|m| (sh.raw(m.0), sh.raw(m.1)));
            sh.items.iter().filter(|it| it.t == 'N' && it.text == t && at.map(|a| same(a, it.at, tol)).unwrap_or(true)).collect()
        } else if let Some(n) = e.get("net").and_then(|v| v.as_str()) {
            sh.items.iter().filter(|it| it.t == 'N' && it.text.eq_ignore_ascii_case(n)).collect()
        } else { vec![] };
        if picked.is_empty() { failed_edits.push(json!({"edit": e, "error": "no label matches"})); continue; }
        if e.get("to").is_some() && picked.len() > 1 { failed_edits.push(json!({"edit": e, "error": "to moves one label only; use by for several"})); continue; }
        for it in picked {
            let mut at = it.at;
            if let Some(m) = e.get("to").and_then(pts_arg) { at = (sh.raw(m.0), sh.raw(m.1)); }
            if let Some(m) = e.get("by").and_then(pts_arg) { at = (at.0 + sh.raw(m.0), at.1 + sh.raw(m.1)); }
            let rot = e.get("rotation").and_then(|v| v.as_i64()).map(|r| ((r.rem_euclid(360)) / 90).to_string()).unwrap_or_default();
            let text = e.get("rename").and_then(|v| v.as_str()).map(clean).unwrap_or_default();
            ops.push(format!("L|{}|{}|{}|{}|{}", it.key, text, at.0, at.1, rot));
            plan.push(json!({"was": id_of(&it.key), "text": if text.is_empty() { it.text.clone() } else { text.clone() }, "at": sh.pt(at),
                "rotation": if rot.is_empty() { it.rot * 90 } else { rot.parse::<i64>().unwrap_or(0) * 90 }}));
        }
    }
    if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no edit matched a label", "failed": failed_edits}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "edited": plan, "failed": failed_edits}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res);
    let edited: Vec<Value> = plan.into_iter().zip(ids).map(|(mut p, id)| { p["id"] = id; p }).collect();
    let fails = failed(&res);
    json!({"success": fails.is_empty() && failed_edits.is_empty(), "sheet": sheet, "edited": edited, "failed": failed_edits, "stepsFailed": fails, "saved": maybe_save(args, &sheet),
        "_hint": "A label renamed joins the net of its new name across the sheet; a label moved off its wire stops naming it: check with altium_sch_pins or altium_compile."})
}

/// Altium's text justification from "left bottom" style words.
pub fn justification(s: &str) -> i64 {
    let w = s.to_lowercase();
    let h = if w.contains("right") { 2 } else if w.contains("center") || w.contains("centre") { 1 } else { 0 };
    let v = if w.contains("top") { 2 } else if w.contains("middle") || (w.contains("center") && !w.contains("left") && !w.contains("right") && w.split_whitespace().count() > 1) { 1 } else { 0 };
    v * 3 + h
}

/// altium_sch_text {sheet, texts:[{text, at, rotation?, sizeMm?, justify?, bold?, italic?}], dryRun, save}
pub fn text(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let mut ops = Vec::new();
    let mut plan = Vec::new();
    for t in args.get("texts").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let Some(m) = t.get("at").and_then(pts_arg) else { return bad("texts: [{text, at: [x, y] mm, ...}]") };
        let s = clean(&st(&t["text"]));
        if s.is_empty() { return bad("each text needs text"); }
        let at = (sh.raw(m.0), sh.raw(m.1));
        // Altium sizes text in points: 10 pt is about 2.54 mm tall
        let pt = ((t.get("sizeMm").and_then(|v| v.as_f64()).unwrap_or(1.27) / 2.54 * 10.0).round() as i64).max(1);
        let rot = t.get("rotation").and_then(|v| v.as_i64()).unwrap_or(0).rem_euclid(360) / 90;
        let b = |k: &str| if t.get(k).and_then(|v| v.as_bool()) == Some(true) { "1" } else { "0" };
        let j = t.get("justify").and_then(|v| v.as_str()).map(|s| justification(s).to_string()).unwrap_or_default();
        ops.push(format!("T|{s}|{}|{}|{rot}|{pt}|{}|{}|{j}", at.0, at.1, b("bold"), b("italic")));
        plan.push(json!({"text": s, "at": sh.pt(at)}));
    }
    if plan.is_empty() { return bad("texts is required"); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "added": plan}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let added: Vec<Value> = plan.into_iter().zip(new_ids(&res)).map(|(mut p, id)| { p["id"] = id; p }).collect();
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "added": added, "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Free text has no electrical meaning: net names are labels (altium_sch_connect). Altium's text is one line; sizes are converted to points (10 pt is about 2.54 mm)."})
}

fn pin_of<'a>(sh: &'a Sheet, key: &str) -> Option<&'a Pin> {
    let (r, n) = key.rsplit_once('.')?;
    sh.pins.iter().find(|p| p.r.eq_ignore_ascii_case(r) && p.num.eq_ignore_ascii_case(n))
        .or_else(|| sh.pins.iter().find(|p| p.r.eq_ignore_ascii_case(r) && p.name.eq_ignore_ascii_case(n)))
}

/// An orthogonal route from a to b through waypoints: straight when aligned, else one turn per leg; the first leg
/// along h (horizontal) or v.
pub fn route(a: P, b: P, via: &[P], first_h: bool) -> Vec<P> {
    let mut pts = vec![a];
    let mut cur = a;
    let mut h = first_h;
    for &t in via.iter().chain(std::iter::once(&b)) {
        if cur.0 != t.0 && cur.1 != t.1 { let corner = if h { (t.0, cur.1) } else { (cur.0, t.1) }; pts.push(corner); }
        pts.push(t);
        h = !h;
        cur = t;
    }
    pts.dedup();
    pts
}

/// Where existing wires' ends land in the middle of the new route, or the route's ends land in the middle of an
/// existing wire: a T, which wants a junction dot.
pub fn tees(sh: &Sheet, route: &[P]) -> Vec<P> {
    let tol = sh.tol();
    let mut out = Vec::new();
    let rs: Vec<(P, P)> = route.windows(2).map(|w| (w[0], w[1])).collect();
    for it in sh.items.iter().filter(|it| it.t == 'W') {
        for e in [it.pts[0], it.pts[it.pts.len() - 1]] { if rs.iter().any(|(a, b)| on_seg(e, *a, *b, tol).1) { out.push(e); } }
        for e in [route[0], route[route.len() - 1]] { if segs(it).iter().any(|(a, b)| on_seg(e, *a, *b, tol).1) { out.push(e); } }
    }
    out.sort(); out.dedup();
    out
}

/// A point on the sheet: [x, y] mm, or a pin's outer end ("U1.3").
fn point_or_pin(sh: &Sheet, v: &Value) -> Option<P> {
    if let Some(key) = v.as_str() { return pin_of(sh, key).map(|p| p.at); }
    pts_arg(v).map(|m| (sh.raw(m.0), sh.raw(m.1)))
}

/// Does a wire pass through the point, or a pin end sit on it? Then a marker or label there means something.
fn touches(sh: &Sheet, p: P) -> bool {
    let tol = sh.tol();
    sh.pins.iter().any(|q| same(q.at, p, tol)) || sh.items.iter().filter(|it| it.t == 'W').any(|w| segs(w).iter().any(|(a, b)| on_seg(p, *a, *b, tol).0))
}

/// The standard's `remove`: true with `id`, or with `at`/`points`/`pin`/`pins`; or a list of ids and points. Items of the kinds in `ts`.
fn removals(sh: &Sheet, ts: &[char], what: &str, args: &Value) -> Result<(Vec<String>, Vec<Value>), Value> {
    let tol = sh.tol();
    let mut wanted: Vec<Value> = args.get("remove").and_then(|v| v.as_array()).cloned().unwrap_or_default();
    if args.get("remove").and_then(|v| v.as_bool()) == Some(true) {
        if let Some(i) = args.get("id") { wanted.push(i.clone()); }
        wanted.extend(where_args(args));
        if wanted.is_empty() { return Err(bad(format!("remove needs the {what}'s id, or where it is"))); }
    }
    let (mut ops, mut ids) = (Vec::new(), Vec::new());
    for v in wanted {
        let hit = if let Some(id) = v.as_str().filter(|x| by_id(sh, x).is_some()) { by_id(sh, id).filter(|(_, it)| ts.contains(&it.t)).map(|(_, it)| it) }
            else { point_or_pin(sh, &v).and_then(|p| sh.items.iter().find(|it| ts.contains(&it.t) && (same(it.at, p, tol) || (it.t == 'P' && port_ends(it).iter().any(|e| same(*e, p, tol)))))) };
        match hit { Some(it) => { ops.push(format!("D|{}", it.key)); ids.push(json!(id_of(&it.key))); } None => return Err(json!({"success": false, "errorCode": "not_found", "error": format!("no {what} {v}: read ids with altium_sch_items")})) }
    }
    Ok((ops, ids))
}

/// The points and pins an edit names: at, points, pin, pins. Pure.
fn where_args(args: &Value) -> Vec<Value> {
    let mut out = Vec::new();
    if let Some(a) = args.get("at") { out.push(a.clone()); }
    if let Some(p) = args.get("points").and_then(|v| v.as_array()) { out.extend(p.iter().cloned()); }
    if let Some(a) = args.get("pin") { out.push(a.clone()); }
    if let Some(p) = args.get("pins").and_then(|v| v.as_array()) { out.extend(p.iter().cloned()); }
    out
}

/// altium_sch_no_connect {sheet, at | points | pin | pins, remove?, id?, dryRun, save}
pub fn no_connect(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let tol = sh.tol();
    let (mut ops, mut planned, mut skipped, mut on_nothing, mut bad_items) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
    let removing = args.get("remove").and_then(|v| v.as_bool()) == Some(true);
    if !removing {
        for v in where_args(args) {
            let Some(p) = point_or_pin(&sh, &v) else { bad_items.push(json!({"item": v, "error": "not [x, y] mm, or that pin is not on this sheet"})); continue; };
            if sh.items.iter().any(|it| it.t == 'X' && same(it.at, p, tol)) { skipped.push(sh.pt(p)); continue; }
            if !touches(&sh, p) { on_nothing.push(sh.pt(p)); }
            ops.push(format!("X|{}|{}", p.0, p.1));
            planned.push(sh.pt(p));
        }
    }
    let (rem, removed) = match removals(&sh, &['X'], "no-connect marker", args) { Ok(x) => x, Err(e) => return e };
    ops.extend(rem);
    if planned.is_empty() && removed.is_empty() && skipped.is_empty() { return json!({"success": false, "errorCode": "bad_args", "error": "give at, points, pin or pins to flag; remove with id or a place", "failed": bad_items}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "add": planned, "removed": removed, "skipped": skipped, "onNothing": on_nothing, "failed": bad_items}); }
    if ops.is_empty() { return json!({"success": bad_items.is_empty(), "sheet": sheet, "added": [], "removed": [], "skipped": skipped, "onNothing": [], "failed": bad_items, "mutated": false}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res[..planned.len().min(res.len())]);
    let added: Vec<Value> = ids.iter().zip(planned.iter()).map(|(i, a)| json!({"id": i, "at": a})).collect();
    let mut fails = failed(&res);
    fails.extend(bad_items);
    json!({"success": fails.is_empty(), "sheet": sheet, "added": added, "removed": removed, "skipped": skipped, "onNothing": on_nothing, "failed": fails, "saved": maybe_save(args, &sheet),
        "_hint": "Altium's No ERC marker: ERC says nothing about a pin or wire end left open under one. onNothing lists markers placed where no pin end or wire is: they flag nothing."})
}

/// The op for one label, by its kind: local is Altium's net label, global its power port, hierarchical its port. Pure.
pub fn label_op(kind: &str, text: &str, p: P, rot: i64, just: &str) -> Result<String, String> {
    match kind {
        "local" => Ok(format!("N|{text}|{}|{}|{rot}|{just}", p.0, p.1)),
        "global" => Ok(format!("O|{text}|{}|{}|{rot}", p.0, p.1)),
        "hierarchical" => Ok(format!("P|{text}|{}|{}|{}", p.0, p.1, if rot == 2 { 1 } else { 0 })),
        o => Err(format!("kind is local, global or hierarchical (got {o})")),
    }
}

/// altium_sch_label {sheet, text | net, at, kind?, rotation?, justify?, remove?, id?, labels?: [...], dryRun, save}
pub fn label(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let removing = args.get("remove").and_then(|v| v.as_bool()) == Some(true);
    // one label at the top level, as the standard has it, or several in labels
    let mut list: Vec<Value> = args.get("labels").and_then(|v| v.as_array()).cloned().unwrap_or_default();
    if !removing && (args.get("text").is_some() || args.get("net").is_some()) { list.insert(0, args.clone()); }
    let (mut ops, mut planned, mut off_wire) = (Vec::new(), Vec::new(), Vec::new());
    for l in list {
        let Some(text) = l.get("text").or(l.get("net")).and_then(|v| v.as_str()).map(clean).filter(|t| !t.is_empty()) else { return bad("every label needs text (its net's name)") };
        let Some(p) = l.get("at").and_then(|v| point_or_pin(&sh, v)) else { return bad(format!("label {text}: at is [x, y] mm or a pin (U1.3) on this sheet")) };
        let rot = l.get("rotation").and_then(|v| v.as_i64()).unwrap_or(0).rem_euclid(360) / 90;
        let just = l.get("justify").and_then(|v| v.as_str()).map(|j| justification(j).to_string()).unwrap_or_default();
        let kind = l.get("kind").and_then(|v| v.as_str()).unwrap_or("local").to_ascii_lowercase();
        match label_op(&kind, &text, p, rot, &just) { Ok(op) => ops.push(op), Err(e) => return bad(e) }
        if !touches(&sh, p) { off_wire.push(json!({"text": text, "at": sh.pt(p)})); }
        planned.push(json!({"text": text, "kind": kind, "at": sh.pt(p), "rotation": rot * 90}));
    }
    // by text with at, as the standard allows, or by id or place
    let mut by_text = Vec::new();
    if removing && args.get("id").is_none() {
        if let (Some(t), Some(p)) = (args.get("text").and_then(|v| v.as_str()), args.get("at").and_then(|v| point_or_pin(&sh, v))) {
            let tol = sh.tol();
            match sh.items.iter().find(|it| matches!(it.t, 'N' | 'O' | 'P') && it.text == t && same(it.at, p, tol)) {
                Some(it) => by_text.push(it),
                None => return json!({"success": false, "errorCode": "not_found", "error": format!("no label {t} at that point")}),
            }
        }
    }
    let (rem, mut removed) = if by_text.is_empty() { match removals(&sh, &['N', 'O', 'P'], "label", args) { Ok(x) => x, Err(e) => return e } } else { (by_text.iter().map(|it| format!("D|{}", it.key)).collect(), by_text.iter().map(|it| json!(id_of(&it.key))).collect()) };
    ops.extend(rem);
    removed.dedup();
    if ops.is_empty() { return bad("give text and at to add a label, or remove with id"); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "add": planned, "removed": removed, "offWire": off_wire}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res[..planned.len().min(res.len())]);
    let added: Vec<Value> = planned.into_iter().zip(ids).map(|(mut a, id)| { a["id"] = id; a }).collect();
    let fails = failed(&res);
    json!({"success": fails.is_empty(), "sheet": sheet, "label": added.first().cloned(), "added": added, "removed": removed, "offWire": off_wire, "failed": fails, "saved": maybe_save(args, &sheet),
        "_hint": "local is Altium's net label, joining the same text on this sheet; global its power port, joining across sheets; hierarchical its port, joining through a sheet entry. offWire lists labels with no wire or pin end under them: they name nothing yet. sch_edit_label moves or renames net labels."})
}

/// altium_sch_wire {sheet, points | wires:[{points}], junctions?, dryRun, save}
pub fn wire(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let lists: Vec<Value> = match args.get("wires").and_then(|v| v.as_array()) {
        Some(w) => w.iter().map(|x| x["points"].clone()).collect(),
        None => vec![args.get("points").cloned().unwrap_or(Value::Null)],
    };
    let (mut ops, mut routes, mut dots) = (Vec::new(), Vec::new(), Vec::<P>::new());
    let want_dots = args.get("junctions").and_then(|v| v.as_bool()).unwrap_or(true);
    for l in lists {
        let Some(a) = l.as_array() else { return bad("points: at least two [x, y] mm or pins (U1.3); wires: [{points}] for several") };
        let mut pts = Vec::new();
        for v in a { match point_or_pin(&sh, v) { Some(p) => pts.push(p), None => return bad(format!("{v} is not [x, y] mm or a pin on this sheet")) } }
        pts.dedup();
        if pts.len() < 2 { return bad("a wire needs at least two different points"); }
        if want_dots { dots.extend(tees(&sh, &pts)); }
        ops.push(format!("W|{}", raw_pts(&sh, &pts)));
        routes.push(pts);
    }
    dots.sort(); dots.dedup();
    let n = ops.len();
    ops.extend(dots.iter().map(|p| format!("J|{}|{}", p.0, p.1)));
    let plain: Vec<Value> = routes.iter().map(|r| json!(r.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>())).collect();
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "routes": plain, "junctionsAdded": dots.iter().map(|p| json!({"at": sh.pt(*p)})).collect::<Vec<_>>()}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res[..n.min(res.len())]);
    // one row per segment, as the standard has it; an Altium wire is one polyline, so its segments share an id
    let mut rows = Vec::new();
    for (r, id) in routes.iter().zip(ids.iter()) { for w in r.windows(2) { rows.push(json!({"id": id, "from": sh.pt(w[0]), "to": sh.pt(w[1])})); } }
    let jids = new_ids(&res[n.min(res.len())..]);
    let added: Vec<Value> = dots.iter().zip(jids.iter()).map(|(p, id)| json!({"id": id, "at": sh.pt(*p)})).collect();
    let fails = failed(&res);
    json!({"success": fails.is_empty(), "sheet": sheet, "wires": rows, "junctionsAdded": added, "failed": fails, "saved": maybe_save(args, &sheet),
        "_hint": "One row per segment; an Altium wire is one polyline through exactly the points given, so a wire's segments share its id. It doesn't avoid bodies or other wires: a leg along another wire merges the nets. Check with altium_sch_pins or altium_compile."})
}

/// altium_sch_connect_pins {sheet, pairs:[{from, to, first?, via?}], dryRun, save}
pub fn connect_pins(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let mut ops = Vec::new();
    let mut routes = Vec::new();
    let mut fails = Vec::new();
    let mut dots: Vec<P> = Vec::new();
    for pr in args.get("pairs").and_then(|v| v.as_array()).cloned().unwrap_or_default() {
        let (f, t) = (st(&pr["from"]), st(&pr["to"]));
        let (Some(a), Some(b)) = (pin_of(&sh, &f), pin_of(&sh, &t)) else { fails.push(json!({"from": f, "to": t, "error": "pin not found on this sheet (Ref.Pin, by number then name)"})); continue; };
        let first_h = match pr.get("first").and_then(|v| v.as_str()) { Some("h") => true, Some("v") => false, _ => a.dir % 2 == 0 };
        let via: Vec<P> = pr.get("via").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().filter_map(pts_arg).map(|m| (sh.raw(m.0), sh.raw(m.1))).collect();
        let r = route(a.at, b.at, &via, first_h);
        dots.extend(tees(&sh, &r));
        ops.push(format!("W|{}", raw_pts(&sh, &r)));
        routes.push(json!({"from": f, "to": t, "points": r.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>()}));
    }
    dots.sort(); dots.dedup();
    let n_routes = ops.len();
    ops.extend(dots.iter().map(|p| format!("J|{}|{}", p.0, p.1)));
    if routes.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no pair could be wired", "failed": fails}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "routes": routes, "junctionsAdded": dots.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>(), "failed": fails}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res[..n_routes.min(res.len())]);
    let routes: Vec<Value> = routes.into_iter().zip(ids).map(|(mut r, id)| { r["ids"] = json!([id]); r }).collect();
    json!({"success": fails.is_empty() && failed(&res).is_empty(), "sheet": sheet, "wired": routes.len(), "routes": routes,
        "junctionsAdded": dots.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>(), "failed": fails, "stepsFailed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Each route is one Altium wire (a polyline). Routes do not avoid bodies or other wires: a leg along another wire merges the nets. Check with altium_sch_pins (connectedPins) or altium_compile."})
}

/// altium_sch_connect_to_bus {sheet, pins, bus?, members? | prefix+start, entry?, busLabel?, dryRun, save}
pub fn connect_to_bus(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let buses: Vec<&Item> = sh.items.iter().filter(|it| it.t == 'B').collect();
    let bus = match args.get("bus").and_then(|v| v.as_str()) {
        Some(id) => match by_id(&sh, id) { Some((_, it)) if it.t == 'B' => it, _ => return json!({"success": false, "errorCode": "not_found", "error": format!("no bus {id}")}) },
        None if buses.len() == 1 => buses[0],
        None => return json!({"success": false, "errorCode": if buses.is_empty() { "no_bus" } else { "ambiguous" }, "error": if buses.is_empty() { "no bus on this sheet: draw one with altium_sch_bus" } else { "several buses: give bus (an id from altium_sch_items)" }}),
    };
    let pins: Vec<String> = args.get("pins").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().map(st).collect();
    if pins.is_empty() { return bad("pins: [\"U1.1\", ...] in member order"); }
    let members: Vec<String> = match args.get("members").and_then(|v| v.as_array()) {
        Some(m) => m.iter().map(|x| clean(&st(x))).collect(),
        None => { let pre = args.get("prefix").and_then(|v| v.as_str()).unwrap_or("D"); let s0 = args.get("start").and_then(|v| v.as_i64()).unwrap_or(0); (0..pins.len()).map(|i| format!("{pre}{}", s0 + i as i64)).collect() }
    };
    if members.len() != pins.len() { return bad("members must name one member per pin"); }
    let step = sh.raw(2.54);
    let tol = sh.tol();
    let mut ops = Vec::new();
    let mut plan = Vec::new();
    let mut fails = Vec::new();
    for (k, key) in pins.iter().enumerate() {
        let Some(p) = pin_of(&sh, key) else { fails.push(json!({"pin": key, "error": "pin not found"})); continue; };
        // the bus segment beside the pin: a vertical one spanning its height or a horizontal one spanning its x
        let seg = segs(bus).into_iter().find(|(a, b)| (a.0 == b.0 && p.at.1 >= a.1.min(b.1) - step && p.at.1 <= a.1.max(b.1) + step) || (a.1 == b.1 && p.at.0 >= a.0.min(b.0) - step && p.at.0 <= a.0.max(b.0) + step));
        let Some((a, b)) = seg else { fails.push(json!({"pin": key, "error": "entry_off_bus: no bus segment beside this pin; extend the bus with altium_sch_bus"})); continue; };
        let vertical = a.0 == b.0;
        let lean = args.get("entry").and_then(|v| v.as_str()).unwrap_or(if vertical { "down" } else { "right" });
        let (wire_end, entry_end) = if vertical {
            let side = if p.at.0 < a.0 { -1 } else { 1 };
            let dy = if lean == "up" { step } else { -step };
            ((a.0 + side * step, p.at.1), (a.0, p.at.1 + dy))
        } else {
            let side = if p.at.1 < a.1 { -1 } else { 1 };
            let dx = if lean == "left" { -step } else { step };
            ((p.at.0, a.1 + side * step), (p.at.0 + dx, a.1))
        };
        if !segs(bus).iter().any(|(x, y)| on_seg(entry_end, *x, *y, tol).0) { fails.push(json!({"pin": key, "error": "entry_off_bus: the entry would miss the bus; extend it with altium_sch_bus"})); continue; }
        let wire = route(p.at, wire_end, &[], vertical);
        ops.push(format!("W|{}", raw_pts(&sh, &wire)));
        ops.push(format!("E|{}|{}|{}|{}", wire_end.0, wire_end.1, entry_end.0, entry_end.1));
        // the member label on the wire, just before the entry
        let lab = wire_end;
        ops.push(format!("N|{}|{}|{}|{}|{}", members[k], lab.0, lab.1, if vertical { 0 } else { 1 }, if vertical && p.at.0 < a.0 { "2" } else { "" }));
        plan.push(json!({"pin": key, "member": members[k], "wire": wire.iter().map(|q| sh.pt(*q)).collect::<Vec<_>>(), "entry": [sh.pt(wire_end), sh.pt(entry_end)]}));
    }
    let bus_label = args.get("busLabel").and_then(|v| v.as_str()).map(clean);
    if let Some(l) = &bus_label { ops.push(format!("N|{l}|{}|{}|{}|", bus.pts[0].0, bus.pts[0].1, if bus.pts[0].0 == bus.pts[1].0 { 1 } else { 0 })); }
    if plan.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no pin could be connected", "failed": fails}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "connected": plan, "busLabel": bus_label, "failed": fails}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let ids = new_ids(&res);
    let connected: Vec<Value> = plan.into_iter().enumerate().map(|(i, mut p)| { p["wireId"] = ids.get(3 * i).cloned().unwrap_or(Value::Null); p["entryId"] = ids.get(3 * i + 1).cloned().unwrap_or(Value::Null); p }).collect();
    json!({"success": fails.is_empty() && failed(&res).is_empty(), "sheet": sheet, "connected": connected, "busLabel": bus_label, "failed": fails, "stepsFailed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Each pin got a wire to 2.54 mm short of the bus, a 45-degree entry onto it and its member label. The bus's own label (busLabel, e.g. D[0..7]) must name every member. Check with altium_compile."})
}

/// altium_sch_move_region {sheet, box, by, wires?, labels?, junctions?, dryRun, save}
pub fn move_region(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let bx: Vec<f64> = args.get("box").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default();
    let Some(by) = args.get("by").and_then(pts_arg) else { return bad("by: [dx, dy] mm is required") };
    if bx.len() != 4 { return bad("box: [x1, y1, x2, y2] mm is required"); }
    let (x0, x1) = (sh.raw(bx[0].min(bx[2])), sh.raw(bx[0].max(bx[2])));
    let (y0, y1) = (sh.raw(bx[1].min(bx[3])), sh.raw(bx[1].max(bx[3])));
    let inside = |p: P| p.0 >= x0 && p.0 <= x1 && p.1 >= y0 && p.1 <= y1;
    let (dx, dy) = (sh.raw(by.0), sh.raw(by.1));
    let flag = |k: &str| args.get(k).and_then(|v| v.as_bool()) != Some(false);
    let mut ops = Vec::new();
    let mut moved: BTreeMap<&str, Vec<Value>> = BTreeMap::new();
    for c in sh.comps.iter().filter(|c| inside(c.at)) { ops.push(format!("C|{}|{dx}|{dy}", c.r)); moved.entry("parts").or_default().push(json!(c.r)); }
    for it in &sh.items {
        let (kind, on) = match it.t { 'W' => ("wires", flag("wires")), 'B' => ("buses", flag("wires")), 'E' => ("busEntries", flag("wires")), 'N' | 'P' | 'O' => ("labels", flag("labels")), 'T' => ("texts", flag("labels")),
            'J' => ("junctions", flag("junctions")), 'X' => ("noConnects", flag("junctions")), 'S' => ("sheets", true), _ => continue };
        if !on { continue; }
        if matches!(it.t, 'W' | 'B') {
            if !it.pts.iter().any(|p| inside(*p)) { continue; }
            let np: Vec<P> = it.pts.iter().map(|p| if inside(*p) { (p.0 + dx, p.1 + dy) } else { *p }).collect();
            ops.push(format!("V|{}|{}", it.key, raw_pts(&sh, &np)));
        } else {
            if !inside(it.at) { continue; }
            ops.push(format!("G|{}|{dx}|{dy}", it.key));
        }
        moved.entry(kind).or_default().push(json!(id_of(&it.key)));
    }
    if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "nothing inside the box"}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "moved": moved}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "moved": moved, "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Ids listed are the items' ids before the move; read new ones with altium_sch_items. Wires with one end inside stretched; move by a pure dx or dy to keep them straight."})
}

/// altium_sch_fix_connectivity {sheet, toleranceMm?, dryRun (default true), save}
pub fn fix_connectivity(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let tol = sh.tol();
    let reach = sh.raw(args.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.5));
    let dry_run = args.get("dryRun").and_then(|v| v.as_bool()) != Some(false);
    // targets a dangling end may snap onto: pins, labels, ports, power, sheet entries, other wires' ends
    let mut targets: Vec<(P, &'static str, String)> = sh.pins.iter().map(|p| (p.at, "pin", format!("{}.{}", p.r, p.num))).collect();
    for it in &sh.items {
        match it.t {
            'N' | 'O' => targets.push((it.at, kind_name(it.t), id_of(&it.key))),
            'P' => for e in port_ends(it) { targets.push((e, "port", id_of(&it.key))) },
            'S' => for (n, side, dist, _) in &it.entries { targets.push((entry_point(it, *side, *dist), "sheetPin", format!("{}/{n}", id_of(&it.key)))) },
            _ => {}
        }
    }
    let mut moves = Vec::new();
    let mut unresolved = Vec::new();
    let mut ops = Vec::new();
    for (wi, w) in sh.items.iter().enumerate().filter(|(_, it)| it.t == 'W') {
        let mut np = w.pts.clone();
        let mut changed = false;
        for end in [0, w.pts.len() - 1] {
            let p = w.pts[end];
            let joined = targets.iter().any(|(q, _, _)| same(*q, p, tol))
                || sh.items.iter().enumerate().any(|(j, o)| j != wi && match o.t { 'W' | 'B' => segs(o).iter().any(|(a, b)| on_seg(p, *a, *b, tol).0), 'J' | 'X' | 'E' => same(o.at, p, tol) || same(o.corner, p, tol), _ => false });
            if joined { continue; }
            let mut best: Option<(f64, P, &str, String)> = None;
            for (q, k, id) in &targets { let d = (((q.0 - p.0) as f64).powi(2) + ((q.1 - p.1) as f64).powi(2)).sqrt(); if d <= reach as f64 && best.as_ref().map(|b| d < b.0).unwrap_or(true) { best = Some((d, *q, k, id.clone())); } }
            for (j, o) in sh.items.iter().enumerate().filter(|(j, o)| *j != wi && o.t == 'W') {
                let _ = j;
                for q in [o.pts[0], o.pts[o.pts.len() - 1]] { let d = (((q.0 - p.0) as f64).powi(2) + ((q.1 - p.1) as f64).powi(2)).sqrt(); if d <= reach as f64 && best.as_ref().map(|b| d < b.0).unwrap_or(true) { best = Some((d, q, "wire", id_of(&o.key))); } }
            }
            match best {
                Some((_, q, k, id)) => {
                    np[end] = q; changed = true;
                    let nb = if end == 0 { np.get(1) } else { np.get(np.len().saturating_sub(2)) }.copied().unwrap_or(q);
                    moves.push(json!({"wireId": id_of(&w.key), "from": sh.pt(p), "to": sh.pt(q), "onto": {"kind": k, "id": id}, "diagonal": nb.0 != q.0 && nb.1 != q.1}));
                }
                None => unresolved.push(sh.pt(p)),
            }
        }
        if changed { ops.push(format!("V|{}|{}", w.key, raw_pts(&sh, &np))); }
    }
    if dry_run || ops.is_empty() { return json!({"success": true, "dryRun": dry_run, "sheet": sheet, "moves": moves, "unresolved": unresolved,
        "_hint": "dryRun defaults to true: read the moves, then call again with dryRun:false. unresolved ends have nothing within toleranceMm."}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    json!({"success": failed(&res).is_empty(), "sheet": sheet, "moves": moves, "unresolved": unresolved, "failed": failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Snapped ends now touch their targets; diagonal:true wires are no longer horizontal or vertical. Check with altium_compile."})
}

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

    #[test]
    fn a_labels_kind_picks_altiums_object() {
        assert_eq!(label_op("local", "SDA", (1, 2), 0, "").unwrap(), "N|SDA|1|2|0|");
        assert_eq!(label_op("global", "VBUS", (1, 2), 1, "").unwrap(), "O|VBUS|1|2|1");
        assert_eq!(label_op("hierarchical", "IO", (1, 2), 2, "").unwrap(), "P|IO|1|2|1", "turned 180, the port's far end is at the point");
        assert_eq!(label_op("hierarchical", "IO", (1, 2), 0, "").unwrap(), "P|IO|1|2|0");
        assert!(label_op("sideways", "X", (0, 0), 0, "").is_err());
    }

    #[test]
    fn the_places_an_edit_names() {
        let w = where_args(&json!({"at": [1, 2], "points": [[3, 4]], "pin": "U1.1", "pins": ["U1.2"]}));
        assert_eq!(w, vec![json!([1, 2]), json!([3, 4]), json!("U1.1"), json!("U1.2")]);
    }

    #[test]
    fn the_sheet_as_the_standards_drawing() {
        let k = 10_000_000.0; // raw units per inch: 1 mm = k / 25.4
        let mm = |v: f64| (v * k / 25.4).round() as i64;
        let it = |t: char, pts: Vec<P>, at: P| Item { t, key: format!("{t}"), pts, at, ..Default::default() };
        let mut sh = Sheet { k, ..Default::default() };
        sh.items.push(it('W', vec![(0, 0), (mm(10.0), 0), (mm(10.0), mm(5.0))], (0, 0)));
        sh.items.push(it('J', vec![], (mm(10.0), 0)));
        let mut port = it('P', vec![], (mm(20.0), mm(5.0))); port.w = mm(4.0); port.text = "IO".into();
        sh.items.push(port);
        sh.pins.push(Pin { r: "U1".into(), num: "3".into(), at: (mm(24.0), mm(5.0)), ..Default::default() });
        sh.pins.push(Pin { r: "U1".into(), num: "9".into(), at: (0, 0), hidden: true, ..Default::default() });
        sh.comps.push(Comp { r: "U1".into(), bx: Some([mm(24.0), 0, mm(40.0), mm(20.0)]), ..Default::default() });
        let d = drawing("Main.SchDoc", &sh);
        assert_eq!(d["wires"].as_array().unwrap().len(), 2, "a polyline is its segments");
        assert_eq!(d["wires"][1], json!({"a": [10.0, 0.0], "b": [10.0, -5.0]}), "y down");
        assert_eq!(d["junctions"][0], json!([10.0, 0.0]));
        // the port's far end meets U1.3, so that is where its label sits
        assert_eq!(d["labels"][0], json!({"text": "IO", "kind": "hierarchical", "at": [24.0, -5.0]}));
        assert_eq!(d["pins"].as_array().unwrap().len(), 1, "a hidden pin has no end on the drawing");
        assert_eq!(d["symbols"][0]["box"], json!([24.0, -20.0, 40.0, 0.0]));
        // on an A4 landscape sheet (7600 mil = 193.04 mm tall) y counts down from the top edge
        sh.page = json!({"style": 0, "custom": false, "orientation": 0});
        let d = drawing("Main.SchDoc", &sh);
        assert_eq!(d["sizeMm"], json!([292.1, 193.04]));
        assert_eq!(d["wires"][1], json!({"a": [10.0, 193.04], "b": [10.0, 188.04]}));
        sh.page = json!({"style": 0, "custom": false, "orientation": 1});
        assert_eq!(sheet_size_mm(&sh).map(|s| s.0.round()), Some(193.0), "portrait swaps the sides");
    }

    fn wire(pts: &[P]) -> Item { Item { t: 'W', key: format!("W:{pts:?}"), pts: pts.to_vec(), ..Default::default() } }
    fn item(t: char, at: P, text: &str) -> Item { Item { t, key: format!("{t}:{at:?}:{text}"), at, text: text.into(), ..Default::default() } }
    fn pin(r: &str, n: &str, at: P) -> Pin { Pin { r: r.into(), num: n.into(), name: n.into(), at, ..Default::default() } }
    fn sheet(items: Vec<Item>, pins: Vec<Pin>) -> Sheet { Sheet { k: 1000.0, items, pins, ..Default::default() } } // 1 raw unit = 1 mil

    #[test]
    fn wires_join_at_ends_and_tees_but_not_where_they_cross() {
        // U1.1 -- wire -- R1.1, a T from the middle down to C1.1, and a crossing wire with no dot
        let sh = sheet(vec![wire(&[(0, 0), (1000, 0)]), wire(&[(500, 0), (500, -500)]), wire(&[(300, 300), (300, -300)])],
            vec![pin("U1", "1", (0, 0)), pin("R1", "1", (1000, 0)), pin("C1", "1", (500, -500)), pin("D1", "1", (300, 300))]);
        let g = graph(&sh);
        let ns = nets(&sh, &g);
        let net = ns.iter().find(|n| n["pins"].as_array().unwrap().contains(&json!("U1.1"))).unwrap();
        let pins: Vec<String> = net["pins"].as_array().unwrap().iter().map(st).collect();
        assert!(pins.contains(&"R1.1".into()) && pins.contains(&"C1.1".into()));
        assert!(!pins.contains(&"D1.1".into()), "a crossing without a dot does not join");
        // with a dot at the crossing it does
        let mut sh2 = sh.clone();
        sh2.items.push(item('J', (300, 0), ""));
        let n2 = nets(&sh2, &graph(&sh2));
        assert!(n2.iter().any(|n| { let p = n["pins"].as_array().unwrap(); p.contains(&json!("D1.1")) && p.contains(&json!("U1.1")) }));
    }

    #[test]
    fn labels_with_the_same_text_are_one_net_and_name_it() {
        let sh = sheet(vec![wire(&[(0, 0), (500, 0)]), wire(&[(0, 1000), (500, 1000)]), item('N', (200, 0), "SDA"), item('N', (200, 1000), "SDA")],
            vec![pin("U1", "5", (0, 0)), pin("U2", "3", (500, 1000))]);
        let ns = nets(&sh, &graph(&sh));
        let sda: Vec<&Value> = ns.iter().filter(|n| n["name"] == "SDA").collect();
        assert_eq!(sda.len(), 1);
        assert_eq!(sda[0]["pins"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn a_route_turns_once_and_tees_are_found() {
        assert_eq!(route((0, 0), (100, 0), &[], true), vec![(0, 0), (100, 0)]);
        assert_eq!(route((0, 0), (100, 50), &[], true), vec![(0, 0), (100, 0), (100, 50)]);
        assert_eq!(route((0, 0), (100, 50), &[], false), vec![(0, 0), (0, 50), (100, 50)]);
        // an existing wire ends on the new route's middle: a T
        let sh = sheet(vec![wire(&[(50, 0), (50, -100)])], vec![]);
        assert_eq!(tees(&sh, &[(0, 0), (100, 0)]), vec![(50, 0)]);
    }

    #[test]
    fn splitting_keeps_every_vertex() {
        let (a, b) = split_at(&[(0, 0), (100, 0), (100, 100)], 1, (100, 40));
        assert_eq!(a, vec![(0, 0), (100, 0), (100, 40)]);
        assert_eq!(b, vec![(100, 40), (100, 100)]);
    }

    #[test]
    fn arms_count_ends_middles_and_pins() {
        let sh = sheet(vec![wire(&[(0, 0), (100, 0)]), wire(&[(50, 0), (50, 100)])], vec![]);
        assert_eq!(arms(&sh, (50, 0)), 3);
        assert_eq!(arms(&sh, (0, 0)), 1);
    }

    #[test]
    fn justification_words() {
        assert_eq!(justification("left bottom"), 0);
        assert_eq!(justification("right top"), 8);
        assert_eq!(justification("center"), 1);
    }

    #[test]
    fn units_and_ids() {
        let sh = Sheet { k: 10_000_000.0, ..Default::default() };
        assert_eq!(sh.raw(25.4), 10_000_000);
        assert_eq!(sh.mm(10_000_000), 25.4);
        assert!(id_of("W:0,0,10,0").starts_with("wire-"));
        assert_ne!(id_of("W:0,0,10,0"), id_of("W:0,0,10,1"));
    }
}