"""Run KiCad's design rules check on a board and fail when it finds anything.

KiCad 10 note: pcbnew.WriteDRCReport() crashes when it is called from a plain Python script
(checked in 10.0.8), so this script asks kicad-cli for the check and reads its JSON report.
Any Python 3 runs it; it needs no KiCad module.

Run:  python run_drc.py board.kicad_pcb
      KICAD_CLI="flatpak run --command=kicad-cli org.kicad.KiCad" python run_drc.py board.kicad_pcb
"""
import json, os, shlex, subprocess, sys


def run_drc(pcb_path, report_path='drc_report.json'):
    cli = shlex.split(os.environ.get('KICAD_CLI', 'kicad-cli'))
    subprocess.run(cli + ['pcb', 'drc', '--schematic-parity', '--severity-all', '--format', 'json',
                          '-o', report_path, pcb_path], check=True, capture_output=True)
    with open(report_path) as f:
        rep = json.load(f)
    found = rep.get('violations', []) + rep.get('unconnected_items', []) + rep.get('schematic_parity', [])
    if not found:
        print(f'DRC PASSED: {pcb_path}')
        return True
    print(f'DRC FAILED: {pcb_path}, {len(found)} item(s)')
    for i, v in enumerate(found, 1):
        where = ', '.join(x.get('description', '') for x in v.get('items', []))
        print(f"  {i}. [{v.get('severity')}] {v.get('description')}: {where}")
    return False


if __name__ == '__main__':
    sys.exit(0 if run_drc(sys.argv[1]) else 1)   # a CI service reads the exit code
