#!/usr/bin/env bash
set -uo pipefail

payload=$(cat)
cwd=$(printf '%s' "$payload" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("cwd", ""))' 2>/dev/null) || cwd=
stop_hook_active=$(printf '%s' "$payload" | python3 -c 'import json,sys; print(str(json.load(sys.stdin).get("stop_hook_active") is True).lower())' 2>/dev/null) ||
  stop_hook_active=false

test "$stop_hook_active" = true && exit 0
test -n "$cwd" || cwd=$PWD

root=$(cd "$(dirname "$0")/.." && pwd)
repo=$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null) || exit 0
test "$repo" = "$root" || exit 0
checker=${CODEX_STOP_CHECKER:-$root/scripts/completion-check}

block() {
  python3 -c 'import json,sys; print(json.dumps({"decision":"block","reason":sys.argv[1]}))' "$1"
  exit 0
}

reason=$("$checker")
status=$?
if test "$status" -ne 0; then
  test -n "$reason" || reason="Completion checks failed; fix them before stopping."
  block "$reason"
fi
