"""Compare two KiCad netlists pin by pin: same parts, values, footprints and the same groups of joined pins.
Net names may differ (the drawn schematic names some nets by their pins). Exit code 1 on any difference."""
import sys
import re
TOK=re.compile(r'\(|\)|"(?:[^"\\]|\\.)*"|[^\s()]+')
def parse(t):
    st=[[]]
    for m in TOK.finditer(t):
        s=m.group(0)
        if s=='(': st.append([])
        elif s==')': x=st.pop(); st[-1].append(x)
        elif s[0]=='"': st[-1].append(bytes(s[1:-1],'utf8').decode('unicode_escape') if '\\' in s else s[1:-1])
        else: st[-1].append(s)
    return st[0][0]
def find(n,key): return [c for c in n if isinstance(c,list) and c and c[0]==key]
def get(n,key,d=None):
    f=find(n,key); return f[0][1] if f and len(f[0])>1 else d


def load(p):
    r = parse(open(p).read())
    parts = {get(c, 'ref'): (get(c, 'value'), get(c, 'footprint')) for c in find(find(r, 'components')[0], 'comp')}
    nets = {}
    for n in find(find(r, 'nets')[0], 'net'):
        pins = frozenset(f"{get(x, 'ref')}.{get(x, 'pin')}" for x in find(n, 'node'))
        if len(pins) > 1: nets[pins] = get(n, 'name')
    return parts, nets

a, b = load(sys.argv[1]), load(sys.argv[2])
bad = 0
for ref in sorted(set(a[0]) | set(b[0])):
    if a[0].get(ref) != b[0].get(ref): print('part', ref, a[0].get(ref), '|', b[0].get(ref)); bad += 1
for pins in set(a[1]) ^ set(b[1]):
    print('net only in', 'A' if pins in a[1] else 'B', (a[1].get(pins) or b[1].get(pins)), sorted(pins)); bad += 1
print(f'{len(a[0])} parts, {len(a[1])} nets with 2 or more pins; differences: {bad}')
sys.exit(1 if bad else 0)
