name: Aider Code Review

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
  workflow_dispatch:
    inputs:
      review_type:
        description: 'Type of code review'
        required: true
        default: 'basic'
        type: choice
        options:
        - basic
        - security
        - performance
      target_files:
        description: 'Specific files to review (optional, comma-separated)'
        required: false
        type: string

jobs:
  code-review:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      with:
        fetch-depth: 0  # 獲取完整的Git歷史
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.11'
    
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install aider-chat
        # 如果有requirements.txt，也安裝專案依賴
        if [ -f requirements.txt ]; then
          pip install -r requirements.txt
        fi
    
    - name: Configure Git
      run: |
        git config --global user.name "GitHub Actions"
        git config --global user.email "actions@github.com"
    
    - name: Run Code Review
      run: |
        # 創建logs目錄
        mkdir -p logs
        
        # 確定要review的檔案
        if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.target_files }}" ]; then
          # 手動觸發，指定檔案
          IFS=',' read -ra FILES <<< "${{ github.event.inputs.target_files }}"
          python scripts/code_review.py --files "${FILES[@]}" --type "${{ github.event.inputs.review_type }}"
        elif [ "${{ github.event_name }}" = "pull_request" ]; then
          # PR，review變更的檔案
          git diff origin/${{ github.base_ref }}...HEAD --name-only --diff-filter=ACM | grep -E '\.(py|js|ts|jsx|tsx|html|css)$' > /tmp/changed_files.txt
          if [ -s /tmp/changed_files.txt ]; then
            python scripts/code_review.py --files $(cat /tmp/changed_files.txt | tr '\n' ' ') --type basic
          else
            echo "No files to review"
          fi
        else
          # Push，review暫存的檔案
          python scripts/code_review.py --auto --type basic
        fi
    
    - name: Upload review reports
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: code-review-reports
        path: logs/review_*.md
        retention-days: 30
    
    - name: Comment PR with review results
      if: github.event_name == 'pull_request'
      uses: actions/github-script@v6
      with:
        script: |
          const fs = require('fs');
          const path = './logs';
          
          try {
            const files = fs.readdirSync(path);
            const reviewFiles = files.filter(f => f.startsWith('review_') && f.endsWith('.md'));
            
            if (reviewFiles.length > 0) {
              let comment = '## 🔍 Aider Code Review 報告\n\n';
              
              reviewFiles.forEach(file => {
                const content = fs.readFileSync(`${path}/${file}`, 'utf8');
                comment += `### ${file}\n\n`;
                comment += '```\n' + content + '\n```\n\n';
              });
              
              github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body: comment
              });
            }
          } catch (error) {
            console.log('No review reports found or error reading reports:', error.message);
          }
