name: Stratified Testing

on:
  workflow_dispatch: # TEMPORARILY manual only for faster CI
  # push:
  #   branches: [master, main]
  # pull_request:
  #   branches: [master, main]

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1
  RUSTFLAGS: "-D warnings"
  RUST_MIN_STACK: 8388608

jobs:
  unit-tests:
    name: Unit Tests (<10s)
    runs-on: ubuntu-latest
    timeout-minutes: 2
    steps:
      - uses: actions/checkout@v4
      
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: llvm-tools-preview
      
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: server -> target
          key: unit-tests
      
      - name: Run unit tests
        run: |
          cargo test --package pmat --test unit_core -- --test-threads=$(nproc)
      
      - name: Upload unit test results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: unit-test-results
          path: target/test-results/

  service-integration:
    name: Service Integration (<30s)
    runs-on: ubuntu-latest
    needs: unit-tests
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4
      
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: llvm-tools-preview
      
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: server -> target
          key: service-tests
      
      - name: Install cargo-llvm-cov
        run: cargo install cargo-llvm-cov --locked
      
      - name: Run service integration tests with coverage
        run: |
          cargo llvm-cov test --package pmat --test services_integration \
            --features integration-tests \
            --json --output-path coverage-service.json \
            -- --test-threads=4
      
      - name: Upload coverage
        uses: codecov/codecov-action@v5
        with:
          files: coverage-service.json
          flags: services
          name: service-coverage

  protocol-validation:
    name: Protocol Validation (<45s)
    runs-on: ubuntu-latest
    needs: service-integration
    timeout-minutes: 8
    steps:
      - uses: actions/checkout@v4
      
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: llvm-tools-preview
      
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: server -> target
          key: protocol-tests
      
      - name: Run protocol adapter tests
        run: |
          cargo test --package pmat --test protocol_adapters \
            --features integration-tests \
            -- --test-threads=2
      
      - name: Validate protocol equivalence
        run: |
          # Run a quick protocol equivalence check
          cargo run --package pmat --release -- analyze complexity . --json > /tmp/cli.json
          echo '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"analyze_complexity","arguments":{"path":"."}},"id":1}' | \
            cargo run --package pmat --release -- --protocol mcp | \
            jq -r '.result.content[0].text' > /tmp/mcp.json
          # Basic validation that outputs exist
          test -s /tmp/cli.json && test -s /tmp/mcp.json

  e2e-validation:
    name: E2E System Tests (<120s)
    runs-on: ubuntu-latest
    needs: [unit-tests, service-integration, protocol-validation]
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      
      - uses: dtolnay/rust-toolchain@stable
      
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: server -> target
          key: e2e-tests
      
      - name: Build release binary
        run: |
          cargo build --package pmat --release
      
      - name: Run E2E system tests
        run: |
          cargo test --package pmat --test e2e_system \
            --features e2e-tests \
            -- --test-threads=1
      
      - name: Test binary installation
        run: |
          ./scripts/install.sh
          pmat --version
          pmat analyze complexity . --top-files 5

  performance-regression:
    name: Performance Regression
    runs-on: ubuntu-latest
    needs: [unit-tests, service-integration]
    if: github.event_name == 'pull_request'
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - uses: dtolnay/rust-toolchain@stable
      
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: server -> target
          key: perf-tests
      
      - name: Checkout base branch
        run: |
          git checkout ${{ github.base_ref }}
          cargo build --package pmat --release
          mv target/release/pmat /tmp/pmat-base
      
      - name: Checkout PR branch
        run: |
          git checkout ${{ github.head_ref }}
          cargo build --package pmat --release
      
      - name: Run performance comparison
        run: |
          # Run performance tests
          cargo test --package pmat --test performance_regression \
            --features perf-tests \
            -- --test-threads=1
          
          # Compare binary sizes
          BASE_SIZE=$(stat -c%s /tmp/pmat-base)
          PR_SIZE=$(stat -c%s target/release/pmat)
          SIZE_DIFF=$((PR_SIZE - BASE_SIZE))
          
          echo "Binary size change: $SIZE_DIFF bytes"
          if [ $SIZE_DIFF -gt 1048576 ]; then
            echo "⚠️ Binary size increased by more than 1MB"
            exit 1
          fi
      
      - name: Upload performance results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: performance-results
          path: |
            target/criterion/
            target/performance/

  coverage-summary:
    name: Coverage Summary
    runs-on: ubuntu-latest
    needs: [unit-tests, service-integration, protocol-validation]
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4
      
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: llvm-tools-preview
      
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: server -> target
          key: coverage
      
      - name: Install cargo-llvm-cov
        run: cargo install cargo-llvm-cov --locked
      
      - name: Generate coverage summary
        run: |
          ./scripts/test-coverage.sh
      
      - name: Upload coverage report
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: target/coverage/
      
      - name: Comment PR with coverage
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const coverage = JSON.parse(fs.readFileSync('target/coverage/summary.json', 'utf8'));
            const pct = coverage.data[0].totals.lines.percent;
            
            const comment = `## Coverage Report 📊
            
            **Overall Coverage:** ${pct.toFixed(2)}%
            
            | Test Suite | Status | Time |
            |------------|--------|------|
            | Unit Tests | ✅ | <10s |
            | Service Integration | ✅ | <30s |
            | Protocol Validation | ✅ | <45s |
            | E2E Tests | ✅ | <120s |
            
            [View detailed coverage report](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})`;
            
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });

  test-matrix-summary:
    name: Test Matrix Summary
    runs-on: ubuntu-latest
    needs: [unit-tests, service-integration, protocol-validation, e2e-validation]
    if: always()
    steps:
      - name: Check test results
        run: |
          if [ "${{ needs.unit-tests.result }}" != "success" ] || \
             [ "${{ needs.service-integration.result }}" != "success" ] || \
             [ "${{ needs.protocol-validation.result }}" != "success" ] || \
             [ "${{ needs.e2e-validation.result }}" != "success" ]; then
            echo "❌ One or more test suites failed"
            exit 1
          fi
          echo "✅ All test suites passed!"