#!/usr/bin/env python3
# pycheck - syntax-check Python files (py_compile) and report
# Usage: pycheck [DIR] [--recursive] [--python PYTHON]
import argparse, os, subprocess, sys

def check(path, python):
    r = subprocess.run([python, "-m", "py_compile", path], capture_output=True, text=True)
    return r.returncode == 0, r.stderr.strip()

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        open(os.path.join(d, "good.py"), "w").write("def f():\n    return 1\n")
        open(os.path.join(d, "bad.py"), "w").write("def f(:\n    return 1\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), d],
                             capture_output=True, text=True)
        assert out.returncode == 1, out.stdout
        assert "good.py" in out.stdout and "PASS" in out.stdout
        assert "bad.py" in out.stdout and "FAIL" in out.stdout
        print("pycheck selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="pycheck",
        description="Syntax-check Python files (py_compile) and report.")
    ap.add_argument("dir", nargs="?", default=".", help="directory to scan (default: .)")
    ap.add_argument("--recursive", "-r", action="store_true", help="recurse into subdirectories")
    ap.add_argument("--python", default=sys.executable, help="python interpreter to use")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    files = []
    if a.recursive:
        for root, dirs, names in os.walk(a.dir):
            dirs[:] = [d for d in dirs if d not in (".git", "__pycache__", ".venv", "venv")]
            for n in names:
                if n.endswith(".py"):
                    files.append(os.path.join(root, n))
    else:
        for n in sorted(os.listdir(a.dir)):
            if n.endswith(".py"):
                p = os.path.join(a.dir, n)
                if os.path.isfile(p):
                    files.append(p)
    if not files:
        print("pycheck: no Python files found in %s" % a.dir); return 0
    ok = bad = 0
    for p in sorted(files):
        good, err = check(p, a.python)
        if good:
            print("PASS  %s" % p); ok += 1
        else:
            print("FAIL  %s" % p); bad += 1
            for line in err.splitlines()[-2:]:
                print("      %s" % line.strip())
    print("pycheck: %d passed, %d failed, %d files." % (ok, bad, len(files)))
    return 1 if bad else 0

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