#!/usr/bin/env sh
#
# Pre-commit: auto-format staged files, then run the tests the commit needs —
# both full suites for a big or risky commit, only the related tests for a
# small one, none for docs alone (see step 2). The commit is ABORTED unless
# every test it runs passes.
#
# Activated via `core.hooksPath=.husky` (set by the package.json "prepare"
# script on `npm install`). No husky/lint-staged runtime required.

# Abort the commit on the first failing command (formatting error or failing test).
set -e

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

# ── 1. Format staged files with Prettier, then re-stage them ────────────────
# Only Added/Copied/Modified/Renamed paths in the index. --ignore-unknown lets
# Prettier silently skip anything it can't parse, so we can hand it every staged
# path without filtering by extension. NUL-delimited (-z / -0) so paths with
# spaces are handled correctly.
#
# NOTE: this re-adds the *whole* file. If you intentionally staged only part of
# a file, review the result after the auto-format.
STAGED="$(git diff --cached --name-only --diff-filter=ACMR)"
if [ -n "$STAGED" ]; then
  PRETTIER="$ROOT/node_modules/.bin/prettier"
  if [ -x "$PRETTIER" ]; then
    set -- "$PRETTIER"
  else
    set -- npx --no-install prettier
  fi

  echo "🎨 Formatting staged files with Prettier..."
  git diff --cached --name-only --diff-filter=ACMR -z | xargs -0 "$@" --write --ignore-unknown
  git diff --cached --name-only --diff-filter=ACMR -z | xargs -0 git add
else
  echo "🎨 No staged files to format."
fi

# ── 2. Run tests — commit is blocked unless all pass ────────────────────────
# Each suite is retried once on failure. The full run executes dozens of test
# files concurrently, each starting its own server (plus the CLI suite's
# spawned child processes with hard kill timeouts), so a loaded machine can
# produce a one-off timing failure unrelated to the commit. A real regression
# is deterministic: it fails both runs and still blocks the commit. This keeps
# the gate strict without making commits a dice roll on machine load.
run_suite() {
  # $1 = human label, $2 = shell command
  echo "🧪 Running $1 tests..."
  if sh -c "$2"; then
    return 0
  fi
  echo "⚠️  $1 suite failed — retrying once to rule out machine-load flakiness..."
  if sh -c "$2"; then
    echo "✅ $1 suite passed on retry — treating the first failure as a load flake."
    echo "   If this keeps happening, the flaky test above deserves a real fix."
    return 0
  fi
  echo "❌ $1 suite failed twice — genuine failure, aborting the commit."
  return 1
}

# The frontend suite needs NODE_ENV=test: a shell exporting
# NODE_ENV=production gets React's production build, where act() throws.
CLIENT_FULL="NODE_ENV=test npm run test:client"

# How much to run. A small commit runs only the tests that touch what it
# stages; a big or risky one runs both full suites, as does
# AGENTHUB_FULL_TESTS=1. Docs alone (*.md, docs/) run nothing.
#   client/ files  → `vitest related`: vitest's own import graph.
#   anything else  → every server/__tests__ file that names the file's module
#                    (a string match: wide on purpose, `db` reaches most).
# ponytail: name matching misses a test that reaches a module only through
# another one; the full run before a release still catches that.
SMALL_MAX=10
CODE="$(git diff --cached --name-only --diff-filter=ACMRD | grep -vE '\.md$|^docs/' || true)"
COUNT=$(printf '%s\n' "$CODE" | grep -c . || true)
FULL=0
[ "${AGENTHUB_FULL_TESTS:-0}" = "1" ] && FULL=1
[ "$COUNT" -gt "$SMALL_MAX" ] && FULL=1
# A dependency, build/test config, this hook or a deleted file can break
# anything, whatever imports it.
if printf '%s\n' "$CODE" | grep -qE '(^|/)package(-lock)?\.json$|(^|/)(vite|vitest|tailwind|postcss|tsconfig)[^/]*$|^\.husky/|^scripts/test-server\.js$'; then
  FULL=1
fi
if git diff --cached --name-only --diff-filter=D | grep -vE '\.md$|^docs/' | grep -q .; then
  FULL=1
fi

if [ "$COUNT" -eq 0 ]; then
  echo "📝 Docs only — no tests to run."
elif [ "$FULL" = "1" ]; then
  echo "🧪 Full run ($COUNT code files staged)."
  run_suite backend "npm run test:server"
  run_suite frontend "$CLIENT_FULL"
else
  echo "🧪 Small commit ($COUNT code files) — running the related tests only."
  OTHER="$(printf '%s\n' "$CODE" | grep -v '^client/' || true)"
  CLIENT="$(printf '%s\n' "$CODE" | grep '^client/' | sed 's|^client/||' || true)"

  if [ -n "$OTHER" ]; then
    RELATED="$(
      printf '%s\n' "$OTHER" | while IFS= read -r f; do
        case "$f" in
          server/__tests__/*.test.js) echo "$f" ;;
          *)
            name="$(basename "$f")"
            name="${name%.*}"
            grep -lF -- "$name" server/__tests__/*.test.js 2>/dev/null || true
            ;;
        esac
      done | sort -u | tr '\n' ' '
    )"
    if [ -n "$RELATED" ]; then
      run_suite "backend ($(echo $RELATED | wc -w) files)" "node scripts/test-server.js $RELATED"
    else
      echo "⏭️  No server test names a staged file — backend skipped."
    fi
  fi

  if [ -n "$CLIENT" ]; then
    LIST="$(printf '%s\n' "$CLIENT" | tr '\n' ' ')"
    run_suite "frontend (related)" "cd client && NODE_ENV=test NODE_OPTIONS=--no-experimental-webstorage npx vitest related --run --passWithNoTests $LIST"
  fi
fi

echo "✅ Formatting applied and the tests passed — proceeding with commit."
