#!/Applications/KiCad/KiCad.app/Contents/Frameworks/Python.framework/Versions/3.9/bin/python3
from pathlib import Path
import hashlib
import json

import wx
app = wx.App(False)
import pcbnew

root = Path(__file__).resolve().parent
board_path = root / "lamp_buck_lmr51450_a1.kicad_pcb"
unrouted_path = root / "lamp_buck_lmr51450_a1_unrouted.kicad_pcb"
ses_path = root / "lamp_buck_lmr51450_a1.ses"
board = pcbnew.LoadBoard(str(board_path))
if not board:
    raise RuntimeError("could not load candidate board")

unrouted_path.write_bytes(board_path.read_bytes())
if not pcbnew.ImportSpecctraSES(board, str(ses_path)):
    raise RuntimeError("KiCad rejected the FreeRouting SES file")
pcbnew.ZONE_FILLER(board).Fill(board.Zones())
if not pcbnew.SaveBoard(str(board_path), board):
    raise RuntimeError("could not save routed candidate board")

result = {
    "status": "FREEROUTING_SES_IMPORTED_DRC_PENDING",
    "ses_bytes": ses_path.stat().st_size,
    "ses_sha256": hashlib.sha256(ses_path.read_bytes()).hexdigest(),
    "unrouted_board_sha256": hashlib.sha256(unrouted_path.read_bytes()).hexdigest(),
    "routed_board_sha256": hashlib.sha256(board_path.read_bytes()).hexdigest(),
    "track_items": len(list(board.GetTracks())),
    "footprints": len(list(board.GetFootprints())),
}
(root / "ses-import.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
