#!/usr/bin/env sh

set -eu

# CI is the contract. The full validation suite (lint:ratchet, format, lockfile-sync, arch,
# versions, python hooks, unit/integration/e2e tests, build, post-build schema gates — see
# `.github/workflows/ci.yml` `lint`, `build`, and `test` jobs) runs once at the PR boundary
# against the pushed commit's checked-out state. This hook stays local and cheap: typecheck and
# lint only, so a push fails fast on the two error classes that are both common and fast to
# check, without re-running work CI already owns. A feature-branch push may otherwise be red;
# the PR boundary is where green is required (`rules/dev-workflow.md` §Validation Commands).

SERVER_DIR=server

# A push that only DELETES remote refs has no content to validate. Git feeds this hook
# `<local ref> <local sha> <remote ref> <remote sha>` per ref, and a deletion is the all-zero
# local sha. Without this, `git push origin --delete <branch>` runs the checks against
# whatever happens to be in the working tree — so retiring a merged branch from a shared
# worktree fails on someone else's in-flight edits, and the only way through is --no-verify,
# which disables the gate for real pushes too.
#
# Reads stdin, so it must run before anything else consumes it. Falls through when stdin is
# empty (the hook invoked by hand) rather than treating "no refs" as "nothing to check".
DELETIONS_ONLY=yes
SAW_REF=no
while read -r _local_ref local_sha _remote_ref _remote_sha; do
  SAW_REF=yes
  case "$local_sha" in
    *[!0]*) DELETIONS_ONLY=no ;;
  esac
done
if [ "$SAW_REF" = yes ] && [ "$DELETIONS_ONLY" = yes ]; then
  echo "🔍 Pre-push: deletion-only push — no content to validate."
  exit 0
fi

echo "🔍 Running pre-push validation (typecheck + lint)..."
echo ""

echo "1/2 Type checking..."
npm --prefix "$SERVER_DIR" run typecheck || { echo "❌ Type checking failed"; exit 1; }

echo ""
echo "2/2 Linting..."
npm --prefix "$SERVER_DIR" run lint:ratchet || { echo "❌ Lint ratchet failed (new violations introduced)"; exit 1; }

echo ""
echo "✅ Pre-push validation passed (typecheck + lint). Full suite runs in CI at the PR boundary."
echo ""
