#!/usr/bin/env python3
# $Id: ppbreadboard_config 71 2026-08-27 08:31:17Z peter $
#
# ppbreadboard_config --- the CLI entry point for breadboard_config.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 breadboard_config.py itself: that module is
# genuinely BOTH a real CLI tool and a densely cross-imported
# library (breadboard_lib.py, build_instructions.py, render.py,
# auto_layout.py), and Python's own import statement needs a real
# ".py" extension to resolve `import breadboard_config`.

import os
import sys
import configparser
from breadboard_config import (
    resolve_config_path, load_config, default_config, write_config,
)


def _version():
    """This project's own current Dewey-decimal version -- CLI-
    specific, so it lives here, not in breadboard_config.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: load a real config file and print it back
    (round-tripped through breadboard_config.py's own parser and
    writer), the simplest possible real confirmation that a given
    file parses as intended -- not a general breadboard-layout tool
    (there isn't one yet; see breadboard_config.py's own header for
    what's still missing).

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

    parser = argparse.ArgumentParser(
        prog="ppbreadboard_config",
        description="Parse a real Unix-style INI breadboard configuration "
                     "file and print it back (round-tripped through this "
                     "module's own writer) -- a real, direct way to "
                     "confirm a given file parses as intended.")
    parser.add_argument("config_file", metavar="CONFIG_FILE", nargs="?",
                         help="a breadboard config file (see this "
                              "program's own man page for the real format, "
                              "and this project's own breadboard1.conf/"
                              "breadboard2.conf for real worked examples). "
                              "Omit to print the tool's own default "
                              "(single-sector, no extra rails) instead.")
    parser.add_argument("--resolve-for", metavar="SCHEMATIC", default=None,
                         help="don't load or print a config -- instead, "
                              "print which real config file (if any) "
                              "resolve_config_path() would choose for a "
                              "circuit at this schematic path, per Péter's "
                              "own priority order ($PACKPAY_BREADBOARD_CONFIG, "
                              "then a breadboard.conf next to SCHEMATIC, "
                              "then ./breadboard.conf), or \"(none found)\" "
                              "if nothing exists at any of them. A real, "
                              "direct way to confirm the lookup itself, "
                              "ahead of any tool actually consuming it.")
    parser.add_argument("--version", action="version",
                         version=f"%(prog)s {_version()}")
    args = parser.parse_args(argv)

    if args.resolve_for is not None:
        found = resolve_config_path(schematic_path=args.resolve_for)
        print(found if found is not None else "(none found)")
        return

    try:
        cfg = load_config(args.config_file) if args.config_file else default_config()
    except (OSError, configparser.Error) as e:
        print(f"ppbreadboard_config: {args.config_file}: {e}", file=sys.stderr)
        raise SystemExit(1)

    print(write_config(cfg), end="")


if __name__ == "__main__":
    main()
