#!/usr/bin/env python3
# maketool - scaffold a new utility: template file plus a test stub
# Usage: maketool NAME [--lang python|bash] [--dir DIR] [--desc TEXT]
import argparse, os, subprocess, sys

PY_TEMPLATE = """#!/usr/bin/env python3
# {name} - {desc}
# Usage: {name} [options]
import argparse, sys

def selftest():
    print("{name} selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="{name}", description="{desc}")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    print("{name}: not implemented yet")
    return 0

if __name__ == "__main__":
    sys.exit(main())
"""

BASH_TEMPLATE = """#!/bin/bash
# {name} - {desc}
# Usage: {name} [options]
set -euo pipefail

usage() {{
  echo "Usage: {name} [--help] [--selftest]"
  echo "{desc}"
}}

selftest() {{
  echo "{name} selftest: PASS"
  return 0
}}

case "${{1:-}}" in
  --help|-h) usage; exit 0 ;;
  --selftest) selftest; exit $? ;;
  *) usage; exit 0 ;;
esac
"""

TEST_STUB = """#!/bin/bash
# Test stub for {name}: runs --help and --selftest.
set -u
BIN="$(dirname "$0")/../bin/{name}"
fail=0
"$BIN" --help >/dev/null 2>&1 || {{ echo "FAIL: {name} --help"; fail=1; }}
"$BIN" --selftest >/dev/null 2>&1 || {{ echo "FAIL: {name} --selftest"; fail=1; }}
if [ "$fail" -eq 0 ]; then echo "PASS: {name}"; else echo "FAIL: {name}"; exit 1; fi
"""

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "demotool",
                              "--dir", d, "--desc", "demo tool for testing"],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        binpath = os.path.join(d, "bin", "demotool")
        testpath = os.path.join(d, "tests", "demotool.sh")
        assert os.path.exists(binpath) and os.access(binpath, os.X_OK), out.stdout
        assert os.path.exists(testpath), out.stdout
        r = subprocess.run(["bash", testpath], capture_output=True, text=True)
        assert r.returncode == 0 and "PASS" in r.stdout, r.stdout + r.stderr
        print("maketool selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="maketool",
        description="Scaffold a new utility: template file plus a test stub.")
    ap.add_argument("name", nargs="?", help="name of the new utility")
    ap.add_argument("--lang", choices=["python", "bash"], default="python",
                    help="template language (default python)")
    ap.add_argument("--dir", default=".", help="project root (default: .)")
    ap.add_argument("--desc", default="a new utility", help="one-line description")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.name:
        ap.error("a utility name is required")
    import re
    if not re.match(r"^[a-z][a-z0-9_-]*$", a.name):
        print("maketool: name must be lowercase letters, digits, - or _, starting with a letter",
              file=sys.stderr)
        return 2
    bindir = os.path.join(a.dir, "bin")
    testdir = os.path.join(a.dir, "tests")
    os.makedirs(bindir, exist_ok=True)
    os.makedirs(testdir, exist_ok=True)
    binpath = os.path.join(bindir, a.name)
    if os.path.exists(binpath):
        print("maketool: %s already exists, refusing to overwrite." % binpath, file=sys.stderr)
        return 1
    tmpl = PY_TEMPLATE if a.lang == "python" else BASH_TEMPLATE
    with open(binpath, "w") as f:
        f.write(tmpl.format(name=a.name, desc=a.desc))
    os.chmod(binpath, 0o755)
    testpath = os.path.join(testdir, a.name + ".sh")
    with open(testpath, "w") as f:
        f.write(TEST_STUB.format(name=a.name))
    os.chmod(testpath, 0o755)
    print("maketool: created %s (%s)" % (binpath, a.lang))
    print("maketool: created %s (run it to check --help and --selftest)" % testpath)
    return 0

if __name__ == "__main__":
    sys.exit(main())
