name: Circuits CI
on:
  pull_request:
    branches:
      - dev
      - staging
      - main
jobs:
  check_changes:
    runs-on: ubuntu-slim
    outputs:
      should_run: ${{ steps.filter.outputs.should_run }}
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Check if should run
        id: filter
        run: |
          set -e
          if [[ "${{ github.base_ref }}" == "main" ]] || [[ "${{ github.base_ref }}" == "staging" ]]; then
            echo "should_run=true" >> $GITHUB_OUTPUT
            echo "Running for ${{ github.base_ref }} - no path filter"
          else
            # For dev branch, check if circuits files changed
            CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD) || {
              echo "Error: Failed to diff against base branch"
              exit 1
            }
            if echo "$CHANGED_FILES" | grep -qE "^circuits/"; then
              echo "should_run=true" >> $GITHUB_OUTPUT
              echo "Running for dev - circuits files changed"
            else
              echo "should_run=false" >> $GITHUB_OUTPUT
              echo "Skipping for dev - no circuits files changed"
            fi
          fi

  run_circuit_tests:
    needs: check_changes
    if: github.event.pull_request.draft == false && needs.check_changes.outputs.should_run == 'true'
    runs-on:
      - "self-hosted"
      - "selfxyz-org"
      - "ubuntu-24-04"
    environment: development
    permissions:
      contents: read
    env:
      CIRCOM_VERSION: "2.1.9"
      CIRCOM_SHA256: "e5575829252d763b7818049df9de2ef9304df834697de77fa63ce7babc23c967"
    steps:
      - uses: actions/checkout@v6

      # Circom installation from https://github.com/erhant/circomkit/blob/main/.github/workflows/tests.yml
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install --yes \
            build-essential \
            libgmp-dev \
            libsodium-dev \
            nasm \
            nlohmann-json3-dev

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

      - name: Restore Circom binary
        id: circom-cache
        uses: actions/cache/restore@v4
        with:
          path: ~/.cache/circom
          key: circom-v2.1.9

      - name: Download Circom Binary v2.1.9
        if: steps.circom-cache.outputs.cache-hit != 'true'
        run: |
          mkdir -p ~/.cache/circom

          # Download with curl (more reliable than wget in CI environments)
          # Use exponential backoff retry logic
          for attempt in 1 2 3; do
            echo "Download attempt $attempt/3..."

            if curl -L --connect-timeout 30 --max-time 300 \
                --retry 3 --retry-delay 2 --retry-max-time 600 \
                -o ~/.cache/circom/circom \
                "https://github.com/iden3/circom/releases/download/v${{ env.CIRCOM_VERSION }}/circom-linux-amd64"; then
              echo "✅ Download successful!"
              break
            else
              echo "❌ Download failed on attempt $attempt"
              if [ $attempt -eq 3 ]; then
                echo "💥 All download attempts failed"
                exit 1
              fi
              # Exponential backoff: 5s, 10s, 20s
              sleep_time=$((5 * attempt))
              echo "⏳ Waiting ${sleep_time}s before retry..."
              sleep $sleep_time
            fi
          done

          # Verify file exists and has content
          if [ ! -f ~/.cache/circom/circom ]; then
            echo "💥 Error: circom binary file is missing"
            exit 1
          fi

          if [ ! -s ~/.cache/circom/circom ]; then
            echo "💥 Error: circom binary file is empty"
            exit 1
          fi

          echo "📁 File size: $(ls -lh ~/.cache/circom/circom | awk '{print $5}')"
          chmod +x ~/.cache/circom/circom

          # Verify checksum
          echo "🔍 Verifying checksum..."
          echo "${{ env.CIRCOM_SHA256 }}  $HOME/.cache/circom/circom" | sha256sum -c -

      - name: Save Circom cache
        if: steps.circom-cache.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          path: ~/.cache/circom
          key: circom-v2.1.9

      - name: Verify Circom checksum (cache hit)
        if: steps.circom-cache.outputs.cache-hit == 'true'
        run: |
          echo "${{ env.CIRCOM_SHA256 }}  $HOME/.cache/circom/circom" | sha256sum -c -

      - name: Add Circom to PATH
        run: echo "$HOME/.cache/circom" >> "$GITHUB_PATH"

      - name: Print Circom version
        run: circom --version

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version-file: .nvmrc

      - name: Enable Corepack
        run: corepack enable

      - name: Cache Yarn dependencies
        uses: ./.github/actions/cache-yarn
        with:
          path: |
            .yarn/cache
            node_modules
            circuits/node_modules
          cache-version: v1

      - name: Install Yarn dependencies
        uses: ./.github/actions/yarn-install
        with:
          working_directory: circuits

      - name: Run lint
        run: yarn workspace @selfxyz/circuits lint
      - name: Run Tests (Circuits)
        env:
          FULL_TEST_SUITE: false
        run: yarn workspace @selfxyz/circuits test
