# ============================================================================
# DISABLED 3 August 2026 — this workflow will not run.
#
# Disabled via `gh workflow disable`, so the logic below is preserved verbatim.
# The disabled state lives in GitHub's API and is NOT visible in git.
#
# Re-enable with:
#   gh workflow enable "Preview: Cleanup" --repo Gemma-Analytics/gemmbot
#
# Why: it is the teardown half of a preview system whose deploy half never ran
# once. It had itself executed 76 times, tearing down previews that had never
# been created. Disabled together with preview-deploy.yml and preview-stale.yml
# so the three stay coherent — re-enable them as a set.
# ============================================================================
name: "Preview: Cleanup"
run-name: "Preview: Cleanup PR #${{ github.event.issue.number || github.event.pull_request.number || 'stale' }}"

on:
  # Auto-cleanup when PR is closed or merged
  pull_request:
    types: [closed]

  # Manual cleanup via /preview-down comment
  issue_comment:
    types: [created]

  # Allow other workflows to call this (e.g. stale preview cleanup)
  workflow_call:

jobs:
  cleanup-preview:
    runs-on: ubuntu-latest
    if: >
      (github.event_name == 'pull_request') ||
      (github.event_name == 'issue_comment' && github.event.issue.pull_request && github.event.comment.body == '/preview-down') ||
      (github.event_name == 'workflow_call')

    steps:
      - 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: Check if preview exists for this PR
        id: check
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_USER: ${{ secrets.EC2_USER }}
        run: |
          # For workflow_call (stale cleanup), just check if any preview exists
          if [ "${{ github.event_name }}" = "workflow_call" ]; then
            EXISTS=$(ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST '
              if [ -f /opt/gemmbot/preview/.pr-number ]; then
                echo "true"
              else
                echo "false"
              fi
            ')
            echo "exists=$EXISTS" >> $GITHUB_OUTPUT
            exit 0
          fi

          # For PR events, check if the preview belongs to this PR
          PR_NUMBER=${{ github.event.pull_request.number || github.event.issue.number }}

          EXISTS=$(ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST '
            if [ -f /opt/gemmbot/preview/.pr-number ]; then
              DEPLOYED_PR=$(cat /opt/gemmbot/preview/.pr-number)
              if [ "$DEPLOYED_PR" = "'"$PR_NUMBER"'" ]; then
                echo "true"
              else
                echo "false"
              fi
            else
              echo "false"
            fi
          ')

          if [ "$EXISTS" = "false" ]; then
            echo "No preview environment found for PR #${PR_NUMBER}"
          else
            echo "Found preview environment for PR #${PR_NUMBER}"
          fi
          echo "exists=$EXISTS" >> $GITHUB_OUTPUT

      - name: Checkout code
        if: steps.check.outputs.exists == 'true'
        uses: actions/checkout@v4

      - name: Cleanup preview on EC2
        if: steps.check.outputs.exists == 'true'
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_USER: ${{ secrets.EC2_USER }}
        run: |
          # Copy cleanup script to EC2
          scp -i ~/.ssh/deploy_key .github/scripts/preview-cleanup.sh $EC2_USER@$EC2_HOST:/opt/gemmbot/preview-cleanup.sh
          ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST "chmod +x /opt/gemmbot/preview-cleanup.sh"

          # Run cleanup (no arguments — single preview directory)
          ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST \
            "/opt/gemmbot/preview-cleanup.sh"

      - name: Post cleanup comment
        if: steps.check.outputs.exists == 'true' && github.event_name != 'workflow_call'
        uses: actions/github-script@v7
        with:
          script: |
            const prNumber = context.payload.pull_request?.number || context.issue?.number;
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: prNumber,
              body: '🧹 **Preview environment cleaned up.**',
            });
