# ========================================
# GITHUB ACTIONS - TESTS SYSTÉMATIQUES
# Pipeline CI/CD avec validation IA automatique
# ========================================

name: 🧪 Tests Systématiques avec Validation IA

on:
  push:
    branches: [ main, master, develop ]
  pull_request:
    branches: [ main, master ]
  schedule:
    # Tests automatiques quotidiens à 2h00 UTC
    - cron: '0 2 * * *'
  workflow_dispatch:
    inputs:
      test_mode:
        description: 'Mode de test'
        required: true
        default: 'quick'
        type: choice
        options:
          - quick
          - full
          - generate-only
      ai_validation:
        description: 'Activer validation IA'
        required: false
        default: true
        type: boolean

env:
  NODE_VERSION: '18'
  TIMEOUT_MINUTES: 30

jobs:
  # ========================================
  # JOB 1: GÉNÉRATION AUTOMATIQUE DES TESTS
  # ========================================
  generate-tests:
    name: 📝 Génération Tests Automatiques
    runs-on: ubuntu-latest
    timeout-minutes: 10
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        
      - name: 🟢 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'
          
      - name: 📦 Install dependencies
        run: npm ci
        
      - name: 🔧 Generate tests
        run: npm run test:generate
        env:
          NODE_ENV: test
          
      - name: 📤 Upload generated tests
        uses: actions/upload-artifact@v4
        with:
          name: generated-tests
          path: tests/systematic/generated/
          retention-days: 7
          
      - name: 📊 Test generation report
        run: |
          echo "## 📝 Rapport Génération Tests" >> $GITHUB_STEP_SUMMARY
          echo "- Timestamp: $(date)" >> $GITHUB_STEP_SUMMARY
          echo "- Fichiers générés: $(ls tests/systematic/generated/*.test.js 2>/dev/null | wc -l)" >> $GITHUB_STEP_SUMMARY

  # ========================================
  # JOB 2: EXÉCUTION TESTS SYSTÉMATIQUES
  # ========================================
  run-systematic-tests:
    name: 🧪 Tests Systématiques
    runs-on: ubuntu-latest
    needs: generate-tests
    timeout-minutes: ${{ fromJson(env.TIMEOUT_MINUTES) }}
    
    strategy:
      matrix:
        test-suite:
          - smoke
          - llm
          - content
          - integration
        fail-fast: false
        
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        
      - name: 🟢 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'
          
      - name: 📦 Install dependencies
        run: npm ci
        
      - name: 📤 Download generated tests
        uses: actions/download-artifact@v4
        with:
          name: generated-tests
          path: tests/systematic/generated/
          
      - name: 🧪 Run test suite
        run: npm run test:${{ matrix.test-suite }}
        env:
          NODE_ENV: test
          TEST_TIMEOUT: 120000
          
      - name: 📊 Test results
        if: always()
        run: |
          echo "## 🧪 Résultats Tests ${{ matrix.test-suite }}" >> $GITHUB_STEP_SUMMARY
          echo "- Suite: ${{ matrix.test-suite }}" >> $GITHUB_STEP_SUMMARY
          echo "- Status: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY

  # ========================================
  # JOB 3: VALIDATION IA DU CONTENU
  # ========================================
  ai-content-validation:
    name: 🤖 Validation IA
    runs-on: ubuntu-latest
    needs: [generate-tests, run-systematic-tests]
    if: ${{ github.event.inputs.ai_validation != 'false' }}
    timeout-minutes: 20
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        
      - name: 🟢 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'
          
      - name: 📦 Install dependencies
        run: npm ci
        
      - name: 🤖 Test AI validation
        run: npm run test:ai-validation
        env:
          NODE_ENV: test
          # Clés API pour validation IA (secrets GitHub)
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          
      - name: 🎯 Run full systematic suite
        run: |
          if [ "${{ github.event.inputs.test_mode }}" = "full" ]; then
            npm run test:systematic
          else
            npm run test:systematic:quick
          fi
        env:
          NODE_ENV: test
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          
      - name: 📤 Upload test reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: systematic-test-reports
          path: tests/reports/
          retention-days: 30
          
      - name: 📊 AI Validation Summary
        if: always()
        run: |
          echo "## 🤖 Rapport Validation IA" >> $GITHUB_STEP_SUMMARY
          echo "- Mode: ${{ github.event.inputs.test_mode || 'quick' }}" >> $GITHUB_STEP_SUMMARY
          echo "- Timestamp: $(date)" >> $GITHUB_STEP_SUMMARY
          
          # Extraction des scores si rapports disponibles
          if [ -f "tests/reports/systematic-test-report-*.json" ]; then
            echo "- Rapports générés: ✅" >> $GITHUB_STEP_SUMMARY
          else
            echo "- Rapports générés: ❌" >> $GITHUB_STEP_SUMMARY
          fi

  # ========================================
  # JOB 4: RAPPORT CONSOLIDÉ
  # ========================================
  consolidated-report:
    name: 📊 Rapport Consolidé
    runs-on: ubuntu-latest
    needs: [generate-tests, run-systematic-tests, ai-content-validation]
    if: always()
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        
      - name: 📤 Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts/
          
      - name: 📊 Generate consolidated report
        run: |
          echo "# 🧪 Rapport Tests Systématiques Consolidé" > report.md
          echo "" >> report.md
          echo "**Exécution:** $(date)" >> report.md
          echo "**Workflow:** ${{ github.workflow }}" >> report.md
          echo "**Commit:** ${{ github.sha }}" >> report.md
          echo "" >> report.md
          
          echo "## 📝 Génération Tests" >> report.md
          echo "- Status: ${{ needs.generate-tests.result }}" >> report.md
          
          echo "## 🧪 Tests Systématiques" >> report.md
          echo "- Status: ${{ needs.run-systematic-tests.result }}" >> report.md
          
          echo "## 🤖 Validation IA" >> report.md
          echo "- Status: ${{ needs.ai-content-validation.result }}" >> report.md
          
          # Ajout au summary GitHub
          cat report.md >> $GITHUB_STEP_SUMMARY
          
      - name: 📤 Upload consolidated report
        uses: actions/upload-artifact@v4
        with:
          name: consolidated-report
          path: report.md

  # ========================================
  # JOB 5: NETTOYAGE ET NOTIFICATION
  # ========================================
  cleanup-and-notify:
    name: 🧹 Nettoyage
    runs-on: ubuntu-latest
    needs: [consolidated-report]
    if: always()
    
    steps:
      - name: 🧹 Cleanup old artifacts
        uses: actions/github-script@v7
        with:
          script: |
            const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: context.runId,
            });
            
            console.log(`Trouvé ${artifacts.data.artifacts.length} artifacts`);
            
      - name: ✅ Workflow completed
        run: |
          echo "## ✅ Workflow Terminé" >> $GITHUB_STEP_SUMMARY
          echo "- Durée totale: ${{ github.event.created_at }}" >> $GITHUB_STEP_SUMMARY
          echo "- Status global: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY

# ========================================
# CONFIGURATION SPÉCIFIQUE
# ========================================
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read
  actions: read
  checks: write