#!/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

# ── Context Guard: SDK vs Consumer (RTL-P3.536) ──
# core.hooksPath makes git run THIS hook for consumer projects too. In a
# consumer context, delegate to project-pre-push (which runs the declared
# hooks.pre_push.tests). The tag-push Docker CI below is the SDK repo's own
# release gate, not a consumer concern. Must run BEFORE the stdin refspec
# loop — exec hands stdin (the refspecs) straight to the delegate.
HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
IS_CONSUMER=false
if [ -d "vendor/routertl" ]; then
    IS_CONSUMER=true
elif [ ! -d "sdk" ]; then
    # RTL-P2.641: any repo without an sdk/ tree is a consumer. The old test
    # required project.yml AT ROOT, so IP repos (ip.yml at root, project.yml in
    # example/) fell through to the SDK release gate below and bricked their
    # v* tag pushes (REPO_ROOT mis-resolved to a dir with no test-ci-local.sh).
    IS_CONSUMER=true
fi
if [ "$IS_CONSUMER" = true ]; then
    if [ -f "$HOOK_DIR/project-pre-push" ]; then
        exec "$HOOK_DIR/project-pre-push"
    fi
    # Consumer with no project-level pre-push hook: the SDK Docker-CI release
    # gate is the SDK repo's own concern, never a consumer's. Nothing to do.
    exit 0
fi

# ── 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)"

# RTL-P2.641: the Docker CI gate is SDK-repo-only and needs the CI-sim script.
# If it's absent (hook reached a non-SDK context), skip gracefully — never
# abort a tag push on a missing internal script.
if [ ! -x "$REPO_ROOT/tools/test-ci-local.sh" ]; then
    echo "⚠️  tools/test-ci-local.sh not found at $REPO_ROOT — skipping CI simulation for $TAG_NAME."
    exit 0
fi

# 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
