#!/Applications/KiCad/KiCad.app/Contents/Frameworks/Python.framework/Versions/3.9/bin/python3
"""Align A2 board fields and DNP attributes with the schematic."""
from pathlib import Path
import json
import wx

app = wx.App(False)
import pcbnew

root = Path(__file__).resolve().parent
board_path = root / "lamp_buck_lmr51450_a2_costdown.kicad_pcb"
board = pcbnew.LoadBoard(str(board_path))
mpns = {
    "C5": "TDK C4532X7R1C336M250KC",
    "C6": "TDK C4532X7R1C336M250KC",
    "C7": "TDK C3225X6S1A107M250AC optional",
    "C8": "TDK C3225X6S1A107M250AC optional",
}
changed = {}
for footprint in board.GetFootprints():
    footprint = pcbnew.Cast_to_FOOTPRINT(footprint)
    ref = footprint.GetReference()
    if ref not in mpns:
        continue
    footprint.SetField("MPN", mpns[ref])
    mpn_field = footprint.GetField("MPN")
    mpn_field.SetLayer(pcbnew.F_Fab)
    mpn_field.SetVisible(False)
    if ref in ("C7", "C8"):
        footprint.SetValue("100uF 10V X6S OPTIONAL DNP")
        footprint.SetDNP(True)
        footprint.SetExcludedFromBOM(True)
        footprint.SetExcludedFromPosFiles(True)
    changed[ref] = {
        "value": footprint.GetValue(),
        "mpn": footprint.GetFieldText("MPN"),
        "dnp": footprint.IsDNP(),
        "excluded_from_bom": footprint.IsExcludedFromBOM(),
        "excluded_from_pos": footprint.IsExcludedFromPosFiles(),
    }
if set(changed) != set(mpns):
    raise RuntimeError(f"footprint set mismatch: {sorted(changed)}")
pcbnew.ZONE_FILLER(board).Fill(board.Zones())
if not pcbnew.SaveBoard(str(board_path), board):
    raise RuntimeError("failed to save A2 PCB")
(root / "board-metadata-sync.json").write_text(
    json.dumps({"status": "SYNCED_DRC_PENDING", "components": changed}, indent=2) + "\n",
    encoding="utf-8",
)
print(json.dumps(changed, indent=2))
