name: Deploy

on:
  workflow_run:
    workflows:
      - CI
    types:
      - completed
  workflow_dispatch:

concurrency:
  group: deploy-${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_branch || github.ref }}
  cancel-in-progress: true

permissions:
  contents: read
  packages: write

env:
  IMAGE_TAG: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}
  ADMIN_API_IMAGE: ghcr.io/${{ github.repository_owner }}/crank-admin-api
  MCP_SERVER_IMAGE: ghcr.io/${{ github.repository_owner }}/crank-mcp-server
  UI_IMAGE: ghcr.io/${{ github.repository_owner }}/crank-ui

jobs:
  build-images:
    if: >
      github.event_name == 'workflow_dispatch' ||
      (
        github.event_name == 'workflow_run' &&
        github.event.workflow_run.conclusion == 'success' &&
        github.event.workflow_run.head_branch == 'main'
      )
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - name: admin-api
            dockerfile: apps/admin-api/Dockerfile
          - name: mcp-server
            dockerfile: apps/mcp-server/Dockerfile
          - name: ui
            dockerfile: apps/ui/Dockerfile

    steps:
      - name: Checkout
        uses: actions/checkout@v5
        with:
          ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}

      - name: Resolve image name
        id: image
        run: |
          case "${{ matrix.name }}" in
            admin-api) echo "name=${ADMIN_API_IMAGE}" >> "$GITHUB_OUTPUT" ;;
            mcp-server) echo "name=${MCP_SERVER_IMAGE}" >> "$GITHUB_OUTPUT" ;;
            ui) echo "name=${UI_IMAGE}" >> "$GITHUB_OUTPUT" ;;
            *) exit 1 ;;
          esac

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v4

      - name: Log in to GHCR
        uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push ${{ matrix.name }}
        uses: docker/build-push-action@v7
        with:
          context: .
          file: ${{ matrix.dockerfile }}
          push: true
          tags: |
            ${{ steps.image.outputs.name }}:${{ env.IMAGE_TAG }}
            ${{ steps.image.outputs.name }}:main
          cache-from: type=gha,scope=${{ matrix.name }}
          cache-to: type=gha,mode=max,scope=${{ matrix.name }}

  deploy:
    needs: build-images
    if: >
      github.event_name == 'workflow_dispatch' ||
      (
        github.event_name == 'workflow_run' &&
        github.event.workflow_run.conclusion == 'success' &&
        github.event.workflow_run.head_branch == 'main'
      )
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v5
        with:
          ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}

      - name: Configure SSH key
        run: |
          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519

      - name: Configure known hosts
        run: |
          printf '%s\n' "${{ secrets.DEPLOY_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
          chmod 644 ~/.ssh/known_hosts

      - name: Sync deployment files to server
        run: |
          ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" \
            "mkdir -p '${{ secrets.DEPLOY_PATH }}'"
          rsync -az docker-compose.yml \
            "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:${{ secrets.DEPLOY_PATH }}/docker-compose.yml"

      - name: Write environment file
        run: |
          {
            printf '%s\n' "${{ secrets.DEPLOY_ENV_FILE }}"
            printf 'CRANK_ADMIN_API_IMAGE=%s:%s\n' "${{ env.ADMIN_API_IMAGE }}" "${{ env.IMAGE_TAG }}"
            printf 'CRANK_MCP_SERVER_IMAGE=%s:%s\n' "${{ env.MCP_SERVER_IMAGE }}" "${{ env.IMAGE_TAG }}"
            printf 'CRANK_UI_IMAGE=%s:%s\n' "${{ env.UI_IMAGE }}" "${{ env.IMAGE_TAG }}"
          } | ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" \
            "mkdir -p '${{ secrets.DEPLOY_PATH }}' && cat > '${{ secrets.DEPLOY_PATH }}/.env'"

      - name: Apply deploy overrides
        run: |
          if [ -n "${{ secrets.DEPLOY_DEMO_SEED }}" ]; then
            ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" "
              set -e
              cd '${{ secrets.DEPLOY_PATH }}'
              sed -i '/^CRANK_DEMO_SEED=/d' .env
              printf 'CRANK_DEMO_SEED=%s\n' '${{ secrets.DEPLOY_DEMO_SEED }}' >> .env
            "
          fi

      - name: Deploy with Docker Compose
        run: |
          ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" "
            set -e
            cd '${{ secrets.DEPLOY_PATH }}'
            echo '${{ secrets.DEPLOY_REGISTRY_TOKEN }}' | docker login ghcr.io -u '${{ secrets.DEPLOY_REGISTRY_USER }}' --password-stdin
            docker compose config -q
            docker compose pull admin-api mcp-server ui
            docker compose up -d --remove-orphans
          "

      - name: Verify health endpoints
        run: |
          ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" "
            set -e
            cd '${{ secrets.DEPLOY_PATH }}'
            for attempt in \$(seq 1 30); do
              if curl --fail --silent http://127.0.0.1:3000/ >/dev/null \
                && curl --fail --silent http://127.0.0.1:3001/health >/dev/null \
                && curl --fail --silent http://127.0.0.1:3002/health >/dev/null; then
                exit 0
              fi
              sleep 2
            done
            echo 'deployment health verification failed' >&2
            docker compose ps >&2
            exit 1
          "
