name: Publish Twister Test Results

on:
  workflow_run:
    workflows: ["Run tests with twister"]
    branches:
      - main
    types:
      - completed

jobs:
  upload-to-elasticsearch:
    if: |
      github.repository == 'zephyrproject-rtos/zephyr' &&
      github.event.workflow_run.event != 'pull_request_target'
    env:
      ELASTICSEARCH_KEY: ${{ secrets.ELASTICSEARCH_KEY }}
      ELASTICSEARCH_SERVER: "https://elasticsearch.zephyrproject.io:443"
    runs-on: ubuntu-22.04
    steps:
      # Needed for elasticearch and upload script
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Download Artifacts
        id: download-artifacts
        uses: dawidd6/action-download-artifact@v6
        with:
          path: artifacts
          workflow: twister.yml
          run_id: ${{ github.event.workflow_run.id }}
          if_no_artifact_found: ignore

      - name: Upload to elasticsearch
        if: steps.download-artifacts.outputs.found_artifact == 'true'
        run: |
          pip install elasticsearch
          # set run date on upload to get consistent and unified data across the matrix.
          run_date=`date --iso-8601=minutes`
          if [ "${{github.event.workflow_run.event}}" = "push" ]; then
            python3 ./scripts/ci/upload_test_results_es.py -r ${run_date} \
            --run-attempt ${{github.run_attempt}} \
            --run-branch ${{github.ref_name}} \
            --index zephyr-main-ci-push-1 artifacts/*/*/twister.json
          elif [ "${{github.event.workflow_run.event}}" = "schedule" ]; then
            python3 ./scripts/ci/upload_test_results_es.py -r ${run_date} \
            --run-attempt ${{github.run_attempt}} \
            --run-branch ${{github.ref_name}} \
            --index zephyr-main-ci-weekly-1 artifacts/*/*/twister.json
          fi
