name: Build and test

on:
  pull_request:

concurrency:
  group: ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
  contents: read

jobs:
  changes:
    runs-on: ubuntu-24.04
    outputs:
      mode: ${{ steps.select.outputs.mode }}
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
          persist-credentials: false
      - name: Test check selection and result gate
        run: python3 -m unittest discover -s tools/ci -p test_checks.py -v
      - name: Select checks from the complete PR diff
        id: select
        env:
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
          HEAD_SHA: ${{ github.event.pull_request.head.sha }}
        run: python3 tools/ci/checks.py select --base "$BASE_SHA" --head "$HEAD_SHA"

  naming:
    needs: changes
    if: needs.changes.outputs.mode == 'full'
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
          persist-credentials: false
      - name: Test APT cache validation
        run: python3 -m unittest discover -s tools/ci -p test_apt_cache.py -v
      - uses: ./.github/actions/naming-toolchain
      - name: Test naming runner and dependency selection
        run: python3 -m unittest tools.test_check_naming tools.ci.test_naming_selection -v
      - name: Configure compilation database
        run: >-
          cmake -S . -B build/naming -G Ninja
          -DCMAKE_BUILD_TYPE=Debug
          -DCMAKE_C_COMPILER=clang-20
          -DCMAKE_CXX_COMPILER=clang++-20
          -DCMAKE_CXX_FLAGS=--gcc-install-dir=/usr/lib/gcc/x86_64-linux-gnu/14
          -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
          -DPORTALS_BUILD_TESTS=ON
          -DPORTALS_BUILD_EXAMPLES=ON
          -DPORTALS_ENABLE_GZIP=ON
      - name: Check project names
        env:
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
          HEAD_SHA: ${{ github.sha }}
        # Analyze the checked-out merge candidate, including the entire PR.
        run: >-
          python3 tools/check_naming.py build/naming --clang-tidy clang-tidy-20
          --jobs 2 --base "$BASE_SHA" --head "$HEAD_SHA"
          --timings build/naming/timings.json
      - name: Save naming timings
        if: ${{ always() && hashFiles('build/naming/timings.json') != '' }}
        continue-on-error: true
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: naming-timings
          path: build/naming/timings.json
          if-no-files-found: error
          retention-days: 14

  smoke:
    needs: changes
    if: needs.changes.outputs.mode == 'full'
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: windows-2022
            preset: windows-msvc-debug
            minimal_consumer_debug_info: 'OFF'
            embedded_consumer_debug_info: 'ON'
          - os: ubuntu-24.04
            preset: linux-gcc-debug
            minimal_consumer_debug_info: 'ON'
            embedded_consumer_debug_info: 'OFF'
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v7
      - name: Configure MSVC environment
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          $vswhere = "${env:ProgramFiles(x86)}/Microsoft Visual Studio/Installer/vswhere.exe"
          $vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
          if (-not $vs) { throw 'MSVC installation not found' }
          Import-Module "$vs/Common7/Tools/Microsoft.VisualStudio.DevShell.dll"
          Enter-VsDevShell -VsInstallPath $vs -SkipAutomaticLocation -DevCmdArguments '-arch=x64 -host_arch=x64'
          foreach ($name in @('PATH', 'INCLUDE', 'LIB', 'LIBPATH')) {
            "$name=$([Environment]::GetEnvironmentVariable($name))" >> $env:GITHUB_ENV
          }
      - name: Configure
        # Package setup and runtime verification use separate fixture phases; per-consumer limits remain.
        run: cmake --preset ${{ matrix.preset }} -DPORTALS_ENABLE_GZIP=ON -DPORTALS_PACKAGE_TEST_TIMEOUT=1200 -DPORTALS_PACKAGE_CONSUMER_MINIMAL_DEBUG_INFO=${{ matrix.minimal_consumer_debug_info }} -DPORTALS_PACKAGE_CONSUMER_EMBEDDED_DEBUG_INFO=${{ matrix.embedded_consumer_debug_info }}
      - name: Build
        run: cmake --build --preset ${{ matrix.preset }}
      - name: Test
        run: ctest --preset ${{ matrix.preset }}
      - name: Configure standalone consumer
        run: cmake -S examples/consumer -B build/consumer -G Ninja -DCMAKE_BUILD_TYPE=Debug
      - name: Build standalone consumer
        run: cmake --build build/consumer
      - name: Run standalone consumer
        run: ./build/consumer/portals_consumer
      - name: Save native failure evidence
        if: failure()
        continue-on-error: true
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: native-failure-${{ matrix.preset }}
          path: |
            build/**/Testing/Temporary/LastTest.log
            build/**/Testing/Temporary/LastTestsFailed.log
            build/**/compile_commands.json
            build/**/.ninja_log
          include-hidden-files: true
          if-no-files-found: warn
          retention-days: 14

  docs:
    needs: changes
    runs-on: ubuntu-24.04
    env:
      DOXYGEN_VERSION: '1.18.0'
      DOXYGEN_SHA256: 14fa81bdc34171edb5f1f02b1d60e74802f0439b77fa44e592565d517d72df90
    steps:
      - uses: actions/checkout@v7
      - name: Test documentation HTML processing
        run: python3 -m unittest discover -s tools/docs -p 'test_*.py' -v
      - uses: actions/setup-node@v7
        with:
          node-version: '24'
      - name: Install documentation toolchain
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-14 g++-14 ninja-build
          archive="doxygen-$DOXYGEN_VERSION.linux.bin.tar.gz"
          release="Release_${DOXYGEN_VERSION//./_}"
          mkdir -p "$RUNNER_TEMP/doxygen"
          curl --fail --location --retry 3 "https://github.com/doxygen/doxygen/releases/download/$release/$archive" -o "$RUNNER_TEMP/$archive"
          echo "$DOXYGEN_SHA256  $RUNNER_TEMP/$archive" | sha256sum --check
          tar -xf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP/doxygen"
          binary=$(find "$RUNNER_TEMP/doxygen" -type f -name doxygen)
          test -n "$binary"
          version=$("$binary" --version)
          test "${version%% *}" = "$DOXYGEN_VERSION"
          dirname "$binary" >> "$GITHUB_PATH"
          npm install --global @mermaid-js/mermaid-cli@12.0.0
      - name: Configure Mermaid renderer
        run: |
          mkdir -p "$RUNNER_TEMP/mermaid-renderer"
          echo '{"args":["--no-sandbox"]}' > "$RUNNER_TEMP/mermaid-renderer/puppeteer.json"
          mmdc_path=$(command -v mmdc)
          printf '#!/bin/sh\nexec "%s" --puppeteerConfigFile "%s" "$@"\n' "$mmdc_path" "$RUNNER_TEMP/mermaid-renderer/puppeteer.json" > "$RUNNER_TEMP/mermaid-renderer/mmdc"
          chmod +x "$RUNNER_TEMP/mermaid-renderer/mmdc"
          echo "$RUNNER_TEMP/mermaid-renderer" >> "$GITHUB_PATH"
      - name: Configure documentation
        run: >-
          cmake -S . -B build/documentation -G Ninja
          -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc-14 -DCMAKE_CXX_COMPILER=g++-14
          -DDOXYGEN_PROJECT_NUMBER="PR ${{ github.event.pull_request.number }} preview"
          -DPORTALS_BUILD_DOCS=ON -DPORTALS_BUILD_TESTS=OFF
          -DPORTALS_BUILD_EXAMPLES=OFF -DPORTALS_BUILD_TOOLS=OFF -DPORTALS_BUILD_FUZZERS=OFF
      - name: Build strict documentation
        run: cmake --build build/documentation --target portals_docs --parallel 2
      - name: Check generated HTML links and anchors
        run: python3 tools/docs/check_links.py build/documentation/docs/html
      - name: Save the documentation preview
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: documentation-preview
          path: build/documentation/docs/html
          include-hidden-files: true
          if-no-files-found: error
          retention-days: 14

  result:
    name: CI result
    if: always()
    needs: [changes, docs, naming, smoke]
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v7
      - name: Require success from every selected check
        env:
          CI_NEEDS: ${{ toJSON(needs) }}
        run: python3 tools/ci/checks.py gate
