#!/usr/bin/env bash
# Gate script for the Claude Code PreToolUse hook on `gh pr create`.
#
# Enforces the project's "smoke + lint before every PR" discipline that
# was repeatedly forgotten when relying on memory alone. The harness
# calls this script before every `gh pr create` Bash invocation; on
# any failure it exits 2, which blocks the PR creation.
#
# Steps:
#   1. Run the full smoke suite (`scripts/smoke/run-all.ts`)
#   2. Run ESLint on the JS/TS files changed vs origin/main
# Either step failing aborts.
#
# This script ignores stdin (the hook payload is informational only —
# the `if: Bash(gh pr create*)` filter in settings already restricts
# WHEN this fires).
set -euo pipefail

REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
cd "$REPO_ROOT"

echo "[pre-pr-create] running smoke suite..." >&2
if ! npx tsx scripts/smoke/run-all.ts >&2; then
    echo "" >&2
    echo "BLOCKED: smoke suite failed. Fix the failures above before opening a PR." >&2
    exit 2
fi

echo "[pre-pr-create] linting changed files..." >&2
# Files changed on this branch vs origin/main, limited to JS/TS that
# eslint can parse. --diff-filter=ACMR EXCLUDES deletions (D) and
# typechanges — passing deleted paths to eslint trips "No files
# matching the pattern X were found" and aborts the gate. `|| true`
# so the pipeline doesn't die on an empty diff.
CHANGED=$(git diff --diff-filter=ACMR --name-only origin/main...HEAD 2>/dev/null | grep -E '\.(ts|tsx|js|jsx|mjs|cjs)$' || true)

if [ -z "$CHANGED" ]; then
    echo "[pre-pr-create] no JS/TS files changed vs origin/main — skipping lint." >&2
else
    # shellcheck disable=SC2086
    if ! echo "$CHANGED" | xargs npx eslint >&2; then
        echo "" >&2
        echo "BLOCKED: ESLint failed on changed files. Fix or rebase before opening a PR." >&2
        exit 2
    fi
fi

echo "[pre-pr-create] smoke + lint passed — proceeding with gh pr create" >&2
exit 0
