name: Memory & Performance Tests
on:
  push:
    branches: [ main ]
  workflow_dispatch:
    inputs:
      test_type:
        description: 'Type of test to run'
        required: false
        default: 'all'
        type: choice
        options:
          - all
          - memory-leak
          - performance

jobs:
  memory-leak-test:
    name: Memory Leak Tests
    runs-on: ubuntu-latest
    timeout-minutes: 30

    services:
      firebase-emulator:
        image: ghcr.io/firebase/firebase-tools:latest
        ports:
          - 9099:9099
          - 5001:5001
          - 8080:8080
          - 9000:9000
          - 9199:9199
        env:
          FIREBASE_PROJECT: roadtripper-test
        options: >-
          --health-cmd "firebase emulators:exec --project=roadtripper-test --only=firestore 'echo ready'"
          --health-interval 10s
          --health-timeout 60s
          --health-retries 10

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          run_install: false
          package_json_path: package.json

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build frontend bundle
        run: pnpm --filter=@my-roadtrip/web build

      - name: Run focused E2E sweep
        run: pnpm test:e2e --project=chromium --workers=1 --reporter=line
        env:
          NODE_ENV: test
          PLAYWRIGHT_HTML_REPORT: playwright-memory-report

      - name: Run memory audit
        run: pnpm audit:memory -- --output memory-audit.json

      - name: Upload memory audit results
        uses: actions/upload-artifact@v4
        with:
          name: memory-audit-results
          path: memory-audit.json

  performance-test:
    name: Performance Tests
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          run_install: false
          package_json_path: package.json

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run performance benchmarks
        run: |
          # Create basic performance benchmarks
          echo "Running performance benchmarks..."

          # Build performance test
          start_time=$(date +%s.%3N)
          pnpm build
          end_time=$(date +%s.%3N)
          build_time=$(echo "$end_time - $start_time" | bc)

          echo "Build time: ${build_time}s"

          # Test execution performance
          start_time=$(date +%s.%3N)
          pnpm test:unit
          end_time=$(date +%s.%3N)
          test_time=$(echo "$end_time - $start_time" | bc)

          echo "Test execution time: ${test_time}s"

          # Create performance report
          cat > performance-report.json << EOF
          {
            "timestamp": "$(date -Iseconds)",
            "build_time_seconds": ${build_time},
            "test_time_seconds": ${test_time},
            "thresholds": {
              "max_build_time": 30,
              "max_test_time": 60
            }
          }
          EOF

          # Check thresholds
          if (( $(echo "$build_time > 30" | bc -l) )); then
            echo "❌ Build time exceeded threshold: ${build_time}s > 30s"
            exit 1
          fi

          if (( $(echo "$test_time > 60" | bc -l) )); then
            echo "❌ Test time exceeded threshold: ${test_time}s > 60s"
            exit 1
          fi

          echo "✅ All performance thresholds met"

      - name: Upload performance report
        uses: actions/upload-artifact@v4
        with:
          name: performance-report
          path: performance-report.json

  quality-gate:
    name: Memory & Performance Quality Gate
    runs-on: ubuntu-latest
    needs: [memory-leak-test, performance-test]
    if: always()

    steps:
      - name: Download memory audit
        uses: actions/download-artifact@v4
        with:
          name: memory-audit-results

      - name: Download performance report
        uses: actions/download-artifact@v4
        with:
          name: performance-report

      - name: Quality gate check
        run: |
          echo "🔍 Checking memory audit results..."
          if [ -f memory-audit.json ]; then
            critical_issues=$(jq '.summary.riskAssessment.critical // 0' memory-audit.json)
            if [ "$critical_issues" -gt 0 ]; then
              echo "❌ Critical memory issues found: $critical_issues"
              exit 1
            fi
            echo "✅ No critical memory issues"
          else
            echo "⚠️ Memory audit results not found"
          fi

          echo "🔍 Checking performance results..."
          if [ -f performance-report.json ]; then
            echo "✅ Performance report found"
            cat performance-report.json
          else
            echo "⚠️ Performance report not found"
          fi

          echo "🎯 Quality gate passed!"

      - name: Create summary comment
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');

            let summary = '## 🔍 Memory & Performance Test Results\n\n';

            // Memory audit results
            if (fs.existsSync('memory-audit.json')) {
              const memoryData = JSON.parse(fs.readFileSync('memory-audit.json', 'utf8'));
              summary += '### Memory Audit\n';
              summary += `✅ Stores analyzed: ${memoryData.summary.found}/${memoryData.summary.totalStores}\n`;
              summary += `🚨 Critical issues: ${memoryData.summary.riskAssessment.critical}\n`;
              summary += `💡 Recommendations: ${memoryData.summary.totalRecommendations}\n\n`;
            }

            // Performance results
            if (fs.existsSync('performance-report.json')) {
              const perfData = JSON.parse(fs.readFileSync('performance-report.json', 'utf8'));
              summary += '### Performance\n';
              summary += `⚡ Build time: ${perfData.build_time_seconds.toFixed(2)}s\n`;
              summary += `🧪 Test time: ${perfData.test_time_seconds.toFixed(2)}s\n\n`;
            }

            summary += '**Status:** ✅ All checks passed\n';

            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: summary
            });
