name: PR Checks

on:
  pull_request:
    types: [opened, synchronize, reopened]

permissions:
  contents: read
  pull-requests: write
  issues: write

jobs:
  # Check PR title follows conventional commits
  pr-title:
    name: Validate PR Title
    runs-on: ubuntu-latest
    
    steps:
      - name: 📝 Check PR title
        uses: amannn/action-semantic-pull-request@v5
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          types: |
            feat
            fix
            docs
            style
            refactor
            test
            chore
            perf
            ci
            build
            revert

  # Check file sizes
  file-size:
    name: Check File Sizes
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: 📏 Check for large files
        run: |
          # Find files larger than 1MB
          large_files=$(find . -type f -size +1M | grep -v -E '(node_modules|\.git|\.next|dist|build)' || true)
          
          if [ ! -z "$large_files" ]; then
            echo "⚠️ Warning: Large files detected (>1MB):"
            echo "$large_files"
            echo "Consider using Git LFS for large files."
          fi

  # Check for secrets
  secret-scan:
    name: Scan for Secrets
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: 🔍 TruffleHog scan
        uses: trufflesecurity/trufflehog@main
        with:
          path: ./
          base: ${{ github.event.pull_request.base.sha }}
          head: ${{ github.event.pull_request.head.sha }}
          extra_args: --only-verified

  # Lighthouse CI (for web apps)
  lighthouse:
    name: Lighthouse CI
    runs-on: ubuntu-latest
    if: false # Enable for web apps
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          cache: 'npm'

      - name: 📦 Install dependencies
        run: npm ci

      - name: 🏗️ Build application
        run: npm run build

      - name: 🔦 Run Lighthouse CI
        uses: treosh/lighthouse-ci-action@v10
        with:
          urls: |
            http://localhost:3000
            http://localhost:3000/about
          uploadArtifacts: true
          temporaryPublicStorage: true

  # Bundle size check
  bundle-size:
    name: Bundle Size Check
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout PR
        uses: actions/checkout@v4

      - name: 📥 Checkout base
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.base.sha }}
          path: base

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          cache: 'npm'

      - name: 📦 Install dependencies (PR)
        run: npm ci

      - name: 📦 Install dependencies (base)
        working-directory: base
        run: npm ci

      - name: 🏗️ Build PR
        run: npm run build

      - name: 🏗️ Build base
        working-directory: base
        run: npm run build

      - name: 📊 Compare bundle sizes
        run: |
          echo "Bundle size comparison:"
          echo "Base branch:"
          du -sh base/.next 2>/dev/null || du -sh base/dist 2>/dev/null || echo "No build output"
          echo "PR branch:"
          du -sh .next 2>/dev/null || du -sh dist 2>/dev/null || echo "No build output"

  # Dependencies check
  dependency-review:
    name: Dependency Review
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔍 Dependency Review
        uses: actions/dependency-review-action@v3
        with:
          fail-on-severity: moderate

  # AI Code Review (using Claude/GPT)
  ai-review:
    name: AI Code Review
    runs-on: ubuntu-latest
    if: false # Enable if you want AI reviews
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: 🤖 Get changed files
        id: changed-files
        run: |
          echo "files=$(git diff --name-only ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} | grep -E '\.(js|jsx|ts|tsx|py|go)$' | head -10 | tr '\n' ' ')" >> $GITHUB_OUTPUT

      - name: 💬 Comment AI review request
        if: steps.changed-files.outputs.files != ''
        uses: actions/github-script@v6
        with:
          script: |
            const files = '${{ steps.changed-files.outputs.files }}'.trim().split(' ');
            const comment = `🤖 **AI Review Checklist**
            
            Please review the following files for:
            - [ ] Code quality and best practices
            - [ ] Potential bugs or issues
            - [ ] Security concerns
            - [ ] Performance implications
            - [ ] Test coverage
            
            Files to review: ${files.join(', ')}`;
            
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });

  # Label PR based on changes
  label-pr:
    name: Auto Label PR
    runs-on: ubuntu-latest
    
    steps:
      - name: 🏷️ Label PR
        uses: actions/labeler@v4
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          configuration-path: .github/labeler.yml

  # Summary comment
  pr-summary:
    name: PR Summary
    runs-on: ubuntu-latest
    needs: [pr-title, file-size, secret-scan, dependency-review]
    if: always()
    
    steps:
      - name: 💬 Comment PR summary
        uses: actions/github-script@v6
        with:
          script: |
            const checks = {
              'PR Title': '${{ needs.pr-title.result }}',
              'File Size': '${{ needs.file-size.result }}',
              'Secret Scan': '${{ needs.secret-scan.result }}',
              'Dependencies': '${{ needs.dependency-review.result }}'
            };
            
            let comment = '## 📋 PR Check Summary\n\n';
            
            for (const [check, status] of Object.entries(checks)) {
              const emoji = status === 'success' ? '✅' : status === 'failure' ? '❌' : '⏭️';
              comment += `${emoji} **${check}**: ${status}\n`;
            }
            
            comment += '\n---\n';
            comment += '💡 All checks must pass before merging.';
            
            // Find and update existing comment or create new one
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });
            
            const botComment = comments.find(comment => 
              comment.user.type === 'Bot' && comment.body.includes('PR Check Summary')
            );
            
            if (botComment) {
              github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: comment
              });
            } else {
              github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body: comment
              });
            }