name: Deploy Workers

on:
  workflow_dispatch:
    inputs:
      action:
        description: 'Action to perform'
        required: true
        type: choice
        options:
          - deploy
          - destroy
          - status
      job_name:
        description: 'Specific job name (blank for all jobs)'
        required: false
        default: ''
  push:
    branches:
      - main
    paths:
      - 'packages/backend/**'
      - 'docker-compose.workers.yml'

jobs:
{% for job in jobs %}
  deploy-{{ job.name }}:
    name: Deploy {{ job.name }}
    runs-on: ubuntu-latest
    if: ${{ '{{' }} github.event.inputs.action != 'destroy' && (github.event.inputs.job_name == '' || github.event.inputs.job_name == '{{ job.name }}') {{ '}}' }}
    steps:
      - uses: actions/checkout@v4

      - name: Install hcloud CLI
        run: |
          curl -sL https://github.com/hetznercloud/cli/releases/latest/download/hcloud-linux-amd64.tar.gz | tar xz
          sudo mv hcloud /usr/local/bin/

      - name: Check if worker VM exists
        id: check
        env:
          HCLOUD_TOKEN: ${{ '{{' }} secrets.HCLOUD_TOKEN {{ '}}' }}
        run: |
          SERVER_NAME="{{ project_name }}-worker-{{ job.name }}"
          if hcloud server describe "$SERVER_NAME" &>/dev/null; then
            echo "exists=true" >> "$GITHUB_OUTPUT"
            SERVER_IP=$(hcloud server ip "$SERVER_NAME")
            echo "server_ip=$SERVER_IP" >> "$GITHUB_OUTPUT"
          else
            echo "exists=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Create worker VM
        if: steps.check.outputs.exists == 'false'
        env:
          HCLOUD_TOKEN: ${{ '{{' }} secrets.HCLOUD_TOKEN {{ '}}' }}
        run: |
          SERVER_NAME="{{ project_name }}-worker-{{ job.name }}"
          hcloud server create \
            --name "$SERVER_NAME" \
            --type {{ job.server_type or default_server_type }} \
            --location {{ job.location or default_location }} \
            --image {{ job.image }} \
            --label managed-by=prisme \
            --label purpose=worker \
            --label job-name={{ job.name }} \
            --label project={{ project_name }}

          echo "Waiting for server to be ready..."
          sleep 30

      - name: Deploy worker container
        env:
          HCLOUD_TOKEN: ${{ '{{' }} secrets.HCLOUD_TOKEN {{ '}}' }}
        run: |
          SERVER_NAME="{{ project_name }}-worker-{{ job.name }}"
          SERVER_IP=$(hcloud server ip "$SERVER_NAME")

          {% if job.docker_image %}
          DOCKER_IMAGE="{{ job.docker_image }}"
          {% else %}
          DOCKER_IMAGE="{{ docker_registry }}/${{ '{{' }} github.repository {{ '}}' }}-backend:latest"
          {% endif %}

          {% if job.restart_policy == "always" %}
          RESTART_FLAG="--restart=always"
          {% elif job.restart_policy == "on-failure" %}
          RESTART_FLAG="--restart=on-failure:{{ job.max_restarts }}"
          {% else %}
          RESTART_FLAG="--restart=no"
          {% endif %}

          ssh -o StrictHostKeyChecking=no root@$SERVER_IP << 'DEPLOY'
            docker pull $DOCKER_IMAGE

            # Stop existing container if running
            docker stop {{ project_name }}-{{ job.name }} 2>/dev/null || true
            docker rm {{ project_name }}-{{ job.name }} 2>/dev/null || true

            {% if job.schedule %}
            # Scheduled job: set up cron
            cat > /etc/cron.d/{{ job.name | replace("-", "_") }} << 'CRON'
            {{ job.schedule }} root docker run --rm \
              --name {{ project_name }}-{{ job.name }}-cron \
              {% for key, value in job.environment.items() %}
              -e {{ key }}="{{ value }}" \
              {% endfor %}
              $DOCKER_IMAGE \
              {{ job.command }}
            CRON
            chmod 0644 /etc/cron.d/{{ job.name | replace("-", "_") }}
            systemctl restart cron
            {% else %}
            # Long-running worker
            docker run -d \
              --name {{ project_name }}-{{ job.name }} \
              $RESTART_FLAG \
              --stop-timeout {{ job.timeout_seconds }} \
              --memory {{ job.memory_mb }}m \
              --cpus {{ job.cpu }} \
              {% for key, value in job.environment.items() %}
              -e {{ key }}="{{ value }}" \
              {% endfor %}
              $DOCKER_IMAGE \
              {{ job.command }}
            {% endif %}
          DEPLOY

          echo "Worker {{ job.name }} deployed to $SERVER_IP"

{% endfor %}

  destroy-workers:
    name: Destroy Workers
    runs-on: ubuntu-latest
    if: ${{ '{{' }} github.event.inputs.action == 'destroy' {{ '}}' }}
    steps:
      - name: Install hcloud CLI
        run: |
          curl -sL https://github.com/hetznercloud/cli/releases/latest/download/hcloud-linux-amd64.tar.gz | tar xz
          sudo mv hcloud /usr/local/bin/

      - name: Destroy worker VMs
        env:
          HCLOUD_TOKEN: ${{ '{{' }} secrets.HCLOUD_TOKEN {{ '}}' }}
        run: |
          JOB_NAME="${{ '{{' }} github.event.inputs.job_name {{ '}}' }}"

          if [ -n "$JOB_NAME" ]; then
            SERVER_NAME="{{ project_name }}-worker-$JOB_NAME"
            echo "Destroying worker: $SERVER_NAME"
            hcloud server delete "$SERVER_NAME" || echo "Server not found"
          else
            echo "Destroying all {{ project_name }} workers..."
            {% for job in jobs %}
            hcloud server delete "{{ project_name }}-worker-{{ job.name }}" 2>/dev/null || true
            {% endfor %}
          fi

  worker-status:
    name: Worker Status
    runs-on: ubuntu-latest
    if: ${{ '{{' }} github.event.inputs.action == 'status' {{ '}}' }}
    steps:
      - name: Install hcloud CLI
        run: |
          curl -sL https://github.com/hetznercloud/cli/releases/latest/download/hcloud-linux-amd64.tar.gz | tar xz
          sudo mv hcloud /usr/local/bin/

      - name: Show worker status
        env:
          HCLOUD_TOKEN: ${{ '{{' }} secrets.HCLOUD_TOKEN {{ '}}' }}
        run: |
          echo "## Worker Status — {{ project_name }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Job | Server | Status | IP |" >> $GITHUB_STEP_SUMMARY
          echo "|-----|--------|--------|----|" >> $GITHUB_STEP_SUMMARY

          {% for job in jobs %}
          SERVER_NAME="{{ project_name }}-worker-{{ job.name }}"
          if hcloud server describe "$SERVER_NAME" -o json &>/dev/null; then
            STATUS=$(hcloud server describe "$SERVER_NAME" -o json | jq -r '.status')
            IP=$(hcloud server ip "$SERVER_NAME" 2>/dev/null || echo "N/A")
            echo "| {{ job.name }} | $SERVER_NAME | $STATUS | $IP |" >> $GITHUB_STEP_SUMMARY
          else
            echo "| {{ job.name }} | $SERVER_NAME | not deployed | - |" >> $GITHUB_STEP_SUMMARY
          fi
          {% endfor %}
