#!/usr/bin/env python3
import argparse
import os
import pcbnew

def main():
    parser = argparse.ArgumentParser(
        description="Export a single PCB layer to a Gerber file using pcbnew."
    )
    parser.add_argument("input", help="Input .kicad_pcb file")
    parser.add_argument("--output", "-o", required=True, help="Output directory")
    parser.add_argument("--layers", "-l", required=True,
                        help="Layer name to export (e.g. User.Eco1)")
    args = parser.parse_args()

    board = pcbnew.LoadBoard(args.input)

    # Resolve layer name to ID
    layer_id = board.GetLayerID(args.layers)
    if layer_id == -1:
        parser.error(f"Unknown layer: {args.layers!r}. "
                     f"Run with a known layer name (e.g. User.Eco1, Edge.Cuts).")

    # Resolve output directory to absolute path so pcbnew doesn't make it
    # relative to the board file location
    output_dir = os.path.abspath(args.output)
    os.makedirs(output_dir, exist_ok=True)

    prefix = args.layers.replace(".", "-")

    pc = pcbnew.PLOT_CONTROLLER(board)
    po = pc.GetPlotOptions()
    po.SetOutputDirectory(output_dir)
    po.SetPlotFrameRef(False)

    pc.SetLayer(layer_id)
    pc.OpenPlotfile(prefix, pcbnew.PLOT_FORMAT_GERBER, args.layers)
    print(f"Plotting layer {args.layers!r} (id={layer_id}) to {pc.GetPlotFileName()}")
    pc.PlotLayer()
    pc.ClosePlot()
    print("Done.")

if __name__ == "__main__":
    main()