name: PR Endpoint Performance Check

on: [pull_request]

jobs:
  endpoint-performance-check:
    name: Test All Endpoints (< 1s)
    runs-on: ubuntu-latest

    steps:
      - name: Checkout PR branch
        uses: actions/checkout@v4

      - name: Setup .NET 10
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: "10.0.x"

      - name: Restore dependencies
        run: dotnet restore Webzine.sln

      - name: Build solution
        run: dotnet build Webzine.sln --no-restore --configuration Release

      - name: Run unit tests
        run: |
          dotnet test Webzine.Entity.Tests/Webzine.Entity.Tests.csproj \
            --no-build \
            --configuration Release \
            --logger "console;verbosity=normal"

      - name: Start Webzine application
        run: |
          dotnet run \
            --project Webzine.WebApplication/Webzine.WebApplication.csproj \
            --configuration Release \
            --no-build \
            -- --urls "http://localhost:5038" &

          echo "Attente du démarrage de l'application..."
          timeout 60 bash -c '
            until curl -sf http://localhost:5038 > /dev/null 2>&1; do
              sleep 1
            done
          '
          echo "Application prête !"

      - name: Test endpoint response times
        id: perf_test
        run: |
          chmod +x scripts/test-endpoints.sh
          bash scripts/test-endpoints.sh http://localhost:5038 1000 2>&1 | tee /tmp/webzine_endpoint_output.txt
          EXIT_CODE=${PIPESTATUS[0]}
          
          FAIL_COUNT=$(grep -c "\[ÉCHEC\]\|\[LENT\]" /tmp/webzine_endpoint_output.txt || echo 0)
          echo "failed=$FAIL_COUNT" >> "$GITHUB_OUTPUT"
          echo "exit_code=$EXIT_CODE" >> "$GITHUB_OUTPUT"
          
          exit $EXIT_CODE

      - name: Post performance report as PR comment
        if: always()
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
          GITEA_SERVER_URL: ${{ gitea.server_url }}
          REPO: ${{ gitea.repository }}
          PR_NUMBER: ${{ gitea.event.pull_request.number }}
        run: |
          # Lire le rapport original
          RAW_REPORT=$(cat /tmp/webzine_endpoint_output.txt)
          FAILED_COUNT="${{ steps.perf_test.outputs.failed }}"
          
          # Convertir le rapport ANSI en Markdown avec couleurs
          # Supprimer d'abord les codes ANSI pour le traitement
          CLEAN_REPORT=$(echo "$RAW_REPORT" | sed 's/\x1b\[[0-9;]*m//g')
          
          # Générer le rapport formaté en Markdown avec couleurs
          FORMATTED_REPORT=$(echo "$CLEAN_REPORT" | sed \
          -e 's/^\[OK\] /✅ /' \
          -e 's/^\[LENT\] /⚠️  /' \
          -e 's/^\[ÉCHEC\] /❌ /' \
          -e 's/^── \(.*\)$/\n### ── \1/' \
          -e 's/^→/  •/' \
          -e 's/^\(Total.*\)$/\n**\1**/' \
          -e 's/^\(Réussis.*\)$/**✅ \1**/' \
          -e 's/^\(Échecs.*\)$/**❌ \1**/' \
          -e 's/^\(❌ ENDPOINTS EN ÉCHEC.*\)$/\n### \1/' \
          -e 's/^\(La PR doit.*\)$/\n**❌ \1**/' \
          -e 's/^╔\(.*\)╗$/```\n╔\1╗/' \
          -e 's/^╚\(.*\)╝$/╚\1╝\n```/')
          
          if [ "${FAILED_COUNT:-0}" -gt 0 ]; then
            HEADER="## ❌ Vérification des performances ÉCHOUÉE"
            INTRO="${FAILED_COUNT} endpoint(s) ont dépassé 1 seconde ou retourné une erreur serveur."
            STATUS="❌ ÉCHEC"
          else
            HEADER="## ✅ Vérification des performances RÉUSSIE"
            INTRO="Tous les endpoints ont répondu en moins d'une seconde."
            STATUS="✅ SUCCÈS"
          fi
          
          BODY=$(cat <<EOF
          $HEADER
          
          $INTRO
          
          ### Rapport complet des tests :
          
          $FORMATTED_REPORT
          
          ---
          **Statut**: $STATUS  
          **Seuil**: 1000ms  
          **Vérifié par**: Workflow PR Endpoint Performance
          EOF
          )
          
          curl -s -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$(jq -n --arg body "$BODY" '{body: $body}')" \
            "$GITEA_SERVER_URL/api/v1/repos/$REPO/issues/$PR_NUMBER/comments"
          
          mkdir -p /tmp/artifacts
          cp /tmp/webzine_endpoint_output.txt /tmp/artifacts/performance-report.txt

      - name: Upload performance report
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: performance-report
          path: /tmp/artifacts/
          retention-days: 7

      - name: Enforce performance gate
        if: always()
        run: |
          FAILED="${{ steps.perf_test.outputs.failed }}"
          if [ "${FAILED:-0}" -gt 0 ]; then
            echo "❌ PR REJETÉE : ${FAILED} endpoint(s) n'ont pas respecté le seuil d'une seconde."
            echo "   Corrigez les endpoints lents ou en erreur avant de fusionner."
            echo ""
            echo "Résumé des problèmes :"
            if [ -f /tmp/webzine_endpoint_output.txt ]; then
              grep -E "\[ÉCHEC\]|\[LENT\]" /tmp/webzine_endpoint_output.txt || echo "  (aucun détail disponible)"
            else
              echo "  (fichier de rapport non disponible)"
            fi
            exit 1
          else
            echo "✅ Tous les endpoints ont passé le contrôle de performance."
          fi