#!/bin/sh
# ATDD pre-merge-commit hook — version gate + main-merge protection.
# Installed by `atdd init`.
#
# All ATDD_SKIP_* bypass env vars have been retired (E030, 2026-05-26).
# For genuine emergencies: atdd emergency --reason "<reason>"

set -e

# --- Emergency bypass check (E031) ---
_REPO_ROOT="${ATDD_REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || echo "")}"

# --- Source-checkout live-source bridge (#928 Gap 4 Item 3) ---
# Cleared first: this is an internal flag read by the interpreter resolution
# below, and a same-named variable inherited from the caller's environment would
# otherwise suppress that resolution and silently restore the bug it fixes.
_ATDD_SOURCE_BRIDGE=
# Inside the atdd toolkit source checkout, prepend src/ so the bare `python3`
# version gate AND `atdd validate` import atdd from the WORKING TREE, not the
# installed wheel. Removes the manual `PYTHONPATH=src` bridge; no-op elsewhere.
if [ -n "$_REPO_ROOT" ] && [ -d "$_REPO_ROOT/src/atdd" ] && \
   grep -q '^name = "atdd"' "$_REPO_ROOT/pyproject.toml" 2>/dev/null; then
    export PYTHONPATH="$_REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
    # Recorded so the interpreter resolution below knows the ambient python3 can
    # now import atdd — from this tree, which is the point.
    _ATDD_SOURCE_BRIDGE=1
fi

# --- BEGIN atdd-gate-interpreter ---
# Which interpreter runs the gates below (#1875).
#
# When the source bridge above applied it put the WORKING TREE on the import
# path, and the gates must test that rather than the installed wheel — so the
# ambient `python3` wins there and the console script is deliberately NOT
# consulted: its entry point carries `-E`, which would discard the very path the
# bridge just set.
#
# Everywhere else the only interpreter known to hold atdd is the one the `atdd`
# console script was built against. pipx and uv install into an isolated venv no
# ambient python3 can import, which is why a freshly initialised consumer repo
# could not push at all. Resolved from the shebang rather than by probing, so
# this costs one `command -v` and one `sed` — no interpreter start-up — on every
# commit and push.
ATDD_PYTHON=python3
if [ -z "${_ATDD_SOURCE_BRIDGE:-}" ]; then
    _ATDD_BIN=$(command -v atdd 2>/dev/null || true)
    if [ -n "$_ATDD_BIN" ]; then
        # Bounded read: `atdd` is a text console script, but some installers ship
        # a binary launcher, and an unbounded `sed` would scan it to the first
        # newline. 256 bytes is far more than any shebang.
        # Both halves muted: a binary launcher makes `sed` complain about an
        # illegal byte sequence, and that would print before every commit and push.
        _ATDD_SHEBANG=$(head -c 256 "$_ATDD_BIN" 2>/dev/null | sed -n '1s|^#!\([^[:space:]]*\).*|\1|p' 2>/dev/null || true)
        # Some installers ship `atdd` as a shell wrapper; only take a python.
        case "$_ATDD_SHEBANG" in
            */python*)
                if [ -x "$_ATDD_SHEBANG" ]; then ATDD_PYTHON="$_ATDD_SHEBANG"; fi
                ;;
        esac
    fi
fi
# --- END atdd-gate-interpreter ---
if [ -n "$_REPO_ROOT" ]; then
    _BYPASS_FILE="${_REPO_ROOT}/.atdd/EMERGENCY_BYPASS"
    if [ -f "$_BYPASS_FILE" ]; then
        if find "$_BYPASS_FILE" -mmin -5 2>/dev/null | grep -q .; then
            printf "ATDD: Emergency bypass active (pre-merge-commit). Reason: %s\n" \
                "$(head -1 "$_BYPASS_FILE" 2>/dev/null | sed 's/^reason=//' || echo 'see .atdd/EMERGENCY_BYPASS')" >&2
            exit 0
        else
            printf "ATDD: Emergency bypass file found but expired (> 5 min). Ignored.\n" >&2
        fi
    fi
fi

# --- Version gate ---
"$ATDD_PYTHON" -c "
import sys
try:
    from atdd.version_check import _gate_main
    _gate_main()
except ImportError:
    print('ATDD: the python3 running this hook (' + sys.executable + ') cannot import atdd.', file=sys.stderr)
    print('  This is an environment/path problem, NOT a stale package: atdd is', file=sys.stderr)
    print('  likely installed in an isolated venv (pipx) that is not on the path', file=sys.stderr)
    print('  of this interpreter. Diagnose and fix:  atdd doctor', file=sys.stderr)
    sys.exit(1)
" 2>&1
if [ $? -ne 0 ]; then exit 1; fi

# --- Block merges into main/master ---
BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || echo "")

case "$BRANCH" in
    main|master) ;;
    *) exit 0 ;;
esac

# Allow: CI-only env bypass
if [ "${CI:-}" = "true" ] && [ "${ATDD_ALLOW_MAIN_MERGE:-0}" = "1" ]; then
    exit 0
fi

cat >&2 <<EOF

ATDD: Direct merges into $BRANCH are blocked.

Use a PR workflow instead of merging locally.
Work in a worktree branch:
  atdd branch <issue-number>

CI bypass (requires CI=true):
  CI=true ATDD_ALLOW_MAIN_MERGE=1 git merge ...

EOF
exit 1
