name: 🛡️ Automated Security & Quality Audit
# StackWorkflow v2.2 - Sistema Adversarial Automatizado

on:
  push:
    branches: [ main, master, develop ]
  pull_request:
    branches: [ main, master, develop ]
  schedule:
    # Auditoria diária às 02:00 UTC
    - cron: '0 2 * * *'
  workflow_dispatch:
    inputs:
      audit_level:
        description: 'Nível de auditoria'
        required: true
        default: 'full'
        type: choice
        options:
        - quick
        - full
        - security-only
        - quality-only

env:
  MIN_SECURITY_SCORE: 70
  MIN_QUALITY_SCORE: 60
  REPORTS_DIR: reports

jobs:
  # ==========================================
  # PRE-SCAN: Detecção Rápida de Vulnerabilidades
  # ==========================================
  pre-scan:
    name: 🚨 Pre-Scan Vulnerabilities
    runs-on: ubuntu-latest
    outputs:
      sql_issues: ${{ steps.scan.outputs.sql_issues }}
      xss_issues: ${{ steps.scan.outputs.xss_issues }}
      secrets_issues: ${{ steps.scan.outputs.secrets_issues }}
      should_continue: ${{ steps.gate.outputs.should_continue }}

    steps:
    - name: 📥 Checkout Code
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: 🔍 Quick Vulnerability Scan
      id: scan
      run: |
        echo "🚨 Executando pre-scan de vulnerabilidades..."

        # SQL Injection patterns
        SQL_ISSUES=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l '\$wpdb->get_var.*{' {} \; 2>/dev/null | wc -l)

        # XSS patterns
        XSS_ISSUES=$(find . \( -name "*.php" -o -name "*.js" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l 'echo.*\$' {} \; 2>/dev/null | wc -l)

        # Hardcoded secrets
        SECRETS_ISSUES=$(find . -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" ! -name "*.log" -exec grep -l "password\|secret\|key\|token" {} \; 2>/dev/null | grep -v ".env.example" | wc -l)

        echo "sql_issues=$SQL_ISSUES" >> $GITHUB_OUTPUT
        echo "xss_issues=$XSS_ISSUES" >> $GITHUB_OUTPUT
        echo "secrets_issues=$SECRETS_ISSUES" >> $GITHUB_OUTPUT

        echo "📊 RESULTADOS PRE-SCAN:"
        echo "- SQL Issues: $SQL_ISSUES"
        echo "- XSS Issues: $XSS_ISSUES"
        echo "- Secrets: $SECRETS_ISSUES"

    - name: 🚦 Quality Gate
      id: gate
      run: |
        TOTAL_CRITICAL=$((${{ steps.scan.outputs.sql_issues }} + ${{ steps.scan.outputs.xss_issues }}))

        if [ $TOTAL_CRITICAL -gt 10 ]; then
          echo "🔴 CRÍTICO: $TOTAL_CRITICAL vulnerabilidades críticas detectadas!"
          echo "should_continue=false" >> $GITHUB_OUTPUT
          exit 1
        else
          echo "🟡 Prosseguindo com auditoria completa..."
          echo "should_continue=true" >> $GITHUB_OUTPUT
        fi

  # ==========================================
  # AUDITORIA DE SEGURANÇA (Gemini-style)
  # ==========================================
  security-audit:
    name: 🛡️ Security Audit
    runs-on: ubuntu-latest
    needs: pre-scan
    if: needs.pre-scan.outputs.should_continue == 'true'

    steps:
    - name: 📥 Checkout Code
      uses: actions/checkout@v4

    - name: 📊 Create Reports Directory
      run: mkdir -p ${{ env.REPORTS_DIR }}

    - name: 🔍 Comprehensive Security Analysis
      run: |
        echo "🛡️ Executando análise de segurança completa..."

        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        REPORT_FILE="${{ env.REPORTS_DIR }}/github-security-audit-$TIMESTAMP.md"

        # Coletar métricas detalhadas
        TOTAL_FILES=$(find . -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)
        PHP_FILES=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)
        JS_FILES=$(find . -name "*.js" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)

        # Recoletar issues do pre-scan
        SQL_ISSUES=${{ needs.pre-scan.outputs.sql_issues }}
        XSS_ISSUES=${{ needs.pre-scan.outputs.xss_issues }}
        SECRETS_ISSUES=${{ needs.pre-scan.outputs.secrets_issues }}

        # Calcular score
        SCORE=$((100 - (SQL_ISSUES * 20) - (XSS_ISSUES * 15) - (SECRETS_ISSUES * 25)))
        if [ $SCORE -lt 0 ]; then SCORE=0; fi

        # Gerar relatório
        cat > "$REPORT_FILE" << EOF
        # 🛡️ GitHub Actions Security Audit Report

        **Data**: $(date '+%Y-%m-%d %H:%M:%S')
        **Commit**: ${{ github.sha }}
        **Branch**: ${{ github.ref_name }}
        **Score**: $SCORE/100

        ## 📊 Resumo Executivo
        - **Total de ficheiros**: $TOTAL_FILES
        - **Ficheiros PHP**: $PHP_FILES
        - **Ficheiros JavaScript**: $JS_FILES
        - **SQL Injection Issues**: $SQL_ISSUES
        - **XSS Issues**: $XSS_ISSUES
        - **Hardcoded Secrets**: $SECRETS_ISSUES

        ## 🚨 Vulnerabilidades Críticas
        EOF

        # Adicionar detalhes de SQL Injection
        if [ $SQL_ISSUES -gt 0 ]; then
          echo "### SQL Injection" >> "$REPORT_FILE"
          find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -Hn '\$wpdb->get_var.*{' {} \; 2>/dev/null | head -5 >> "$REPORT_FILE"
        fi

        # Adicionar detalhes de XSS
        if [ $XSS_ISSUES -gt 0 ]; then
          echo "### Cross-Site Scripting (XSS)" >> "$REPORT_FILE"
          find . \( -name "*.php" -o -name "*.js" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -Hn 'echo.*\$' {} \; 2>/dev/null | head -5 >> "$REPORT_FILE"
        fi

        # Classificação final
        cat >> "$REPORT_FILE" << EOF

        ## 📊 Classificação Final
        EOF

        if [ $SCORE -ge 90 ]; then
          echo "**🟢 EXCELENTE** - Segurança robusta" >> "$REPORT_FILE"
        elif [ $SCORE -ge 70 ]; then
          echo "**🟡 BOM** - Algumas melhorias necessárias" >> "$REPORT_FILE"
        elif [ $SCORE -ge 50 ]; then
          echo "**🟠 MÉDIO** - Vulnerabilidades significativas" >> "$REPORT_FILE"
        else
          echo "**🔴 CRÍTICO** - Correção imediata necessária" >> "$REPORT_FILE"
        fi

        echo "SECURITY_SCORE=$SCORE" >> $GITHUB_ENV
        echo "📊 Score de segurança: $SCORE/100"

    - name: 🚦 Security Quality Gate
      run: |
        if [ $SECURITY_SCORE -lt ${{ env.MIN_SECURITY_SCORE }} ]; then
          echo "🔴 FALHA: Score de segurança ($SECURITY_SCORE) abaixo do mínimo (${{ env.MIN_SECURITY_SCORE }})"
          exit 1
        else
          echo "✅ Score de segurança aprovado: $SECURITY_SCORE/${{ env.MIN_SECURITY_SCORE }}"
        fi

    - name: 📤 Upload Security Report
      uses: actions/upload-artifact@v4
      with:
        name: security-audit-report
        path: ${{ env.REPORTS_DIR }}/*.md
        retention-days: 30

  # ==========================================
  # AUDITORIA DE QUALIDADE (Cursor-style)
  # ==========================================
  quality-audit:
    name: 🏗️ Code Quality Audit
    runs-on: ubuntu-latest
    needs: pre-scan
    if: needs.pre-scan.outputs.should_continue == 'true'

    steps:
    - name: 📥 Checkout Code
      uses: actions/checkout@v4

    - name: 📊 Create Reports Directory
      run: mkdir -p ${{ env.REPORTS_DIR }}

    - name: 🔍 Code Quality Analysis
      run: |
        echo "🏗️ Executando análise de qualidade de código..."

        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        REPORT_FILE="${{ env.REPORTS_DIR }}/github-quality-audit-$TIMESTAMP.md"

        # Métricas de qualidade
        TOTAL_FILES=$(find . -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)
        PHP_FILES=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)
        JS_FILES=$(find . -name "*.js" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)

        # Funções longas (>50 linhas)
        LONG_FUNCTIONS=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec awk '/function.*{/{start=NR} /^}$/{if(NR-start>50) print FILENAME":"start":"NR-start" lines"}' {} \; 2>/dev/null | wc -l)

        # Linhas muito longas (>120 chars)
        LONG_LINES=$(find . \( -name "*.php" -o -name "*.js" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec awk 'length>120{count++} END{print count+0}' {} \; 2>/dev/null | awk '{sum+=$1} END{print sum+0}')

        # Loops aninhados
        NESTED_LOOPS=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l 'foreach.*foreach\|for.*for' {} \; 2>/dev/null | wc -l)

        # Calcular score de qualidade
        COMPLEXITY_PENALTY=$((LONG_FUNCTIONS * 5 + NESTED_LOOPS * 10))
        QUALITY_SCORE=$((100 - COMPLEXITY_PENALTY))
        if [ $QUALITY_SCORE -lt 0 ]; then QUALITY_SCORE=0; fi

        # Gerar relatório
        cat > "$REPORT_FILE" << EOF
        # 🏗️ GitHub Actions Quality Audit Report

        **Data**: $(date '+%Y-%m-%d %H:%M:%S')
        **Commit**: ${{ github.sha }}
        **Branch**: ${{ github.ref_name }}
        **Score**: $QUALITY_SCORE/100

        ## 📊 Métricas de Qualidade
        - **Total de ficheiros**: $TOTAL_FILES
        - **Ficheiros PHP**: $PHP_FILES
        - **Ficheiros JavaScript**: $JS_FILES
        - **Funções longas (>50 linhas)**: $LONG_FUNCTIONS
        - **Linhas longas (>120 chars)**: $LONG_LINES
        - **Loops aninhados**: $NESTED_LOOPS

        ## 🔧 Análise de Complexidade
        EOF

        if [ $LONG_FUNCTIONS -gt 0 ]; then
          echo "### ⚠️ Funções Complexas Detectadas" >> "$REPORT_FILE"
          find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec awk '/function.*{/{start=NR} /^}$/{if(NR-start>50) print FILENAME":"start":"NR-start" lines"}' {} \; 2>/dev/null | head -3 >> "$REPORT_FILE"
        fi

        # Classificação final
        cat >> "$REPORT_FILE" << EOF

        ## 📊 Classificação Final
        EOF

        if [ $QUALITY_SCORE -ge 90 ]; then
          echo "**🟢 EXCELENTE** - Código bem estruturado" >> "$REPORT_FILE"
        elif [ $QUALITY_SCORE -ge 70 ]; then
          echo "**🟡 BOM** - Qualidade adequada" >> "$REPORT_FILE"
        elif [ $QUALITY_SCORE -ge 50 ]; then
          echo "**🟠 MÉDIO** - Refactoring recomendado" >> "$REPORT_FILE"
        else
          echo "**🔴 CRÍTICO** - Refactoring urgente" >> "$REPORT_FILE"
        fi

        echo "QUALITY_SCORE=$QUALITY_SCORE" >> $GITHUB_ENV
        echo "📊 Score de qualidade: $QUALITY_SCORE/100"

    - name: 🚦 Quality Gate
      run: |
        if [ $QUALITY_SCORE -lt ${{ env.MIN_QUALITY_SCORE }} ]; then
          echo "🔴 FALHA: Score de qualidade ($QUALITY_SCORE) abaixo do mínimo (${{ env.MIN_QUALITY_SCORE }})"
          exit 1
        else
          echo "✅ Score de qualidade aprovado: $QUALITY_SCORE/${{ env.MIN_QUALITY_SCORE }}"
        fi

    - name: 📤 Upload Quality Report
      uses: actions/upload-artifact@v4
      with:
        name: quality-audit-report
        path: ${{ env.REPORTS_DIR }}/*.md
        retention-days: 30

  # ==========================================
  # CONSOLIDAÇÃO E NOTIFICAÇÃO
  # ==========================================
  consolidate-results:
    name: 📋 Consolidate Results
    runs-on: ubuntu-latest
    needs: [security-audit, quality-audit]
    if: always()

    steps:
    - name: 📥 Download All Reports
      uses: actions/download-artifact@v4
      with:
        path: all-reports

    - name: 📊 Generate Consolidated Report
      run: |
        echo "📋 Consolidando resultados..."

        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        CONSOLIDATED_REPORT="consolidated-audit-$TIMESTAMP.md"

        cat > "$CONSOLIDATED_REPORT" << EOF
        # 🎯 Consolidated Audit Report - StackWorkflow v2.2

        **Data**: $(date '+%Y-%m-%d %H:%M:%S')
        **Commit**: ${{ github.sha }}
        **Branch**: ${{ github.ref_name }}
        **Workflow**: ${{ github.workflow }}

        ## 📊 Resumo Geral

        | Componente | Status | Score | Threshold |
        |------------|--------|-------|-----------|
        | 🛡️ Segurança | ${{ needs.security-audit.result }} | - | ${{ env.MIN_SECURITY_SCORE }} |
        | 🏗️ Qualidade | ${{ needs.quality-audit.result }} | - | ${{ env.MIN_QUALITY_SCORE }} |

        ## 📁 Relatórios Detalhados

        Consulte os artifacts desta execução para relatórios completos:
        - \`security-audit-report\`: Análise de vulnerabilidades
        - \`quality-audit-report\`: Análise de qualidade de código

        ## 🎯 Próximos Passos

        1. **Se falhou**: Corrigir issues críticos identificados
        2. **Se passou**: Considerar implementar melhorias sugeridas
        3. **Integração**: Executar \`/avaliar\` no StackWorkflow para correções automáticas

        ---
        **Powered by**: StackWorkflow v2.2 Adversarial System
        **CI/CD**: GitHub Actions Automated Audit
        EOF

        echo "✅ Relatório consolidado gerado"

    - name: 📤 Upload Consolidated Report
      uses: actions/upload-artifact@v4
      with:
        name: consolidated-audit-report
        path: consolidated-audit-*.md
        retention-days: 90

    - name: 💬 Comment on PR
      if: github.event_name == 'pull_request'
      uses: actions/github-script@v7
      with:
        script: |
          const securityStatus = '${{ needs.security-audit.result }}';
          const qualityStatus = '${{ needs.quality-audit.result }}';

          let emoji = '✅';
          let title = 'Auditoria Passou';

          if (securityStatus === 'failure' || qualityStatus === 'failure') {
            emoji = '🔴';
            title = 'Auditoria Falhou';
          } else if (securityStatus === 'skipped' || qualityStatus === 'skipped') {
            emoji = '⚠️';
            title = 'Auditoria Parcial';
          }

          const body = `${emoji} **${title}**

          | Componente | Status |
          |------------|--------|
          | 🛡️ Segurança | ${securityStatus} |
          | 🏗️ Qualidade | ${qualityStatus} |

          📁 **Relatórios**: Consulte os artifacts desta execução para detalhes completos.

          🔧 **Correções**: Execute \`/avaliar\` no StackWorkflow para implementar correções automáticas.
          `;

          github.rest.issues.createComment({
            issue_number: context.issue.number,
            owner: context.repo.owner,
            repo: context.repo.repo,
            body: body
          });