name: Deploy to Digital Ocean

on:
  workflow_run:
    workflows: ["Publish to PyPI"]
    types: [completed]
  workflow_dispatch:  # Allow manual trigger
    inputs:
      version:
        description: 'Version to deploy (leave empty for latest)'
        required: false

jobs:
  deploy:
    name: Deploy to Production
    runs-on: ubuntu-latest
    environment: "Digital Ocean"
    if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}

    steps:
      - name: Deploy to Digital Ocean
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.DO_DROPLET_IP }}
          username: root
          key: ${{ secrets.DO_SSH_KEY }}
          script: |
            echo "Upgrading WineBox..."
            sudo -u winebox /opt/winebox/.venv/bin/pip install winebox --upgrade --no-cache-dir

            echo "Updating static files symlink..."
            rm -f /opt/winebox/static
            ln -sf /opt/winebox/.venv/lib/python3.*/site-packages/winebox/static /opt/winebox/static

            echo "Restarting service..."
            systemctl restart winebox

            echo "Reloading nginx..."
            nginx -t && systemctl reload nginx

            echo "Waiting for service to start..."
            sleep 5

            echo "Checking service status..."
            systemctl is-active winebox

            echo "Health check (with retry)..."
            for i in 1 2 3 4 5; do
              if curl -sf http://localhost:8000/health; then
                echo ""
                echo "Deployment complete!"
                exit 0
              fi
              echo "Attempt $i failed, retrying in 2s..."
              sleep 2
            done
            echo "Health check failed after 5 attempts"
            exit 1
