# ============================================================================
# DISABLED 3 August 2026 — this workflow will not run.
#
# Disabled via `gh workflow disable`, not by removing triggers, so the logic
# below is preserved verbatim. The disabled state lives in GitHub's API and is
# NOT visible in git, which is why this comment exists.
#
# Re-enable with:
#   gh workflow disable/enable — see the sibling preview-*.yml files too
#   gh workflow enable "Preview: Deploy" --repo Gemma-Analytics/gemmbot
#
# Why: it had never run once since being written, while `preview-deploy.sh`
# copies the PRODUCTION .env — including the real Google OAuth client id and
# secret — onto the preview host. Untested infrastructure that hands production
# credentials to another environment is a liability, not a feature. Retired as
# part of the August 2026 GCP rebuild.
#
# Before re-enabling, note the preview callback was never registered on any
# OAuth client, so Google sign-in on a preview fails with redirect_uri_mismatch.
# You would need to add BOTH of these to the Gemmbot client in the
# gemma-oauth-internal project:
#   origin:   https://preview.gemmbot.gemmaanalytics.com
#   redirect: https://preview.gemmbot.gemmaanalytics.com/api/auth/callback/google
# Better still, give previews their own OAuth client rather than reusing prod's.
# ============================================================================
name: "Preview: Deploy"
run-name: "Preview: Deploy PR #${{ github.event.issue.number || github.event.pull_request.number }}"

on:
  # Trigger on label added to PR
  pull_request:
    types: [labeled]

  # Trigger on /preview comment
  issue_comment:
    types: [created]

jobs:
  deploy-preview:
    runs-on: ubuntu-latest
    # Run if: label "preview" was added, OR someone commented "/preview" on a PR
    if: >
      (github.event_name == 'pull_request' && github.event.label.name == 'preview') ||
      (github.event_name == 'issue_comment' && github.event.issue.pull_request && github.event.comment.body == '/preview')

    steps:
      - name: Get PR info
        id: pr
        uses: actions/github-script@v7
        with:
          script: |
            let pr;
            if (context.eventName === 'issue_comment') {
              const { data } = await github.rest.pulls.get({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: context.issue.number,
              });
              pr = data;
            } else {
              pr = context.payload.pull_request;
            }
            core.setOutput('number', pr.number);
            core.setOutput('ref', pr.head.ref);
            core.setOutput('sha', pr.head.sha);
            core.setOutput('state', pr.state);

      - name: Reject if PR is closed
        if: steps.pr.outputs.state != 'open'
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: ${{ steps.pr.outputs.number }},
              body: '⛔ **Cannot deploy preview for a closed PR.** Reopen the PR first, then try again.',
            });
            core.setFailed('PR is closed — preview deployment not allowed.');

      - name: React to comment
        if: github.event_name == 'issue_comment'
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.reactions.createForIssueComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: context.payload.comment.id,
              content: 'rocket',
            });

      - name: Post deployment status comment
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: ${{ steps.pr.outputs.number }},
              body: '🚀 **Deploying preview environment...**\n\nBuilding and deploying `${{ steps.pr.outputs.ref }}` (`${{ steps.pr.outputs.sha }}`). This takes ~2 minutes.',
            });

      - name: Setup SSH
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_SSH_KEY: ${{ secrets.EC2_SSH_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$EC2_SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H $EC2_HOST >> ~/.ssh/known_hosts

      - name: Checkout PR branch
        uses: actions/checkout@v4
        with:
          ref: ${{ steps.pr.outputs.ref }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'
          cache-dependency-path: ui/package-lock.json

      - name: Build UI
        working-directory: ui
        run: |
          npm ci
          npx prisma generate
          npx next build

      - name: Deploy preview to EC2
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_USER: ${{ secrets.EC2_USER }}
          PR_NUMBER: ${{ steps.pr.outputs.number }}
        run: |
          # Copy deploy script to EC2
          scp -i ~/.ssh/deploy_key .github/scripts/preview-deploy.sh $EC2_USER@$EC2_HOST:/opt/gemmbot/preview-deploy.sh
          ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST "chmod +x /opt/gemmbot/preview-deploy.sh"

          # Sync built UI to EC2 staging area
          rsync -rlvz --delete --omit-dir-times \
            -e "ssh -i ~/.ssh/deploy_key" \
            --exclude node_modules \
            --exclude .env \
            --exclude .env.local \
            ui/ $EC2_USER@$EC2_HOST:/opt/gemmbot/preview-staging/

          # Run deploy script (replaces any existing preview)
          ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST \
            "/opt/gemmbot/preview-deploy.sh ${PR_NUMBER}"

      - name: Verify preview is healthy
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_USER: ${{ secrets.EC2_USER }}
        run: |
          sleep 5
          ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST \
            "curl -s -o /dev/null -w '%{http_code}' http://localhost:4001/login" | grep -q "200" || {
            echo "WARNING: Preview UI not responding yet, may still be starting"
          }

      - name: Post success comment
        if: success()
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: ${{ steps.pr.outputs.number }},
              body: '✅ **Preview environment ready!**\n\n🔗 https://preview.gemmbot.gemmaanalytics.com\n\nLog in with your Gemma Google account.\n\nTo tear down: comment `/preview-down` or close/merge the PR.',
            });

      - name: Post failure comment
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: ${{ steps.pr.outputs.number }},
              body: '❌ **Preview deployment failed.** Check the [workflow logs](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details.',
            });
