#!/bin/sh
# Pre-push hook for agentic-devtools
# Delegates to the Python checks module for cross-platform, fast validation.
# Full coverage runs in CI after Copilot review; full suite runs post-merge.
#
# Exit code 10 from checks = ruff reformatted files (auto-fixable).
#
# To enable:  git config core.hooksPath .githooks
# To disable: git config --unset core.hooksPath

cd "$(git rev-parse --show-toplevel)" || exit 1

# Run checks with format auto-fix (-u = unbuffered so output streams through tee).
# Use a temp file to relay the Python exit code across the pipe (POSIX-portable).
# On Windows (MSYS/Git Bash), the mktemp binary may be blocked by security policy,
# so fall back to constructing a path from $TMPDIR / $TEMP / $TMP / /tmp.
_rc_file=$(mktemp 2>/dev/null) || _rc_file=$(mktemp -t agdt-pre-push.XXXXXX 2>/dev/null) || _rc_file=""
if [ -z "$_rc_file" ]; then
    _tmp_dir="${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"
    if [ ! -d "$_tmp_dir" ] || [ ! -w "$_tmp_dir" ] || [ ! -x "$_tmp_dir" ]; then
        _tmp_dir=/tmp
        if [ ! -d "$_tmp_dir" ] || [ ! -w "$_tmp_dir" ] || [ ! -x "$_tmp_dir" ]; then
            echo "❌ No usable temporary directory for pre-push exit code capture."
            exit 1
        fi
    fi
    i=0
    while :; do
        _rc_file="${_tmp_dir}/agdt-pre-push-$$-${i}.tmp"
        (umask 077; set -C; : > "$_rc_file") 2>/dev/null && break
        i=$((i + 1))
        [ "$i" -ge 100 ] && {
            echo "❌ Failed to create temporary file for pre-push exit code capture."
            exit 1
        }
    done
fi

cleanup() {
    rm -f "$_rc_file"
}
trap cleanup 0 HUP INT TERM

(python -u -m agentic_devtools.cli.checks --format-fix; echo $? > "$_rc_file") 2>&1 | tee .pre-push-output.log
if ! rc=$(cat "$_rc_file" 2>/dev/null); then
    echo "❌ Failed to read pre-push check exit code."
    exit 1
fi

# Exit code 10 = ruff reformatted files — require explicit save-work flow
if [ "$rc" -eq 10 ]; then
    echo "❌ Files were reformatted by ruff."
    echo "Run agdt-git-save-work to stage/commit formatted changes, then push again."
    exit 1
fi

exit "$rc"
