#!/usr/bin/env bash
# Pre-push gate (bypass with `git push --no-verify` is FORBIDDEN — see CLAUDE.md rule 4):
#   Part 1 — owner-lock: only push to github.com/cocodedk/*
#   Part 2 — block force-push / deletion of protected branches
#   Part 3 — CLAUDE.md rules 1,4,5: 200-line file cap, full test suite, 100% coverage
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

OWNER="cocodedk"
remote_url="${2:-}"

# ── Part 1: owner-lock the push URL ───────────────────────────────────────────
# An SSH host alias from ~/.ssh/config (git@github.com-cocodedk:…) is judged by the host it
# resolves to, so origin's alias passes and an alias for any other host is still refused.
target_url="$remote_url"
if [[ "$remote_url" =~ ^git@([^:]+):(.*)$ ]]; then
  real_host=$(ssh -G "${BASH_REMATCH[1]}" 2>/dev/null | awk '$1 == "hostname" { print $2; exit }') || true
  target_url="git@${real_host:-${BASH_REMATCH[1]}}:${BASH_REMATCH[2]}"
fi
case "$target_url" in
  https://github.com/$OWNER/*|git@github.com:$OWNER/*|ssh://git@github.com/$OWNER/*) ;;
  *)
    echo "pre-push: refusing — push URL is not under github.com/$OWNER" >&2
    echo "  remote: ${1:-?}" >&2
    echo "  url:    $remote_url" >&2
    exit 1
    ;;
esac

# ── Part 2: guard protected branches; note whether commits are being pushed ───
# git feeds one line per ref on stdin: <local_ref> <local_sha> <remote_ref> <remote_sha>
ZERO='0000000000000000000000000000000000000000'
pushing_commits=0
while read -r _local_ref local_sha remote_ref remote_sha; do
  case "$remote_ref" in
    refs/heads/*) if [ "$local_sha" != "$ZERO" ]; then pushing_commits=1; fi ;;
  esac
  case "$remote_ref" in
    refs/heads/main|refs/heads/master|refs/heads/release) ;;
    *) continue ;;
  esac
  branch="${remote_ref#refs/heads/}"
  if [ "$local_sha" = "$ZERO" ]; then
    echo "pre-push: blocked deletion of protected branch '$branch'" >&2
    exit 1
  fi
  if [ "$remote_sha" != "$ZERO" ] && \
     ! git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null; then
    echo "pre-push: blocked non-fast-forward push to protected branch '$branch'" >&2
    exit 1
  fi
done

# Tag-only pushes and branch deletions carry no commits — skip the heavy gate.
if [ "$pushing_commits" -eq 0 ]; then
  echo "pre-push: no branch commits in this push — skipping the test/coverage gate" >&2
  exit 0
fi

# ── Part 3: full verification gate (runs once per push) ───────────────────────
[ -f "$HOME/.chess-env.sh" ] && source "$HOME/.chess-env.sh"

echo "pre-push: checking file lengths (<= 200)"
./scripts/check-file-length.sh

echo "pre-push: running tests + 100% coverage gate"
./gradlew --quiet test koverVerify </dev/null

echo "pre-push: OK"
