#!/usr/bin/env python3
"""Export the pin-to-net map of the mainboard connectors and chips used by the breadboard guide.

  python docs/breadboard/export_pinmap.py

Runs kicad-cli on kicad_mainboard/Mainboard.kicad_sch (netlist export) and writes docs/breadboard/pinmap.json:
{reference: {pin: net}}. build_breadboard_guide.py checks its wiring against this file, so the breadboard is
verified against the schematic rather than against someone's reading of it.
"""
import glob
import json
import os
import subprocess
import tempfile
import xml.etree.ElementTree as ET

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
SCH = os.path.join(ROOT, "kicad_mainboard", "Mainboard.kicad_sch")
REFS = ["J1-H1", "J1-H2", "J2-MODE", "J2-MOTOR", "U1", "U3", "U5", "J-LED-SIG", "J-FAN", "J-ENC-MAIN",
        "J-ENC-HUE", "J-ENC-SAT", "J-ENC-VAL", "J-BTN-TAP", "R9", "R18", "R21", "R22", "R23", "R26", "R61", "R62", "R57", "R58", "R59", "Q6",
        "D1", "C8", "R65", "R66", "C16", "D34"]


def kicad_cli():
    for pat in ("C:/Program Files/KiCad/*/bin/kicad-cli.exe", "/usr/bin/kicad-cli"):
        hits = sorted(glob.glob(pat), key=lambda s: [int(x) if x.isdigit() else 0 for x in s.replace("\\", "/").split("/")[-3].split(".")])
        if hits:
            return hits[-1]
    return "kicad-cli"


def main():
    with tempfile.TemporaryDirectory() as d:
        xml = os.path.join(d, "net.xml")
        subprocess.run([kicad_cli(), "sch", "export", "netlist", "--format", "kicadxml", "-o", xml, SCH], check=True,
                       capture_output=True)
        root = ET.parse(xml).getroot()
    out = {r: {} for r in REFS}
    for net in root.find("nets"):
        for node in net:
            ref = node.get("ref")
            if ref in out:
                out[ref][node.get("pin")] = net.get("name")
    with open(os.path.join(HERE, "pinmap.json"), "w", encoding="utf-8", newline="\n") as f:
        json.dump(out, f, indent=1, sort_keys=True)
    print("wrote", os.path.join(HERE, "pinmap.json"), {r: len(v) for r, v in out.items()})


if __name__ == "__main__":
    main()
