name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Nim
        uses: jiro4989/setup-nim-action@v1
        with:
          nim-version: '2.2.10'

      - name: Install system dependencies
        run: sudo apt-get update -qq && sudo apt-get install -y -qq libssl-dev libpcre3-dev openssl ca-certificates

      - name: Install Nim dependencies
        run: nimble install --depsOnly -y

      - name: Debug environment
        run: |
          nim --version
          nimble list -i
          uname -a
          free -h

      - name: Run tests
        run: |
          nim c -d:ssl --threads:on --path:src -r tests/test_all.nim > test_output.log 2>&1
          EXIT=$?
          tail -n 200 test_output.log
          exit $EXIT

      - name: Post test log as commit comment
        if: failure()
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          BODY=$(cat test_output.log | sed 's/"/\\"/g' | head -c 60000)
          curl -s -X POST \
            -H "Authorization: token $GITHUB_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"body\":\"Test failure log:\\n\\n\\`\\`\\`\\n$BODY\\n\\`\\`\\`\"}" \
            https://api.github.com/repos/${{ github.repository }}/commits/${{ github.sha }}/comments

      - name: Compile benchmarks
        run: nim c -d:release --threads:on benchmarks/bench_all.nim

      - name: Compile stress test
        run: nim c -d:ssl --threads:on --path:src tests/stress_test.nim

      - name: Run stress test
        run: ./tests/stress_test

      - name: Check for unused declarations and imports
        run: |
          nim c -d:ssl --threads:on --path:src tests/test_all.nim 2>&1 | tee build.log || true
          echo "--- Checking for XDeclaredButNotUsed hints ---"
          grep -E "XDeclaredButNotUsed|UnusedImport" build.log | while read -r line; do
            echo "::warning::$line"
          done
          echo "--- Done ---"

  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '21'

      - name: Cache tla2tools.jar
        uses: actions/cache@v4
        with:
          path: formal-verification/tla2tools.jar
          key: tla2tools-${{ hashFiles('formal-verification/tla2tools.jar') }}
          restore-keys: |
            tla2tools-

      - name: Run TLA+ model checker on all specs
        working-directory: formal-verification
        continue-on-error: true
        run: |
          for spec in raft twopc mvcc replication gossip deadlock sharding; do
            echo "=== Verifying ${spec}.tla ==="
            java -cp tla2tools.jar tlc2.TLC -config models/${spec}.cfg ${spec}.tla
          done
