      # ==============================================
      # SAFE AUTO-DEPLOY WITH HEALTH CHECK & ROLLBACK
      # ==============================================
      # Enhanced deployment with safety features:
      # - Health check after deployment
      # - Automatic rollback on failure
      # - Deployment notifications
      # - Downtime tracking
      #
      - name: Deploy to Production (Safe)
        if: success() && github.ref == 'refs/heads/main'
        run: |
          # Set up SSH
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H ${{ secrets.PRODUCTION_HOST }} >> ~/.ssh/known_hosts

          echo "Deploying Paper Dynasty v${{ steps.meta.outputs.version }} to production..."
          DEPLOY_START=$(date +%s)

          # Deploy with health check and rollback
          ssh -i ~/.ssh/deploy_key ${{ secrets.DEPLOY_USER }}@${{ secrets.PRODUCTION_HOST }} bash << 'EOF'
            set -e
            cd /home/cal/container-data/paper-dynasty

            # Save current image tag for rollback
            CURRENT_IMAGE=$(docker compose images -q paper-dynasty 2>/dev/null || echo "none")
            echo "Current image: $CURRENT_IMAGE"

            # Pull new image
            echo "Pulling new image..."
            docker compose pull

            # Stop old container
            echo "Stopping old container..."
            docker compose down

            # Start new container
            echo "Starting new container..."
            docker compose up -d

            # Health check with retry
            echo "Running health check..."
            for i in {1..10}; do
              sleep 3
              if docker compose ps | grep -q "Up"; then
                echo "Container is up!"

                # Additional health check: check bot is responding
                # Adjust this based on your bot's health endpoint
                # if curl -f http://localhost:YOUR_PORT/health; then
                #   echo "Health check passed!"
                #   exit 0
                # fi

                exit 0
              fi
              echo "Waiting for container... ($i/10)"
            done

            # If we get here, deployment failed
            echo "Health check failed! Rolling back..."

            # Rollback to previous image
            if [ "$CURRENT_IMAGE" != "none" ]; then
              docker compose down
              # This assumes you have the old image still cached
              # In production, you might want to keep the last N images
              docker compose up -d
              echo "Rolled back to previous version"
              exit 1
            else
              echo "WARNING: No previous image to rollback to!"
              exit 1
            fi
          EOF

          DEPLOY_STATUS=$?
          DEPLOY_END=$(date +%s)
          DEPLOY_TIME=$((DEPLOY_END - DEPLOY_START))

          if [ $DEPLOY_STATUS -eq 0 ]; then
            echo "Deployment successful! (${DEPLOY_TIME}s)"
          else
            echo "Deployment failed after ${DEPLOY_TIME}s"
            exit 1
          fi

      # ==============================================
      # CREATE GIT TAG - MARK DEPLOYED VERSION
      # ==============================================
      # Creates immutable git tag after successful deployment
      # - Only tags after deployment health check passes
      # - Tag matches VERSION file (single source of truth)
      # - Represents what's actually running in production
      # - Enables version history and rollback references
      #
      - name: Create Git Tag
        if: success() && github.ref == 'refs/heads/main'
        run: |
          VERSION=$(cat VERSION)

          # Configure git
          git config user.name "Gitea Actions"
          git config user.email "actions@git.manticorum.com"

          # Create annotated tag with deployment info
          git tag -a "v${VERSION}" -m "Release v${VERSION}

          Deployed: ${{ steps.meta.outputs.timestamp }}
          Commit: ${{ github.sha }}
          Author: ${{ github.actor }}

          Deployed to production and health check passed
          Built and deployed via Gitea Actions"

          # Push tag to repository
          git push origin "v${VERSION}"

          echo "Created and pushed tag v${VERSION}"

      # ==============================================
      # DEPLOYMENT NOTIFICATION - SUCCESS
      # ==============================================
      - name: Discord Notification - Deployed Successfully
        if: success() && github.ref == 'refs/heads/main'
        run: |
          curl -H "Content-Type: application/json" \
            -d '{
              "embeds": [{
                "title": "Paper Dynasty Deployed to Production",
                "description": "New version is live and healthy",
                "color": 5793266,
                "fields": [
                  {
                    "name": "Version",
                    "value": "`v${{ steps.meta.outputs.version }}`",
                    "inline": true
                  },
                  {
                    "name": "Git Tag",
                    "value": "[v${{ steps.meta.outputs.version }}](${{ github.server_url }}/${{ github.repository }}/releases/tag/v${{ steps.meta.outputs.version }})",
                    "inline": true
                  },
                  {
                    "name": "Deployed By",
                    "value": "${{ github.actor }}",
                    "inline": true
                  },
                  {
                    "name": "Server",
                    "value": "sba-bots (10.10.0.88)",
                    "inline": true
                  },
                  {
                    "name": "Status",
                    "value": "Health check passed",
                    "inline": false
                  }
                ],
                "timestamp": "${{ steps.meta.outputs.timestamp }}"
              }]
            }' \
            https://discord.com/api/webhooks/YOUR_WEBHOOK_URL

      # ==============================================
      # DEPLOYMENT NOTIFICATION - FAILED/ROLLED BACK
      # ==============================================
      - name: Discord Notification - Deployment Failed
        if: failure() && github.ref == 'refs/heads/main'
        run: |
          TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)
          curl -H "Content-Type: application/json" \
            -d '{
              "embeds": [{
                "title": "Paper Dynasty Deployment Failed",
                "description": "Deployment failed and was rolled back to previous version",
                "color": 16776960,
                "fields": [
                  {
                    "name": "Attempted Version",
                    "value": "`v${{ steps.meta.outputs.version }}`",
                    "inline": true
                  },
                  {
                    "name": "Author",
                    "value": "${{ github.actor }}",
                    "inline": true
                  },
                  {
                    "name": "Action",
                    "value": "Rolled back to previous version",
                    "inline": false
                  },
                  {
                    "name": "View Logs",
                    "value": "[Click here](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})",
                    "inline": false
                  }
                ],
                "timestamp": "'"$TIMESTAMP"'"
              }]
            }' \
            https://discord.com/api/webhooks/YOUR_WEBHOOK_URL
