#!/bin/bash
# Test Docker build cache functionality locally
# Usage: scripts/test-docker-cache.sh

set -e

echo "🧪 Testing Docker Build Cache"
echo "============================"
echo ""

# Check requirements
if ! command -v docker >/dev/null 2>&1; then
    echo "❌ Docker not found. Please install Docker first."
    exit 1
fi

if ! command -v go >/dev/null 2>&1; then
    echo "❌ Go not found. Please install Go 1.26.1+."
    exit 1
fi

echo "✅ Requirements met"
echo ""

# 1. Calculate dependency hash (same as CI)
echo "1. Calculating dependency hash..."
# Use shasum on macOS, sha256sum on Linux
if command -v sha256sum >/dev/null 2>&1; then
    DEPS_HASH=$(sha256sum go.mod go.sum | sha256sum | cut -d' ' -f1 | head -c 12)
else
    DEPS_HASH=$(shasum -a 256 go.mod go.sum | shasum -a 256 | cut -d' ' -f1 | head -c 12)
fi
echo "   Dependency hash: $DEPS_HASH"
echo ""

# 2. Build Docker cache image
echo "2. Building Docker cache image..."
IMAGE_NAME="dance-lessons-coach-build-cache:$DEPS_HASH"
echo "   Image name: $IMAGE_NAME"

docker build -t "$IMAGE_NAME" -f Dockerfile.build .
echo "✅ Docker image built successfully"
echo ""

# 3. Test running commands in Docker
echo "3. Testing Docker execution..."

echo "   Testing 'go version'..."
docker run --rm -v "$(pwd):/workspace" -w /workspace "$IMAGE_NAME" go version
echo "   ✅ Go version command works"

echo "   Testing 'go build'..."
docker run --rm -v "$(pwd):/workspace" -w /workspace "$IMAGE_NAME" go build -o /tmp/test ./cmd/greet
echo "   ✅ Go build command works"

echo "   Testing 'swag' availability..."
docker run --rm -v "$(pwd):/workspace" -w /workspace "$IMAGE_NAME" swag --version || echo "   ⚠️  Swag not available"
echo ""

# 4. Performance comparison
echo "4. Performance comparison..."

echo "   Running 'go build' natively..."
START=$(date +%s%N)
go build -o /tmp/native-test ./cmd/greet > /dev/null 2>&1
NATIVE_TIME=$((($(date +%s%N) - $START)/1000000))
echo "   Native build: ${NATIVE_TIME}ms"

echo "   Running 'go build' in Docker..."
START=$(date +%s%N)
docker run --rm -v "$(pwd):/workspace" -w /workspace "$IMAGE_NAME" go build -o /tmp/docker-test ./cmd/greet > /dev/null 2>&1
DOCKER_TIME=$((($(date +%s%N) - $START)/1000000))
echo "   Docker build: ${DOCKER_TIME}ms"

echo "   Overhead: $((DOCKER_TIME - NATIVE_TIME))ms"
echo ""

# Clean up
rm -f /tmp/native-test /tmp/docker-test

echo "✅ Docker cache testing complete!"
echo ""
echo "💡 The Docker image is ready for CI use."
echo "💡 Push this image to your registry for CI caching:"
echo "   docker tag $IMAGE_NAME your-registry/$IMAGE_NAME"
echo "   docker push your-registry/$IMAGE_NAME"