name: Deploy to GitHub Pages

on:
  push:
    branches: [develop]
  workflow_dispatch:
    inputs:
      backend_url:
        description: 'Backend Base URL (e.g. https://agent.bytedev.site/)'
        required: true
        default: 'https://agent.bytedev.site/'
        type: string

jobs:
  deploy-gh-pages:
    runs-on: ubuntu-latest
    concurrency:
      group: deploy-gh-pages
      cancel-in-progress: true
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 10
          run_install: false

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - name: Install dependencies
        run: pnpm install

      - name: add environment variable
        env:
          ENV_BACKEND_URL: ${{ github.event.inputs.backend_url || 'https://agent.bytedev.site/' }}
        run: |
          if [[ "$ENV_BACKEND_URL" == *$'\n'* || "$ENV_BACKEND_URL" == *$'\r'* ]]; then
            echo "::error::backend_url must be a single-line value"
            exit 1
          fi

          if [[ ! "$ENV_BACKEND_URL" =~ ^https?://[a-zA-Z0-9._-]+(:[0-9]+)?(/[a-zA-Z0-9._/~:%-]*)?$ ]]; then
            echo "::error::backend_url must be an http(s) base URL using only URL-safe characters (letters, digits, . _ - / ~ : %)"
            exit 1
          fi

          ENV_BACKEND_URL="${ENV_BACKEND_URL%/}/"

          cat <<EOF >> designer-demo/env/.env.alpha
          # ---- appended by CI (gh-pages) ----
          VITE_ORIGIN=$ENV_BACKEND_URL
          EOF
          echo "VITE_ORIGIN_URL=$ENV_BACKEND_URL"
      - name: Run Build
        run: |
          set -eo pipefail
          pnpm run build:plugin 2>&1 | tee /tmp/build-plugin.log
          pnpm run build:alpha 2>&1 | tee /tmp/build-alpha.log

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v4
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./designer-demo/dist/
          keep_files: true
          force_orphan: false
          user_name: 'github-actions[bot]'
          user_email: 'github-actions[bot]@users.noreply.github.com'