#!/bin/sh
# Format only fully staged Python files; pre-push remains the fallback gate.
python=${AGDT_PYTHON-python}
if ! command -v "$python" >/dev/null 2>&1; then
    echo "Warning: commit not formatted by pre-commit (Python unavailable); pre-push is the fallback format gate; CI still enforces its gates." >&2
    exit 0
fi
exec "$python" - <<'PY'
import os
import subprocess
import sys

def run(args, **kwargs):
    return subprocess.run(args, shell=False, **kwargs)

try:
    staged = run(["git", "diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"],
                 capture_output=True, check=True).stdout.split(b"\0")
    paths = [p for p in staged if p.endswith(b".py")]
    if not paths:
        sys.exit(0)
    unstaged = run(["git", "diff", "--name-only", "-z"],
                   capture_output=True, check=True).stdout.split(b"\0")
    partial = [p for p in paths if p in set(unstaged)]
    if partial:
        print("Partially staged Python files:", file=sys.stderr)
        for path in partial:
            print(f"  {os.fsdecode(path)!r}", file=sys.stderr)
        sys.exit("Please finish staging these files or separate the unstaged edits before committing.")
    module = run([sys.executable, "-m", "ruff", "--version"], capture_output=True)
    if module.returncode:
        print("Warning: commit not formatted by pre-commit (Python Ruff unavailable); "
              "pre-push is the fallback format gate; CI still enforces its gates.", file=sys.stderr)
        sys.exit(0)
    try:
        cli = run(["ruff", "--version"], capture_output=True, check=True)
    except (OSError, subprocess.CalledProcessError):
        sys.exit("PATH Ruff unavailable: install ruff on PATH to match the selected Python's "
                 "Ruff version; set AGDT_PYTHON to the matching interpreter.")
    if module.stdout.strip() != cli.stdout.strip():
        sys.exit("PATH Ruff version does not match Python Ruff: align PATH and AGDT_PYTHON "
                 "with the same Ruff installation before committing.")
    result = run([sys.executable, "-m", "ruff", "format", "--", *paths])
    if result.returncode:
        sys.exit(f"Ruff formatter failed (exit {result.returncode}); commit blocked.")
    run(["git", "--literal-pathspecs", "add", "--", *paths], check=True)
except (OSError, subprocess.CalledProcessError) as exc:
    sys.exit(f"Pre-commit formatting/staging failed: {exc}")
PY
