name: Build binaries, docs and publish to dev folder
on:
  workflow_dispatch:
  schedule:
    - cron: '0 0 * * *'
jobs:
  build-upload:
    runs-on: ubuntu-latest
    if: github.repository_owner == '1technophile'
    name: Build and upload Assets to Release
    steps:
      - uses: actions/checkout@v4
      - uses: benjlevesque/short-sha@v2.1
        id: short-sha
        with:
          length: 6
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.13"
      - name: Install uv
        uses: astral-sh/setup-uv@v6
        with:
          version: "latest"
          enable-cache: false
      - name: Install dependencies
        run: |
          uv pip install --system -U https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.18.zip
      - name: Set sha tag
        run: |
          sed -i "s/version_tag/${{ steps.short-sha.outputs.sha }}/g" main/User_config.h scripts/latest_version_dev.json
          sed -i "s/version_tag/DEVELOPMENT SHA:${{ steps.short-sha.outputs.sha }} TEST ONLY/g" docs/.vuepress/config.js
          sed -i "s|base: '/'|base: '/dev/'|g" docs/.vuepress/config.js
      - name: Extract ESP32 platform version from platformio.ini
        run: |
          ESP32_VERSION=$(grep 'esp32_platform\s*=' platformio.ini | cut -d'@' -f2 | tr -d '[:space:]')
          echo "ESP32_PLATFORM_VERSION=${ESP32_VERSION}" >> $GITHUB_ENV
      - name: Run PlatformIO
        env:
          PYTHONIOENCODING: utf-8
          PYTHONUTF8: '1'
        run: |
          export PLATFORMIO_BUILD_FLAGS="'-DDEVELOPMENTOTA=true'"
          platformio run
      - name: Prepare Release Assets
        run: |
          sudo apt install rename
          ./scripts/prepare_deploy.sh
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "16.x"
      - name: Download Common Config
        run: |
          curl -o docs/.vuepress/public/commonConfig.js https://www.theengs.io/commonConfig.js
      - name: Build documentation
        run: |
          python ./scripts/gen_wu.py --dev
          npm run docs:build
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs/.vuepress/dist
          destination_dir: dev
          cname: docs.openmqttgateway.com
      - name: Running Page Speed Insights
        uses: jakepartusch/psi-action@v1.3
        id: psi
        with:
          url: "https://docs.openmqttgateway.com/dev/"
          threshold: 60
          key: ${{ secrets.APIKEY }}
