name: Deploy to GitHub Pages

on:
  push:
    branches:
      - main

permissions:
  contents: write
  id-token: write
  pages: write

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npm ci

      - name: Install sharp
        run: npm install sharp

      - name: Build project
        run: npm run build

      - name: Generate logos.json
        run: node scripts/update-data.js

      - name: Generate SVG variants
        run: node scripts/generate-svg-variants.js

      - name: Generate PWA cache list
        run: node scripts/generate-pwa-cache-list.js

      - name: Prepare Pages artifact
        run: |
          mkdir -p ./gh-pages-artifact/build
          cp public/build/* ./gh-pages-artifact/build/
          cp public/index.html ./gh-pages-artifact/
          cp public/global.css ./gh-pages-artifact/
          cp public/favicon.svg ./gh-pages-artifact/
          cp public/favicon.png ./gh-pages-artifact/
          cp public/favicon.ico ./gh-pages-artifact/
          cp public/apple-touch-icon.png ./gh-pages-artifact/
          cp public/icon-192.png ./gh-pages-artifact/
          cp public/icon-512.png ./gh-pages-artifact/
          cp public/manifest.json ./gh-pages-artifact/
          cp public/sw.js ./gh-pages-artifact/
          cp -r public/data ./gh-pages-artifact/
          cp -r public/images ./gh-pages-artifact/
          cp public/pwa-files-to-cache.json ./gh-pages-artifact/
          if [ -f public/CNAME ]; then
            cp public/CNAME ./gh-pages-artifact/CNAME
          fi

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
            path: ./gh-pages-artifact

  deploy:
    needs: build-and-deploy
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
