"""KiCad action plugin: write the board name, revision and date on the front silkscreen.

Put this file in KiCad's plugin folder (PCB Editor: Tools > External Plugins > Open Plugin Directory),
then Tools > External Plugins > Refresh Plugins. Checked in KiCad 10.0.8, where the SWIG plugins
still load (KiCad marks them deprecated, as in 9). Linux: ~/.local/share/kicad/10.0/scripting/plugins/
(flatpak: ~/.var/app/org.kicad.KiCad/data/kicad/10.0/scripting/plugins/).
"""
import datetime, os
import pcbnew


class BoardInfoPlugin(pcbnew.ActionPlugin):
    def defaults(self):
        self.name = "Add Board Info"
        self.category = "Fabrication"
        self.description = "Writes the board name, revision and date on the front silkscreen"
        self.show_toolbar_button = True

    def Run(self):
        board = pcbnew.GetBoard()
        name = os.path.splitext(os.path.basename(board.GetFileName()))[0]
        rev = board.GetTitleBlock().GetRevision() or "A"
        text = f"{name}  rev {rev}  {datetime.date.today().isoformat()}"
        # inside the outline, 2 mm up and in from its lower left corner, wherever the board sits on the sheet
        box = board.GetBoardEdgesBoundingBox()
        txt = pcbnew.PCB_TEXT(board)
        txt.SetText(text)
        txt.SetLayer(pcbnew.F_SilkS)
        txt.SetTextSize(pcbnew.VECTOR2I(pcbnew.FromMM(1), pcbnew.FromMM(1)))
        txt.SetTextThickness(pcbnew.FromMM(0.15))
        txt.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_LEFT)
        txt.SetPosition(pcbnew.VECTOR2I(box.GetLeft() + pcbnew.FromMM(2), box.GetBottom() - pcbnew.FromMM(2)))
        board.Add(txt)
        pcbnew.Refresh()


BoardInfoPlugin().register()
