#!/bin/bash
# Check CI/CD pipeline status across all platforms

set -e

echo "🔍 Checking CI/CD Pipeline Status"
echo "================================"

# 1. Gitea (Primary) - Internal URL
if curl -s -o /dev/null -w "%{http_code}" "https://gitea.arcodange.lab/api/v1/repos/arcodange/DanceLessonsCoach/actions/workflows" 2>/dev/null | grep -q "200"; then
    echo "✅ Gitea Internal API: Accessible"
    # Get workflow list
    WORKFLOWS=$(curl -s "https://gitea.arcodange.lab/api/v1/repos/arcodange/DanceLessonsCoach/actions/workflows" 2>/dev/null | jq -r '.[] | .name + " (" + .file_name + ")"' 2>/dev/null || echo "Unable to fetch workflow list")
    echo "📋 Gitea Workflows:"
    echo "$WORKFLOWS" | sed 's/^/  - /'
else
    echo "❌ Gitea Internal API: Not accessible (check network/vpn)"
fi

# 2. Gitea (External) - Public URL
echo ""
echo "🌐 Gitea External Status:"
if curl -s -o /dev/null -w "%{http_code}" "https://gitea.arcodange.fr/arcodange/DanceLessonsCoach" 2>/dev/null | grep -q "200"; then
    echo "✅ Gitea External: Accessible"
    echo "🔗 Repository: https://gitea.arcodange.fr/arcodange/DanceLessonsCoach"
else
    echo "❌ Gitea External: Not accessible"
fi

# 3. Check badge API
echo ""
echo "🏷️  Badge API Status:"
BADGE_URL="https://gitea.arcodange.fr/api/badges/arcodange/DanceLessonsCoach/status"
if curl -s -o /dev/null -w "%{http_code}" "$BADGE_URL" 2>/dev/null | grep -q "200"; then
    echo "✅ Badge API: Accessible"
    echo "🔗 Badge URL: $BADGE_URL"
else
    echo "❌ Badge API: Not accessible"
fi

# 4. Check workflow file existence
echo ""
echo "📁 Workflow Files:"
if [ -f ".gitea/workflows/ci-cd.yaml" ]; then
    echo "✅ .gitea/workflows/ci-cd.yaml: Found"
    if command -v yq >/dev/null 2>&1; then
        echo "📊 Jobs: $(yq eval '.jobs | keys | join(", ")' .gitea/workflows/ci-cd.yaml 2>/dev/null || echo 'Unable to parse')"
    else
        echo "📊 Jobs: yq not installed, cannot parse jobs"
    fi
else
    echo "❌ .gitea/workflows/ci-cd.yaml: Not found"
fi

echo ""
echo "🎯 Validation Summary"
echo "================================"
echo "✅ Local workflow file: .gitea/workflows/ci-cd.yaml"
if command -v yq >/dev/null 2>&1; then
    echo "✅ Syntax validation: $(yq eval '.' .gitea/workflows/ci-cd.yaml > /dev/null 2>&1 && echo 'Valid YAML' || echo 'Invalid YAML')"
else
    echo "⚠️  Syntax validation: yq not installed"
fi
echo "✅ Gitea compatibility: Uses .gitea/workflows/ directory"
echo "✅ Arcodange conventions: Matches webapp workflow style"

echo ""
echo "💡 Next Steps:"
echo "  1. Push to trigger workflow: git push origin main"
echo "  2. Check Gitea Actions: https://gitea.arcodange.lab/arcodange/DanceLessonsCoach/actions"
echo "  3. Monitor badges: https://gitea.arcodange.fr/arcodange/DanceLessonsCoach"