master
Ray Publish 0.5.1 6234640
"""Acceptance 1: the viewer reproduces the matplotlib mocks' positions exactly.

Recomputes every machine pin, contact and pad centre the way the mock scripts did (claude-pcb-f411's mcu_line /
wiki_pad_geometry helpers, shapely), runs `adom-2dboard render --json` on the matching example layouts, and compares
positions and nets. Usage: python3 mock_positions.py <adom-2dboard binary> <mock scratch dir>"""
import json, math, subprocess, sys
from pathlib import Path
sys.path.insert(0, '/home/adom/project/claude-pcb-f411/scripts'); sys.path.insert(0, '/home/adom/project/claude-pcb-f411/.validation-packages')
import mcu_line as M
from wiki_pad_geometry import footprint_pads
from shapely.geometry import box
from shapely import affinity

BIN, MOCK = sys.argv[1], Path(sys.argv[2])
EX = Path(__file__).resolve().parents[2] / 'examples'
TOL = 1e-4

def viewer(*layouts):
    out = subprocess.run([BIN, 'render', *sum((['--layout', str(l)] for l in layouts), []), '--out', '/dev/null', '--json'],
                         capture_output=True, text=True, check=True).stdout
    return json.loads(out[:out.rindex(']') + 1])

def compare(name, want, got):
    """want/got: {key: (x, y, net-or-None)}"""
    bad = [k for k in want if k not in got or math.dist(want[k][:2], got[k][:2]) > TOL or (want[k][2] is not None and want[k][2] != got[k][2])]
    extra = [k for k in got if k not in want]
    worst = max((math.dist(want[k][:2], got[k][:2]) for k in want if k in got), default=0)
    print(f'{name}: {len(want)} positions, {len(bad)} differ, {len(extra)} extra, worst offset {worst:.2e} mm')
    for k in bad[:5]: print('   ', k, 'mock', want[k], 'viewer', got.get(k))
    return not bad and not extra

def got_of(scene):
    g = {('MP', m['name']): (m['x'], m['y'], m['net']) for m in scene['machinePins']}
    g.update({('MC', c['name']): (c['x'], c['y'], c['net']) for c in scene['contacts']})
    g.update({('pad', p['part'], p['pin']): (p['x'], p['y'], None) for p in scene['pads']})
    return g

ok = True
# 74HC595BQ, 8 x 8 with 2 mm top and bottom wings (m595v/mock.py)
plan = json.load(open(MOCK / 'm595v/plan.json'))
roles = {'MP1': 'GND', 'MP2': 'VCC', 'MP3': 'VCC', 'MP4': 'GND'}
want = {('MP', m['name']): (m['x'], m['y'], roles[m['name']]) for m in plan['machinePins']}
want.update({('MC', c['designator']): (c['x'], c['y'], c['net']) for c in plan['contacts']})
for ref, slug, pos in (('U1', '74hc595bq', (0, -0.25)), ('C1', '0402b104j160ct', (1.4, 2.75))):
    want.update({('pad', ref, k): (c[0], c[1], None) for k, (c, g) in M.pad_geoms(slug, pos, 0).items()})
ok &= compare('74HC595BQ 8 x 8 + wings (m595v)', want, got_of(viewer(EX / '74hc595bq-8x8-wings/layout.json')[0]))

# CD74HC4067 A / B (mock4067.py)
U1PINS = {1:'COM',2:'I7',3:'I6',4:'I5',5:'I4',6:'I3',7:'I2',8:'I1',9:'I0',10:'S0',11:'S1',12:'GND',13:'S3',14:'S2',15:'E',16:'I15',17:'I14',18:'I13',19:'I12',20:'I11',21:'I10',22:'I9',23:'I8',24:'VCC'}
plan = json.load(open(MOCK / 'plan4067.json')); slots = {(x, y): k for k, (n, x, y) in plan.items()}
MPS = {'MP1': ((-4, -8), 'GND'), 'MP2': ((-4, 8), 'VCC'), 'MP3': ((4, 8), 'VCC'), 'MP4': ((4, -8), 'GND')}
scenes = viewer(EX / 'cd74hc4067/a-upright.json', EX / 'cd74hc4067/b-turned.json')
for variant, scene in zip(('upright', 'turned'), scenes):
    if variant == 'upright':
        rot = 0; nets = {k: n for k, (n, x, y) in plan.items()}
        parts = [('C1', (4.3, 5.4), 90), ('R1', (4.3, -5.4), 90)]
    else:
        rot = 90
        order_top = [(6, 0), (6, 2), (6, 4), (6, 6), (6, 8), (2, 8), (-2, 8), (-6, 8), (-6, 6), (-6, 4), (-6, 2)]
        order_bot = [(-6, 0), (-6, -2), (-6, -4), (-6, -6), (-6, -8), (-2, -8), (2, -8), (6, -8), (6, -6), (6, -4), (6, -2)]
        nets = {}
        for pn, xy in zip(range(13, 24), order_top): nets[slots[xy]] = U1PINS[pn]
        for pn, xy in zip(range(1, 12), order_bot): nets[slots[xy]] = U1PINS[pn]
        parts = [('C1', (-4.6, 5.6), 90), ('R1', (1.0, 5.6), 0)]
    want = {('MP', k): (xy[0], xy[1], n) for k, (xy, n) in MPS.items()}
    want.update({('MC', k): (x, y, nets.get(k, n)) for k, (n, x, y) in plan.items()})
    for p in footprint_pads(MOCK / 'logic/cd74hc4067sm96/cd74hc4067sm96.kicad_mod'):
        if not any(l.endswith('.Cu') for l in p['layers']): continue
        w, h = p['size']; g = affinity.rotate(box(p['at'][0] - w / 2, -p['at'][1] - h / 2, p['at'][0] + w / 2, -p['at'][1] + h / 2), rot, origin=(0, 0))
        want[('pad', 'U1', str(p['pad']))] = (g.centroid.x, g.centroid.y, None)
    for ref, (cx, cy), r in parts:
        for k, x, y, w, h in (('1', -0.5, 0.0, 0.6, 0.5), ('2', 0.5, 0.0, 0.6, 0.5)):
            g = affinity.translate(affinity.rotate(box(x - w / 2, y - h / 2, x + w / 2, y + h / 2), r, origin=(0, 0)), cx, cy)
            want[('pad', ref, k)] = (g.centroid.x, g.centroid.y, None)
    ok &= compare(f'CD74HC4067 {variant} (mock4067.py)', want, got_of(scene))
print('PASS' if ok else 'FAIL'); sys.exit(0 if ok else 1)