#!/bin/bash
# Test CI/CD setup locally without requiring Gitea instance

set -e

echo "🧪 Testing CI/CD Local Setup"
echo "=============================="

# 1. Validate YAML syntax
echo "1. Validating YAML syntax..."
if command -v yq >/dev/null 2>&1; then
    yq eval '.' .gitea/workflows/go-ci-cd.yaml > /dev/null
    yq eval '.' .gitea/workflows/dockerimage.yaml > /dev/null
    echo "✅ YAML syntax is valid"
else
    echo "⚠️  yq not found, skipping YAML validation"
fi

# 2. Validate workflow structure
echo "2. Validating workflow structure..."
./scripts/cicd/validate-workflow.sh

# 3. Check docker-compose configuration
echo "3. Checking docker-compose configuration..."
docker compose -f docker-compose.cicd-test.yml config > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ docker-compose configuration is valid"
else
    echo "❌ docker-compose configuration has issues"
    exit 1
fi

# 4. Check for required files
echo "4. Checking required files..."
REQUIRED_FILES=(
    ".gitea/workflows/go-ci-cd.yaml"
    ".gitea/workflows/dockerimage.yaml"
    "docker-compose.cicd-test.yml"
    "config/runner.example"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "$file" ]; then
        echo "✅ $file exists"
    else
        echo "❌ $file missing"
        exit 1
    fi
done

# 5. Show configuration status
echo "5. Configuration status..."
if [ -f "config/runner" ]; then
    echo "✅ config/runner exists (gitignored)"
    echo "📝 You can connect to Gitea instance"
else
    echo "ℹ️  config/runner not found (expected - it's gitignored)"
    echo "📝 To connect to Gitea:"
    echo "   1. Copy config/runner.example to config/runner"
    echo "   2. Fill in your Gitea runner configuration"
    echo "   3. Set environment variables:"
    echo "      export GITEA_RUNNER_REGISTRATION_TOKEN=your-token"
    echo "   4. Run: docker compose -f docker-compose.cicd-test.yml up"
fi

echo ""
echo "🎉 CI/CD Local Setup Validation Complete!"
echo "=============================="
echo "📋 Summary:"
echo "  ✅ YAML syntax validated"
echo "  ✅ Workflow structure validated"
echo "  ✅ Docker-compose configuration validated"
echo "  ✅ All required files present"
echo ""
echo "🚀 Next steps:"
echo "  1. Create config/runner file with your Gitea runner token"
echo "  2. Set GITEA_RUNNER_REGISTRATION_TOKEN environment variable"
echo "  3. Run: docker compose -f docker-compose.cicd-test.yml up"
echo ""
echo "💡 For local testing without Gitea:"
echo "  Use: ./scripts/test-cicd-simple.sh (if available)"
echo "  Or manually test workflow steps"
