#!/usr/bin/env bash
set -euo pipefail

# Protected branches keep the full CI parity gate.
# Feature branches use a faster gate and let GitHub CI run the full suite.
# Override in emergencies only: CCS_SKIP_PREPUSH_GATE=1 git push --no-verify

CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
BASE_BRANCH="${CCS_PR_BASE:-}"

if [[ -z "$BASE_BRANCH" ]]; then
  if [[ "$CURRENT_BRANCH" == "main" || "$CURRENT_BRANCH" =~ ^hotfix/ || "$CURRENT_BRANCH" =~ ^kai/hotfix- ]]; then
    BASE_BRANCH="main"
  else
    BASE_BRANCH="dev"
  fi
fi

if [[ "$CURRENT_BRANCH" == "main" || "$CURRENT_BRANCH" == "dev" || "$CURRENT_BRANCH" =~ ^hotfix/ || "$CURRENT_BRANCH" =~ ^kai/hotfix- ]]; then
  echo "[i] Protected branch detected, running full CI parity gate..."
  bun run validate:ci-parity
  exit 0
fi

echo "[i] Feature branch detected, running fast pre-push gate..."
echo "    branch: $CURRENT_BRANCH"
echo "    base:   $BASE_BRANCH"

bun run typecheck
bun run lint:fix
bun run format:check

git fetch origin "$BASE_BRANCH" --quiet || true
DIFF_RANGE="HEAD"
if git show-ref --verify --quiet "refs/remotes/origin/$BASE_BRANCH"; then
  DIFF_RANGE="origin/$BASE_BRANCH...HEAD"
fi

CHANGED_FILES="$(git diff --name-only "$DIFF_RANGE" || true)"

if printf '%s\n' "$CHANGED_FILES" | grep -q '^ui/'; then
  echo "[i] UI changes detected, running ui:validate..."
  bun run ui:validate
fi

if printf '%s\n' "$CHANGED_FILES" | grep -qE '^(\.github/workflows/|scripts/github/|tests/unit/scripts/github/)'; then
  echo "[i] GitHub workflow changes detected, running workflow tests..."
  bun test tests/unit/scripts/github
fi

if printf '%s\n' "$CHANGED_FILES" | grep -qE '^(src/commands/update-command.ts|tests/unit/commands/update-command-current-install.test.ts|tests/integration/update-command-install-origin.test.ts)'; then
  echo "[i] Update command changes detected, running targeted update tests..."
  bun test tests/unit/commands/update-command-current-install.test.ts tests/integration/update-command-install-origin.test.ts
fi

if printf '%s\n' "$CHANGED_FILES" | grep -qE '^(src/cursor/cursor-models.ts|tests/unit/cursor/cursor-models.test.ts)'; then
  echo "[i] Cursor model changes detected, running targeted cursor model tests..."
  bun test tests/unit/cursor/cursor-models.test.ts
fi

echo "[OK] Fast pre-push gate passed."
