#!/usr/bin/env bash
# pre-push hook — runs before every git push
# Blocks the push if unit tests, coverage, or dashboard TypeScript fail.
# Install: chmod +x .git/hooks/pre-push  (done automatically by scripts/install-hooks.sh)

set -euo pipefail

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

# Load .env so integration tests get CLICKHOUSE_USER, CLICKHOUSE_PASSWORD etc.
if [ -f ".env" ]; then
  set -a
  # shellcheck disable=SC1091
  source .env
  set +a
fi

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

pass() { echo -e "${GREEN}✓${NC} $1"; }
fail() { echo -e "${RED}✗${NC} $1"; exit 1; }
info() { echo -e "${YELLOW}▸${NC} $1"; }

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  LangSight pre-push checks"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# ── 1. Unit + regression tests ────────────────────────────────────────────────
info "Running unit + regression tests..."
if uv run pytest tests/unit/ tests/security/ \
    --override-ini="addopts=" \
    --tb=short -q 2>&1 | tee /tmp/pytest-unit.log | tail -3; then
  pass "Unit + regression tests"
else
  fail "Unit + regression tests failed — fix before pushing\n  See: /tmp/pytest-unit.log"
fi

# ── 2. Coverage ≥ 70% ─────────────────────────────────────────────────────────
info "Checking coverage threshold (≥ 70%)..."
if uv run pytest tests/unit/ \
    --override-ini="addopts=" \
    --cov=langsight --cov-fail-under=70 \
    --no-header -q 2>&1 | tail -5; then
  pass "Coverage ≥ 70%"
else
  fail "Coverage below 70% — add tests before pushing"
fi

# ── 3. Integration tests (skip if docker not running) ────────────────────────
if docker info &>/dev/null && docker compose ps 2>/dev/null | grep -q "Up"; then
  info "Docker is running — running integration tests..."
  if uv run pytest tests/integration/ -m integration \
      --override-ini="addopts=" \
      --tb=short -q 2>&1 | tail -5; then
    pass "Integration tests"
  else
    fail "Integration tests failed — fix before pushing"
  fi
else
  echo -e "${YELLOW}⚠${NC}  Docker not running — skipping integration tests (run manually: uv run pytest tests/integration/ -m integration)"
fi

# ── 4. Dashboard TypeScript ───────────────────────────────────────────────────
if [ -d "dashboard" ] && command -v npx &>/dev/null; then
  info "Checking dashboard TypeScript..."
  if (cd dashboard && npx tsc --noEmit 2>&1) | tee /tmp/tsc.log | tail -5; then
    pass "Dashboard TypeScript"
  else
    fail "Dashboard TypeScript errors — fix before pushing\n  See: /tmp/tsc.log"
  fi
else
  echo -e "${YELLOW}⚠${NC}  dashboard/ or npx not found — skipping TypeScript check"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "  ${GREEN}All pre-push checks passed ✓${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
