#!/bin/bash
# Comprehensive Docker-based CI/CD testing script
# Tests workflows locally using Docker containers

set -e

echo "🐳 Docker-based CI/CD Testing"
echo "================================"

# 1. Check Docker is available
if ! command -v docker >/dev/null 2>&1; then
    echo "❌ Docker not found. Please install Docker first."
    echo "   https://docs.docker.com/get-docker/"
    exit 1
fi

echo "✅ Docker is available"

# 2. Pull required images
echo ""
echo "📦 Pulling Docker images..."
docker pull gitea/act_runner:latest
docker pull pipelinecomponents/yamllint:latest
docker pull mikefarah/yq:latest

echo "✅ Images pulled successfully"

# 3. Validate YAML syntax with yq
echo ""
echo "🔍 Validating YAML syntax..."
docker run --rm \
    -v $(pwd):/workspace \
    -w /workspace \
    mikefarah/yq:latest \
    yq eval .gitea/workflows/go-ci-cd.yaml > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "✅ YAML syntax is valid"
else
    echo "❌ YAML syntax error"
    docker run --rm \
        -v $(pwd):/workspace \
        -w /workspace \
        mikefarah/yq:latest \
        yq eval .gitea/workflows/go-ci-cd.yaml || true
    exit 1
fi

# 4. Lint YAML with yamllint
echo ""
echo "🧹 Linting YAML..."
docker run --rm \
    -v $(pwd):/workspace \
    -w /workspace \
    pipelinecomponents/yamllint:latest \
    yamllint .gitea/workflows/

if [ $? -eq 0 ]; then
    echo "✅ YAML linting passed"
else
    echo "❌ YAML linting failed"
    exit 1
fi

# 5. Run workflow with act
echo ""
echo "🚀 Running CI/CD workflow..."
docker run --rm \
    -v $(pwd):/workspace \
    -w /workspace \
    -e GITEA_INTERNAL="https://gitea.arcodange.lab/" \
    -e GITEA_EXTERNAL="https://gitea.arcodange.fr/" \
    -e GITEA_ORG="arcodange" \
    -e GITEA_REPO="DanceLessonsCoach" \
    gitea/act_runner:latest \
    act -W .gitea/workflows/go-ci-cd.yaml --rm

if [ $? -eq 0 ]; then
    echo "✅ Workflow executed successfully"
else
    echo "❌ Workflow execution failed"
    exit 1
fi

echo ""
echo "🎉 All CI/CD tests passed!"
echo "================================"
echo "📁 Workflow: .gitea/workflows/ci-cd.yaml"
echo "✅ YAML syntax validated"
echo "✅ YAML linting passed"
echo "✅ Workflow execution successful"
echo "🎯 Ready for production deployment"

echo ""
echo "💡 Next Steps:"
echo "  1. Commit changes: git commit -m '🤖 ci: update workflow'"
echo "  2. Push to trigger: git push origin main"
echo "  3. Monitor pipeline: https://gitea.arcodange.lab/arcodange/DanceLessonsCoach/actions"
echo "  4. Check badges: https://gitea.arcodange.fr/arcodange/DanceLessonsCoach"
