name: Ultra-Deploy Performance Tests

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]
  schedule:
    # Run nightly at 2 AM UTC
    - cron: "0 2 * * *"

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  ultra-deploy-tests:
    name: Ultra-Deploy Tests - ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest]
        rust: [stable, nightly]
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: macos-latest
            target: x86_64-apple-darwin

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

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: ${{ matrix.rust }}
          components: rustfmt, clippy

      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: ~/.cargo/registry
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}

      - name: Cache cargo index
        uses: actions/cache@v4
        with:
          path: ~/.cargo/git
          key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}

      - name: Cache cargo build
        uses: actions/cache@v4
        with:
          path: target
          key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}

      - name: Install Docker (Ubuntu)
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y docker.io
          sudo systemctl start docker
          sudo usermod -aG docker $USER

      - name: Install Docker (macOS)
        if: matrix.os == 'macos-latest'
        run: |
          # Docker installation on macOS runners is unreliable in CI
          # Skip Docker on macOS; tests will use mocks instead
          echo "⚠️ Skipping Docker on macOS (CI limitation)"
          echo "Tests will use mock implementations for Docker services"
          true

      - name: Build ggen (release mode)
        run: |
          cargo build --release
          echo "Built binary: $(ls -lh target/release/ggen)"

      - name: Run ultra-deploy tests
        run: |
          cargo test --test ultra_deploy_test -- --nocapture --test-threads=1
        timeout-minutes: 15

      - name: Run performance benchmarks
        run: |
          cargo test --test ultra_deploy_test test_performance_benchmark -- --nocapture
        timeout-minutes: 10

      - name: Generate test report
        if: always()
        run: |
          echo "## Ultra-Deploy Test Results" > test-report.md
          echo "" >> test-report.md
          echo "- OS: ${{ matrix.os }}" >> test-report.md
          echo "- Rust: ${{ matrix.rust }}" >> test-report.md
          echo "- Target: ${{ matrix.target }}" >> test-report.md
          echo "" >> test-report.md
          cargo test --test ultra_deploy_test -- --nocapture 2>&1 | tee -a test-report.md

      - name: Upload test report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: test-report-${{ matrix.os }}-${{ matrix.rust }}
          path: test-report.md

  performance-comparison:
    name: Performance Comparison
    runs-on: ubuntu-latest
    needs: ultra-deploy-tests

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

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Download test reports
        uses: actions/download-artifact@v4
        with:
          path: test-reports/

      - name: Compare performance
        run: |
          echo "## Performance Comparison" > comparison.md
          echo "" >> comparison.md
          echo "Comparing performance across platforms..." >> comparison.md
          find test-reports/ -name "test-report-*.md" -exec cat {} \; >> comparison.md

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

  integration-matrix:
    name: Integration Matrix
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        template: [rust-cli-minimal, rust-lib-minimal]
        scenario: [sequential, concurrent]

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

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Build ggen
        run: cargo build --release

      - name: Run matrix tests
        run: |
          echo "Testing template: ${{ matrix.template }}"
          echo "Scenario: ${{ matrix.scenario }}"
          cargo test --test ultra_deploy_test -- --nocapture
        timeout-minutes: 10

  performance-regression:
    name: Performance Regression Check
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'

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

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Build and test PR
        run: |
          cargo build --release
          cargo test --test ultra_deploy_test test_performance_benchmark -- --nocapture > pr-results.txt

      - name: Checkout base branch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.base_ref }}

      - name: Build and test base
        run: |
          cargo build --release
          cargo test --test ultra_deploy_test test_performance_benchmark -- --nocapture > base-results.txt

      - name: Compare results
        run: |
          set -euo pipefail
          echo "## Performance Regression Analysis" > regression-report.md
          echo "" >> regression-report.md
          echo "### Base Branch Results" >> regression-report.md
          cat base-results.txt >> regression-report.md
          echo "" >> regression-report.md
          echo "### PR Results" >> regression-report.md
          cat pr-results.txt >> regression-report.md
          echo "" >> regression-report.md
          echo "### Regression Analysis" >> regression-report.md

          # Extract test execution times and compare
          if [ -f base-results.txt ] && [ -f pr-results.txt ]; then
            BASE_TESTS=$(grep -c "test result:" base-results.txt || echo "0")
            PR_TESTS=$(grep -c "test result:" pr-results.txt || echo "0")

            echo "**Base branch tests completed**: $BASE_TESTS" >> regression-report.md
            echo "**PR branch tests completed**: $PR_TESTS" >> regression-report.md

            # Check for test failures
            if grep -q "test result: FAILED" pr-results.txt; then
              echo "" >> regression-report.md
              echo "❌ **REGRESSION DETECTED**: Tests are failing in PR" >> regression-report.md
              echo "Please review the PR changes for performance regressions." >> regression-report.md
            elif grep -q "PASSED\|ok" pr-results.txt && [ "$PR_TESTS" -gt 0 ]; then
              echo "" >> regression-report.md
              echo "✅ **PASSED**: All performance tests passed" >> regression-report.md
            else
              echo "" >> regression-report.md
              echo "⚠️ **WARNING**: Could not determine test status. Review logs." >> regression-report.md
            fi
          else
            echo "❌ Results files missing" >> regression-report.md
            exit 1
          fi

      - name: Upload regression report
        uses: actions/upload-artifact@v4
        with:
          name: regression-report
          path: regression-report.md

      - name: Comment on PR
        if: always()
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const report = fs.readFileSync('regression-report.md', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: report
            });
