#!/bin/bash
# SPDX-FileCopyrightText: 2026 Daniel J. Mazure
# SPDX-License-Identifier: MIT
#
# pre-push hook — runs heavyweight CI simulation before pushing tags.
#
# On regular pushes: nothing extra (pre-commit already covers it).
# On tag pushes (v*): runs tools/test-ci-local.sh Docker simulation
# to catch CI environment drift before a release hits GitHub Actions.
#
# Install: git config core.hooksPath already points to sdk/infra/hooks/

set -eo pipefail

# ── Detect tag push ──
# Git passes refspec info via stdin: <local ref> <local sha> <remote ref> <remote sha>
TAG_PUSH=false
while read -r local_ref local_sha remote_ref remote_sha; do
    if [[ "$remote_ref" == refs/tags/v* ]]; then
        TAG_PUSH=true
        TAG_NAME="${remote_ref#refs/tags/}"
        break
    fi
done

if [ "$TAG_PUSH" = false ]; then
    # Normal branch push — nothing extra needed
    exit 0
fi

echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  🏷️  Tag push detected: $TAG_NAME"
echo "  Running Docker CI simulation before release push..."
echo "═══════════════════════════════════════════════════════════"
echo ""

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"

# Check Docker availability
if ! command -v docker &>/dev/null || ! docker info &>/dev/null 2>&1; then
    echo "⚠️  Docker not available — skipping CI simulation."
    echo "   Run './tools/test-ci-local.sh' manually before pushing."
    exit 0
fi

# Run the full CI simulation (both tiers)
if "$REPO_ROOT/tools/test-ci-local.sh" all; then
    echo ""
    echo "✅ Docker CI simulation passed — safe to push $TAG_NAME"
else
    echo ""
    echo "❌ Docker CI simulation FAILED — aborting tag push."
    echo "   Fix the issues above before pushing $TAG_NAME."
    echo "   To bypass: git push --no-verify"
    exit 1
fi
