#!/usr/bin/env python3
# $Id: ppfootprint 72 2026-08-27 08:32:33Z peter $
#
# ppfootprint --- the CLI entry point for footprint.py's own library
# functions. ADDED 2026-08-26, per Péter's own direct preference (no
# extension on executable files, a project-specific "pp" prefix) --
# see ppnetlist's own header comment for the full real account of
# why this is a real, separate file rather than a direct rename of
# footprint.py itself: that module is genuinely BOTH a real CLI tool
# and a densely cross-imported library (auto_layout.py,
# render_footprints.py), and Python's own import statement needs a
# real ".py" extension to resolve `import footprint`.

import os
import sys
from footprint import find_footprint_file, load_footprint


def _version():
    """This project's own current Dewey-decimal version -- CLI-
    specific, so it lives here, not in footprint.py's own library
    code. See ppnetlist's own identical helper for the fuller
    reasoning."""
    here = os.path.dirname(os.path.abspath(__file__))
    try:
        with open(os.path.join(here, "VERSION")) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#"):
                    return line
    except OSError:
        pass
    return "unknown"


def main(argv=None):
    """CLI entry point, ADDED 2026-08-18, this project's own THIRD
    script (after netlist.py and render.py) brought up to
    DevelopmentStandard.org's own real "Options and Arguments" bar --
    see ppfootprint.1 (this program's own manual page, renamed
    alongside this file itself).

    MOVED 2026-08-26 from footprint.py's own file into this new,
    separate, extensionless CLI entry point -- unchanged otherwise."""
    import argparse

    parser = argparse.ArgumentParser(
        prog="ppfootprint",
        description="Load a real KiCad footprint (.kicad_mod) file and "
                     "print its real pad geometry and courtyard size -- "
                     "the same data real_size_rows() (auto_layout.py) uses "
                     "for footprint-aware component sizing.")
    parser.add_argument("footprint_ref", metavar="LIBRARY:FOOTPRINT",
                         help="a footprint reference in KiCad's own "
                              "LibraryName:FootprintName form, e.g. "
                              "Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_"
                              "P10.16mm_Horizontal -- the exact string a "
                              "component's own footprint field holds once "
                              "assigned. Resolved under $KICAD_FOOTPRINT_DIR "
                              "if set, else /usr/share/kicad/footprints.")
    parser.add_argument("--version", action="version",
                         version=f"%(prog)s {_version()}")
    parser.add_argument("--debug", action="store_true",
                         help="also print the resolved .kicad_mod file "
                              "path and the courtyard's own real bounding "
                              "coordinates (not just its size)")
    parser.add_argument("--quiet", action="store_true",
                         help="print only the summary and courtyard lines; "
                              "suppress the description and the full "
                              "per-pad listing")
    args = parser.parse_args(argv)

    try:
        if args.debug:
            print(f"  file: {find_footprint_file(args.footprint_ref)}")
        fp = load_footprint(args.footprint_ref)
    except ValueError as e:
        print(f"ppfootprint: {args.footprint_ref}: {e}", file=sys.stderr)
        raise SystemExit(1)
    except FileNotFoundError as e:
        print(f"ppfootprint: {e}", file=sys.stderr)
        raise SystemExit(1)

    print(f"{fp.name}")
    if not args.quiet:
        print(f"  {fp.description}")
    print(f"  {len(fp.pads)} pads, pad-center span {fp.pad_span_x():.2f}mm, "
          f"pad bounding box {fp.bounding_box()[0]:.2f} x {fp.bounding_box()[1]:.2f}mm")
    if fp.courtyard_bbox:
        cw, ch = fp.courtyard_size()
        print(f"  courtyard (real keep-out size): "
              f"{cw:.2f} x {ch:.2f}mm")
        if args.debug:
            x0, y0, x1, y1 = fp.courtyard_bbox
            print(f"  courtyard bbox: ({x0:.2f}, {y0:.2f}) to ({x1:.2f}, {y1:.2f})mm")
    else:
        print("  (no courtyard layer found)")
    if not args.quiet:
        for p in fp.pads:
            print(f"    pad {p.number}: ({p.x:.2f}, {p.y:.2f})mm, "
                  f"size {p.size_x:.2f}x{p.size_y:.2f}mm, {p.kind}/{p.shape}")


if __name__ == "__main__":
    main()
