#!/usr/bin/env bash
# IceBreak pre-push hook — runs evals when src/ or evals/ has changed,
# blocks the push if the rubric pass rate falls below MIN_PASS_RATE.
#
# Install once per clone:    git config core.hooksPath .githooks
# Bypass for a single push:  git push --no-verify
#
# Exits 0 (allow push) when:
#   - no src/ or evals/ files changed in the commits being pushed
#   - .env is missing (can't run evals without keys)
#   - evals pass rate >= MIN_PASS_RATE
# Exits 1 (block push) when:
#   - evals pass rate < MIN_PASS_RATE
#
# Tolerates the occasional flaky run (Tavily index drift, GitHub data
# changes) by setting the threshold below 100%. Tighten if you want
# stricter guardrails.

set -uo pipefail

MIN_PASS_RATE="${ICEBREAK_EVAL_MIN:-0.5}"

# Read what's about to be pushed from stdin. Each line is:
#   <local-ref> <local-sha> <remote-ref> <remote-sha>
# Diff each range; if any src/ or evals/ file shows up, run evals.
src_changed="no"
zero="0000000000000000000000000000000000000000"
while read -r local_ref local_sha remote_ref remote_sha; do
    [ "$local_sha" = "$zero" ] && continue   # branch deletion
    if [ "$remote_sha" = "$zero" ]; then
        # New branch on the remote — diff against main if it exists,
        # otherwise inspect just the tip commit.
        if git rev-parse --verify --quiet main >/dev/null; then
            range="main..$local_sha"
        else
            range="$local_sha"
        fi
    else
        range="$remote_sha..$local_sha"
    fi
    if git diff --name-only "$range" 2>/dev/null | grep -qE "^(src/|evals/)"; then
        src_changed="yes"
        break
    fi
done

if [ "$src_changed" = "no" ]; then
    echo "[pre-push] No src/ or evals/ changes in this push. Skipping evals."
    exit 0
fi

if [ ! -f ".env" ]; then
    echo "[pre-push] No .env file found — evals need API keys to run."
    echo "[pre-push] Skipping (push allowed). To enable: cp .env.example .env"
    exit 0
fi

if ! command -v uv >/dev/null 2>&1; then
    echo "[pre-push] 'uv' not found in PATH — can't run evals."
    echo "[pre-push] Skipping (push allowed)."
    exit 0
fi

echo "[pre-push] src/ or evals/ changed — running evals (cheap mode)..."
echo "[pre-push] Threshold: ${MIN_PASS_RATE} (override via ICEBREAK_EVAL_MIN env var)"
echo

if uv run python -m evals.run --min-pass-rate "$MIN_PASS_RATE"; then
    echo
    echo "[pre-push] ✓ evals passed; push allowed."
    exit 0
else
    echo
    echo "[pre-push] ✗ evals fell below ${MIN_PASS_RATE} pass rate."
    echo "[pre-push]   To inspect: cat .cache/evals-*.jsonl | tail -1"
    echo "[pre-push]   To bypass:  git push --no-verify"
    exit 1
fi
