from pathlib import Path
import json,xml.etree.ElementTree as E
import wx
_app=wx.App(False)
import pcbnew as k
p=Path(__file__).resolve().parent;b=k.LoadBoard(str(p/'board/led_driver.kicad_pcb'));r=E.parse(p/'netlist.xml').getroot()
pins={(c.get('ref'),c.get('pin')):n.get('name') for n in r.findall('./nets/net') for c in n};seen={};circuit=[]
for f in b.GetFootprints():
 if f.GetReference().startswith('H'):continue
 circuit.append(f.GetReference())
 assert f.IsDNP()==(f.GetReference() in ['R6','R7'])
 for pad in f.Pads():
  if pad.GetNumber():seen[(f.GetReference(),pad.GetNumber())]=pad.GetNetname()
assert seen==pins,'PCB pad-to-net mismatch'
thermal=[]
for v in b.GetTracks():
 if isinstance(v,k.PCB_VIA):
  x,y=k.ToMM(v.GetPosition().x),k.ToMM(v.GetPosition().y)
  if abs(y-46)<=1.61 and any(abs(x-a)<=.81 for a in [23,53,83]):thermal.append((x,y,v.GetNetname()))
assert len(thermal)==18 and all(n=='/GND' for x,y,n in thermal)
erc=json.loads((p/'erc.json').read_text());assert not [v for sh in erc['sheets'] for v in sh.get('violations',[])]
d=json.loads((p/'drc.json').read_text());assert len(d['violations'])==0
assert len(d['schematic_parity'])==0
widths=[k.ToMM(t.GetWidth()) for t in b.GetTracks() if not isinstance(t,k.PCB_VIA)]
assert widths and min(widths)>=.199999
checks={'native_ERC':0,'matched_electrical_ref_pin_pairs':len(seen),'circuit_footprints':len(circuit),'schematic_mounting_holes':4,'DRC_geometric_violations':0,'unconnected_items':len(d['unconnected_items']),'schematic_parity_issues':0,'thermal_vias_confirmed':18,'thermal_via_net':'GND','min_track_width_mm':min(widths),'routing':'INCOMPLETE' if d['unconnected_items'] else 'CONNECTED_CANDIDATE','physical_validation':False,'manufacturing':'HOLD'}
checks['VLED_min_width_mm']=min(k.ToMM(t.GetWidth()) for t in b.GetTracks() if not isinstance(t,k.PCB_VIA) and t.GetNetname()=='/VLED_GUARDED')
assert checks['VLED_min_width_mm']>=2.
checks['power_current_rating_validated']=False
(p/'checks.json').write_text(json.dumps(checks,indent=2)+'\n');print(json.dumps(checks))
