name: "Release Bundle Analysis"
on:
  push:
    tags:
      - v*
  workflow_dispatch:

env:
  NODE_DEFAULT_VERSION: 24
  NODE_OPTIONS: "--max_old_space_size=4096"

jobs:
  bundle-analysis:
    runs-on: ubuntu-latest
    steps:
      - name: "Check out Git repository"
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2

      - name: "Use Node.js ${{ env.NODE_DEFAULT_VERSION }}"
        uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af #v4.1.0
        with:
          node-version: ${{ env.NODE_DEFAULT_VERSION }}

      - name: "Install backend dependencies"
        run: |
          npm install --ignore-scripts

      - name: "Install frontend dependencies and build"
        run: |
          cd frontend
          npm install --ignore-scripts
          npm run build

      - name: "Generate bundle report"
        run: |
          cd frontend
          npm run bundle-visualizer

      - name: "Install Playwright for screenshot"
        run: npm install playwright

      - name: "Take screenshot of bundle report"
        run: |
          npx playwright install chromium
          node -e "
            const { chromium } = require('playwright');
            (async () => {
              const browser = await chromium.launch();
              const page = await browser.newPage();
              const filePath = 'file://${{ github.workspace }}/frontend/dist/frontend/bundle-report.html';
              await page.goto(filePath);
              await page.setViewportSize({ width: 1920, height: 1080 });
              await page.screenshot({ path: 'screenshots/bundle-analysis.png', fullPage: true });
              await browser.close();
              console.log('Screenshot saved to screenshots/bundle-analysis.png');
            })();
          "

      - name: "Commit and push screenshot to master"
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git checkout master || git checkout -b master
          git add screenshots/bundle-analysis.png
          git diff --quiet && git diff --staged --quiet || git commit -m "📸 Update bundle analysis screenshot" -s
          git push origin master
        continue-on-error: true
