"""Draw the 66 x 53 mm outline and move the main parts of the scripting lesson's board to their places.

The lesson's script, checked in KiCad 10.0.8 (pcbnew from KiCad's own Python). Give it a board that
already holds the footprints (PCB Editor: File > Import > Netlist..., then save).
Run:  python place_parts.py atmega328p_breakout.kicad_pcb
      (flatpak: flatpak run --command=python3 org.kicad.KiCad place_parts.py atmega328p_breakout.kicad_pcb)
"""
import sys
import pcbnew

src = sys.argv[1] if len(sys.argv) > 1 else "atmega328p_breakout.kicad_pcb"
board = pcbnew.LoadBoard(src)

outline = pcbnew.PCB_SHAPE(board)
outline.SetShape(pcbnew.SHAPE_T_RECTANGLE)
outline.SetStart(pcbnew.VECTOR2I_MM(0, 0))
outline.SetEnd(pcbnew.VECTOR2I_MM(66, 53))
outline.SetLayer(pcbnew.Edge_Cuts)
outline.SetWidth(pcbnew.FromMM(0.1))
board.Add(outline)

# (x mm, y mm, rotation in degrees); y grows downward; a footprint's origin is its pin 1
placement = {
    'U1': (16.5, 31, 90), 'U2': (8, 44, 0), 'J1': (15, 13, 0), 'Y1': (30, 13, 0),
    'J2': (54, 11, 0), 'J3': (16.5, 49, 90), 'J4': (16.5, 4, 90),
}
missing = [ref for ref in placement if board.FindFootprintByReference(ref) is None]
if missing:
    sys.exit(f"not on the board: {missing}. Import the netlist first.")
for ref, (x, y, angle) in placement.items():
    fp = board.FindFootprintByReference(ref)
    fp.SetPosition(pcbnew.VECTOR2I_MM(x, y))
    fp.SetOrientationDegrees(angle)

out = src.replace(".kicad_pcb", "_placed.kicad_pcb")
board.Save(out)
print(f"{len(placement)} parts placed, saved {out}. The other parts stay where the import put them.")
