"""Check that neighbouring stack boards mate: S1 J2 (top header) -> S2 J1 (bottom socket).

For every bus pin the header pad and the socket pad must sit in the same row and on the same side of the
connector (seen from the top), and carry the same net (or both be unconnected). Exit code 1 on any mismatch.
    python verify_stack.py <project dir>
"""
import os, sys
import pcbnew

P = sys.argv[1]
B = {t: pcbnew.LoadBoard(os.path.join(P, d, f'XFM5050UV-{d}.kicad_pcb'))
     for t, d in [('s1', 'S1-Power'), ('s2', 'S2-Driver')]}
PAIRS = [('s1', 's2')]


def pads(board, ref, want_bottom):
    fp = board.FindFootprintByReference(ref)
    assert fp.IsFlipped() == want_bottom, f'{ref} should be on the {"bottom" if want_bottom else "top"}'
    c = fp.GetPosition()
    out = {}
    for p in fp.Pads():
        d = p.GetPosition() - c
        net = p.GetNetname().lstrip('/')
        out[p.GetNumber()] = (pcbnew.ToMM(d.x), pcbnew.ToMM(d.y), '' if net.startswith('unconnected') else net)
    return pcbnew.ToMM(c.x), pcbnew.ToMM(c.y), out


bad = 0
for lo, hi in PAIRS:
    hx, hy, h = pads(B[lo], 'J2', False)
    sx, sy, s = pads(B[hi], 'J1', True)
    if abs(hx - sx) > 0.01 or abs(hy - sy) > 0.01:
        print(f'{lo} J2 at ({hx}, {hy}) but {hi} J1 at ({sx}, {sy})'); bad += 1
    for n in sorted(h, key=int):
        (ax, ay, an), (bx, by, bn) = h[n], s[n]
        if abs(ay - by) > 0.05 or (ax > 0) != (bx > 0):
            print(f'{lo}->{hi} pin {n}: header ({ax:.2f}, {ay:.2f}) vs socket ({bx:.2f}, {by:.2f})'); bad += 1
        if an != bn:
            print(f'{lo}->{hi} pin {n}: net {an or "NC"} vs {bn or "NC"}'); bad += 1
    print(f'{lo} J2 -> {hi} J1: ' + ', '.join(f'{n}={h[n][2] or "NC"}' for n in sorted(h, key=int)))
print('STACK OK' if not bad else f'STACK MISMATCH ({bad})')
sys.exit(1 if bad else 0)
