#!/usr/bin/env bash
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE

branch=$(git rev-parse --abbrev-ref HEAD)

if [ "$branch" = "main" ]; then
  exit 0
fi

# Stash untracked/modified work-tree files (unrelated to the push) so rebase
# doesn't abort. trap restores them on every exit path.
STASH_MARKER="pre-push-auto-$$"
STASH_CREATED=false
cleanup_stash() {
  if [ "$STASH_CREATED" = true ]; then
    STASH_REF=$(git stash list | grep -F "$STASH_MARKER" | head -1 | cut -d: -f1)
    if [ -n "$STASH_REF" ]; then
      if ! git stash pop "$STASH_REF" --quiet; then
        echo "WARNING: stash pop conflicted. Your changes are preserved in '$STASH_REF' — resolve manually."
      fi
    fi
  fi
}
trap cleanup_stash EXIT

if [ -n "$(git status --porcelain)" ]; then
  if git stash push -u -m "$STASH_MARKER" --quiet; then
    STASH_CREATED=true
    echo "Stashed unrelated work-tree changes before rebase ($STASH_MARKER)"
  fi
fi

# Rebase on main before push
git fetch origin main --quiet
if ! git rebase origin/main --quiet; then
  echo "Rebase on main failed — resolve conflicts first."
  git rebase --abort
  exit 1
fi
echo "Rebased on origin/main"

# Prefer project venv (has pytest and all deps), fall back to uv-managed Python 3.11+
# In worktrees, --show-toplevel points to the worktree, not the main repo.
# The .venv lives in the main repo, so also check --git-common-dir's parent.
REPO_ROOT="$(git rev-parse --show-toplevel)"
MAIN_ROOT="$(cd "$(git rev-parse --git-common-dir)/.." && pwd)"
PLUGIN_VENV="$HOME/.autosearch/venv/bin/python"
if [ -x "$REPO_ROOT/.venv/bin/python3" ]; then
  PYTHON="$REPO_ROOT/.venv/bin/python3"
elif [ -x "$MAIN_ROOT/.venv/bin/python3" ]; then
  PYTHON="$MAIN_ROOT/.venv/bin/python3"
elif [ -x "$PLUGIN_VENV" ]; then
  PYTHON="$PLUGIN_VENV"
else
  PYTHON=$(command -v python3.11 || command -v python3.12 || echo "")
  if [ -z "$PYTHON" ]; then
    for p in "$HOME"/.local/share/uv/python/cpython-3.1*/bin/python3; do
      [ -x "$p" ] && PYTHON="$p" && break
    done
  fi
fi
if [ -z "$PYTHON" ]; then
  echo "warning: Python 3.10+ not found, skipping tests"
  exit 0
fi

PYTHONPATH="$REPO_ROOT" "$PYTHON" -m pytest tests/ -x -q \
  -m "not real_llm and not perf and not slow and not network" 2>/dev/null \
  || PYTHONPATH="$REPO_ROOT" "$PYTHON" -m unittest discover -s tests -q

# --- Version bump check ---
# Block push if source files changed since last tag but version not bumped.
# Only checks on non-main branches (main pushes come from merged PRs).
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -n "$LAST_TAG" ]; then
  TAG_VERSION="${LAST_TAG#v}"
  PLUGIN_VERSION=$("$PYTHON" -c "import json; print(json.load(open('$REPO_ROOT/.claude-plugin/plugin.json'))['version'])" 2>/dev/null || echo "")

  if [ "$TAG_VERSION" = "$PLUGIN_VERSION" ]; then
    # Check if source files changed since the tag
    SOURCE_CHANGES=$(git diff --name-only "$LAST_TAG"..HEAD -- \
      commands/ agents/ skills/ lib/ channels/ scripts/ \
      PROTOCOL.md CLAUDE.md .claude-plugin/ \
      2>/dev/null | head -1)

    if [ -n "$SOURCE_CHANGES" ]; then
      echo ""
      echo "[VERSION] Source files changed since $LAST_TAG but version is still $PLUGIN_VERSION."
      echo "          Run: scripts/bump-version.sh"
      echo ""
      exit 1
    fi
  fi
fi
