name: Dependency Management

on:
  # schedule:
  #   - cron: '0 3 * * 1'  # Weekly on Monday at 3 AM
  workflow_dispatch:  # Manual only to avoid automated PRs
    inputs:
      update_type:
        description: 'Update type'
        required: true
        default: 'conservative'
        type: choice
        options:
          - conservative
          - aggressive
          - security-only

env:
  RUST_BACKTRACE: 1
  CARGO_TERM_COLOR: always
  RUST_MIN_STACK: 8388608

jobs:
  analyze-dependencies:
    runs-on: ubuntu-22.04
    outputs:
      has_updates: ${{ steps.check.outputs.has_updates }}
      update_summary: ${{ steps.check.outputs.summary }}
    steps:
      - uses: actions/checkout@v4
      
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        
      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            target/
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          
      - name: Install cargo-outdated and cargo-edit
        run: |
          make install-dev-tools
          
      - name: Check for updates
        id: check
        run: |
          # Save outdated deps to a file
          make server-outdated > outdated.json
          
          OUTDATED_COUNT=$(cat outdated.json | jq '.dependencies | length')
          
          if [ "$OUTDATED_COUNT" -gt 0 ]; then
            echo "has_updates=true" >> $GITHUB_OUTPUT
            
            # Generate summary
            SUMMARY=$(cat outdated.json | jq -r '
              .dependencies[] | 
              "\(.name): \(.project) → \(.latest)"
            ' | head -10)
            
            # Escape for GitHub Actions
            SUMMARY="${SUMMARY//$'\n'/%0A}"
            echo "summary=$SUMMARY" >> $GITHUB_OUTPUT
          else
            echo "has_updates=false" >> $GITHUB_OUTPUT
          fi

  update-dependencies:
    needs: analyze-dependencies
    if: needs.analyze-dependencies.outputs.has_updates == 'true'
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        
      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            target/
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          
      - name: Update dependencies
        run: |
          UPDATE_TYPE="${{ github.event.inputs.update_type || 'conservative' }}"
          
          case $UPDATE_TYPE in
            aggressive)
              make update-deps-aggressive
              ;;
            security-only)
              make update-deps-security
              ;;
            *)
              make update-deps
              ;;
          esac
          
      - name: Run tests
        run: |
          make server-test-all
          make server-lint
          
      - name: Check binary size impact
        run: |
          # Build before and after to compare
          git stash
          make server-build-release
          BEFORE_SIZE=$(stat -f%z target/release/paiml-mcp-agent-toolkit 2>/dev/null || stat -c%s target/release/paiml-mcp-agent-toolkit)
          
          git stash pop
          make server-build-release
          AFTER_SIZE=$(stat -f%z target/release/paiml-mcp-agent-toolkit 2>/dev/null || stat -c%s target/release/paiml-mcp-agent-toolkit)
          
          SIZE_DIFF=$((AFTER_SIZE - BEFORE_SIZE))
          echo "Binary size impact: $SIZE_DIFF bytes"
          
          # Fail if binary grows more than 5%
          if [ $SIZE_DIFF -gt $((BEFORE_SIZE / 20)) ]; then
            echo "::error::Binary size increased by more than 5%"
            exit 1
          fi
          
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v5
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: "deps: automated dependency updates"
          title: "Automated Dependency Updates"
          body: |
            ## 🤖 Automated Dependency Updates
            
            **Update Summary:**
            ```
            ${{ needs.analyze-dependencies.outputs.update_summary }}
            ```
            
            **Checks performed:**
            - ✅ All tests passing
            - ✅ No clippy warnings
            - ✅ Binary size impact checked
            - ✅ Security audit passed
            
            Please review the changes and merge if everything looks good.
          branch: deps/automated-update-${{ github.run_number }}
          labels: dependencies,automated

  security-audit:
    name: Security Audit
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v4
      
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      
      - name: Install cargo-audit
        run: make install-dev-tools
      
      - name: Run security audit
        run: |
          make server-audit
      
      - name: Create issue if vulnerabilities found
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            const title = 'Security vulnerabilities found in dependencies';
            const body = `Security audit has found vulnerabilities in the project dependencies.
            
            Please check the [workflow run](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}) for details.
            
            Run \`cargo audit\` locally to see the full report.`;
            
            github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: title,
              body: body,
              labels: ['security', 'dependencies']
            });