name: 📊 Manual Security & Quality Audit
# StackWorkflow v2.2 - Auditoria Manual com Tendências

on:
  workflow_dispatch:
    inputs:
      audit_type:
        description: 'Tipo de auditoria agendada'
        required: true
        default: 'manual'
        type: choice
        options:
        - manual
        - comprehensive
        - trend_analysis

env:
  REPORTS_DIR: reports/manual

jobs:
  manual-audit:
    name: 📊 Comprehensive Manual Audit
    runs-on: ubuntu-latest

    steps:
    - name: 📥 Checkout Code
      uses: actions/checkout@v4
      with:
        fetch-depth: 0  # História completa para análise de tendências

    - name: 📊 Setup Reports Directory
      run: |
        mkdir -p ${{ env.REPORTS_DIR }}
        echo "📁 Diretório de relatórios criado: ${{ env.REPORTS_DIR }}"

    - name: 🔍 Comprehensive Project Analysis
      run: |
        echo "📊 Executando análise abrangente do projeto..."

        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        AUDIT_TYPE="${{ github.event.inputs.audit_type || 'manual' }}"
        REPORT_FILE="${{ env.REPORTS_DIR }}/manual-audit-$TIMESTAMP.md"

        # ========== MÉTRICAS BÁSICAS ==========
        echo "📋 Coletando métricas básicas..."

        TOTAL_FILES=$(find . -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" ! -path "./reports/*" | 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)
        CSS_FILES=$(find . -name "*.css" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)
        PYTHON_FILES=$(find . -name "*.py" -type f ! -path "./.venv/*" ! -path "./venv/*" ! -path "./.git/*" | wc -l)

        # Lines of Code
        TOTAL_LOC=$(find . \( -name "*.php" -o -name "*.js" -o -name "*.py" -o -name "*.css" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" ! -path "./.venv/*" ! -path "./venv/*" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")

        # ========== ANÁLISE DE SEGURANÇA ==========
        echo "🛡️ Análise de segurança..."

        # 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)
        SQL_DETAILS=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -Hn '\$wpdb->get_var.*{' {} \; 2>/dev/null | head -5)

        # XSS vulnerabilities
        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)
        XSS_DETAILS=$(find . \( -name "*.php" -o -name "*.js" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -Hn 'echo.*\$' {} \; 2>/dev/null | head -5)

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

        # Insecure configurations
        PUBLIC_ENDPOINTS=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l '__return_true' {} \; 2>/dev/null | wc -l)

        # ========== ANÁLISE DE QUALIDADE ==========
        echo "🏗️ Análise de qualidade..."

        # Funções complexas
        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)

        # Code duplication (simplified)
        DUPLICATE_LINES=$(find . \( -name "*.php" -o -name "*.js" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec wc -l {} + 2>/dev/null | awk '{sum+=$1} END{print sum*0.03}' | cut -d. -f1 || echo "0")

        # TODO/FIXME comments
        TODO_ITEMS=$(find . \( -name "*.php" -o -name "*.js" -o -name "*.py" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" ! -path "./.venv/*" -exec grep -c "TODO\|FIXME\|HACK" {} + 2>/dev/null | awk '{sum+=$1} END{print sum+0}')

        # ========== ANÁLISE DE TENDÊNCIAS ==========
        echo "📈 Análise de tendências..."

        # Commits recentes (últimos 30 dias)
        RECENT_COMMITS=$(git log --since="30 days ago" --oneline | wc -l)

        # Contributors ativos
        ACTIVE_CONTRIBUTORS=$(git log --since="30 days ago" --format="%an" | sort | uniq | wc -l)

        # Arquivos modificados recentemente
        RECENT_CHANGES=$(git log --since="7 days ago" --name-only --pretty=format: | sort | uniq | grep -v "^$" | wc -l)

        # ========== CÁLCULO DE SCORES ==========
        echo "📊 Calculando scores..."

        # Security Score (0-100)
        SECURITY_PENALTY=$(( (SQL_ISSUES * 20) + (XSS_ISSUES * 15) + (SECRETS_ISSUES * 25) + (PUBLIC_ENDPOINTS * 10) ))
        SECURITY_SCORE=$(( 100 - SECURITY_PENALTY ))
        if [ $SECURITY_SCORE -lt 0 ]; then SECURITY_SCORE=0; fi

        # Quality Score (0-100)
        QUALITY_PENALTY=$(( (LONG_FUNCTIONS * 5) + (TODO_ITEMS * 2) ))
        QUALITY_SCORE=$(( 100 - QUALITY_PENALTY ))
        if [ $QUALITY_SCORE -lt 0 ]; then QUALITY_SCORE=0; fi

        # Overall Score
        OVERALL_SCORE=$(( (SECURITY_SCORE + QUALITY_SCORE) / 2 ))

        # ========== GERAÇÃO DO RELATÓRIO ==========
        echo "📝 Gerando relatório..."

        cat > "$REPORT_FILE" << EOF
        # 📊 Manual Audit Report - StackWorkflow v2.2

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

        ## 📊 Scores Finais

        | Métrica | Score | Status |
        |---------|-------|--------|
        | 🛡️ **Segurança** | **$SECURITY_SCORE/100** | $([ $SECURITY_SCORE -ge 80 ] && echo "🟢 Excelente" || [ $SECURITY_SCORE -ge 60 ] && echo "🟡 Bom" || echo "🔴 Crítico") |
        | 🏗️ **Qualidade** | **$QUALITY_SCORE/100** | $([ $QUALITY_SCORE -ge 80 ] && echo "🟢 Excelente" || [ $QUALITY_SCORE -ge 60 ] && echo "🟡 Bom" || echo "🔴 Crítico") |
        | 🎯 **Geral** | **$OVERALL_SCORE/100** | $([ $OVERALL_SCORE -ge 80 ] && echo "🟢 Excelente" || [ $OVERALL_SCORE -ge 60 ] && echo "🟡 Bom" || echo "🔴 Crítico") |

        ## 📋 Resumo do Projeto

        ### 📁 Estrutura
        - **Total de ficheiros**: $TOTAL_FILES
        - **Linhas de código**: $TOTAL_LOC
        - **Ficheiros PHP**: $PHP_FILES
        - **Ficheiros JavaScript**: $JS_FILES
        - **Ficheiros CSS**: $CSS_FILES
        - **Ficheiros Python**: $PYTHON_FILES

        ### 📈 Atividade (últimos 30 dias)
        - **Commits**: $RECENT_COMMITS
        - **Contributors ativos**: $ACTIVE_CONTRIBUTORS
        - **Ficheiros alterados (7 dias)**: $RECENT_CHANGES

        ## 🛡️ Análise de Segurança

        ### 🚨 Vulnerabilidades Detectadas
        - **SQL Injection**: $SQL_ISSUES issues
        - **XSS**: $XSS_ISSUES issues
        - **Secrets hardcoded**: $SECRETS_ISSUES issues
        - **Endpoints públicos**: $PUBLIC_ENDPOINTS issues

        EOF

        # Adicionar detalhes de vulnerabilidades se existirem
        if [ $SQL_ISSUES -gt 0 ]; then
          echo "### 🔴 SQL Injection Details" >> "$REPORT_FILE"
          echo "\`\`\`" >> "$REPORT_FILE"
          echo "$SQL_DETAILS" >> "$REPORT_FILE"
          echo "\`\`\`" >> "$REPORT_FILE"
          echo "" >> "$REPORT_FILE"
        fi

        if [ $XSS_ISSUES -gt 0 ]; then
          echo "### 🔴 XSS Vulnerabilities Details" >> "$REPORT_FILE"
          echo "\`\`\`" >> "$REPORT_FILE"
          echo "$XSS_DETAILS" >> "$REPORT_FILE"
          echo "\`\`\`" >> "$REPORT_FILE"
          echo "" >> "$REPORT_FILE"
        fi

        cat >> "$REPORT_FILE" << EOF

        ## 🏗️ Análise de Qualidade

        ### 📏 Métricas de Código
        - **Funções complexas (>50 linhas)**: $LONG_FUNCTIONS
        - **Duplicação estimada**: $DUPLICATE_LINES linhas (~3%)
        - **TODOs/FIXMEs**: $TODO_ITEMS itens

        ## 🎯 Recomendações Prioritárias

        EOF

        # Gerar recomendações baseadas nos scores
        if [ $SECURITY_SCORE -lt 70 ]; then
          echo "### 🔴 Segurança (Crítico)" >> "$REPORT_FILE"
          echo "1. **Corrigir SQL Injection**: Usar prepared statements" >> "$REPORT_FILE"
          echo "2. **Eliminar XSS**: Sanitizar outputs com esc_html()" >> "$REPORT_FILE"
          echo "3. **Remover secrets**: Migrar para variáveis de ambiente" >> "$REPORT_FILE"
          echo "" >> "$REPORT_FILE"
        fi

        if [ $QUALITY_SCORE -lt 70 ]; then
          echo "### 🟡 Qualidade (Melhorar)" >> "$REPORT_FILE"
          echo "1. **Refatorar funções grandes**: Quebrar em funções menores" >> "$REPORT_FILE"
          echo "2. **Eliminar duplicação**: Aplicar DRY principle" >> "$REPORT_FILE"
          echo "3. **Resolver TODOs**: Implementar ou documentar" >> "$REPORT_FILE"
          echo "" >> "$REPORT_FILE"
        fi

        cat >> "$REPORT_FILE" << EOF
        ## 🔄 Próximas Ações

        1. **Imediato**: Corrigir issues críticos de segurança
        2. **Curto prazo**: Refatorar código com alta complexidade
        3. **Médio prazo**: Implementar testes automatizados
        4. **Automação**: Executar \`/avaliar\` para correções automáticas

        ---
        **Powered by**: StackWorkflow v2.2 Manual Audit System
        **Execução**: Manual via `/avaliar` ou workflow_dispatch
        EOF

        echo "SECURITY_SCORE=$SECURITY_SCORE" >> $GITHUB_ENV
        echo "QUALITY_SCORE=$QUALITY_SCORE" >> $GITHUB_ENV
        echo "OVERALL_SCORE=$OVERALL_SCORE" >> $GITHUB_ENV

        echo "✅ Relatório manual gerado: $REPORT_FILE"

    - name: 📤 Upload Manual Report
      uses: actions/upload-artifact@v4
      with:
        name: manual-audit-report-${{ github.run_number }}
        path: ${{ env.REPORTS_DIR }}/*.md
        retention-days: 90

    - name: 📊 Create Issue for Critical Findings
      if: env.OVERALL_SCORE < 50
      uses: actions/github-script@v7
      with:
        script: |
          const title = `🔴 Critical Issues Found - Manual Audit ${new Date().toISOString().split('T')[0]}`;
          const body = `# 🚨 Critical Security & Quality Issues Detected

          **Overall Score**: ${process.env.OVERALL_SCORE}/100 🔴
          **Security Score**: ${process.env.SECURITY_SCORE}/100
          **Quality Score**: ${process.env.QUALITY_SCORE}/100

          ## 🎯 Immediate Action Required

          This automated manual audit has detected critical issues that require immediate attention.

          ### 📋 Next Steps
          1. 🔍 **Review** the detailed audit report in the artifacts
          2. 🔧 **Fix** critical security vulnerabilities first
          3. 🏗️ **Refactor** code quality issues
          4. ⚡ **Run** \`/avaliar\` in StackWorkflow for automated fixes

          ### 📁 Reports
          - Check the "manual-audit-report-${{ github.run_number }}" artifact for detailed findings
          - Review file:line references for specific issues

          ---
          **Auto-generated by**: StackWorkflow v2.2 Manual Audit
          **Report ID**: ${{ github.run_number }}
          `;

          await github.rest.issues.create({
            owner: context.repo.owner,
            repo: context.repo.repo,
            title: title,
            body: body,
            labels: ['security', 'quality', 'critical', 'automated-audit']
          });

    - name: 🏆 Success Summary
      if: env.OVERALL_SCORE >= 80
      run: |
        echo "🎉 PARABÉNS! Projeto com qualidade excelente!"
        echo "📊 Score geral: $OVERALL_SCORE/100"
        echo "🛡️ Segurança: $SECURITY_SCORE/100"
        echo "🏗️ Qualidade: $QUALITY_SCORE/100"