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
        env:
          POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
          POSTGRES_USER: ${{ secrets.POSTGRES_USER }}
          POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
          POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }}
          POSTGRES_PORT: ${{ secrets.POSTGRES_PORT }}
          CRANK_STORAGE_ROOT: ${{ secrets.CRANK_STORAGE_ROOT }}
          CRANK_PUBLISH_BIND: ${{ secrets.CRANK_PUBLISH_BIND }}
          CRANK_ADMIN_BIND: ${{ secrets.CRANK_ADMIN_BIND }}
          CRANK_MCP_BIND: ${{ secrets.CRANK_MCP_BIND }}
          CRANK_MCP_REFRESH_MS: ${{ secrets.CRANK_MCP_REFRESH_MS }}
          CRANK_LOG_LEVEL: ${{ secrets.CRANK_LOG_LEVEL }}
          CRANK_MASTER_KEY: ${{ secrets.CRANK_MASTER_KEY }}
          CRANK_BASE_URL: ${{ secrets.CRANK_BASE_URL }}
          CRANK_SESSION_SECRET: ${{ secrets.CRANK_SESSION_SECRET }}
          CRANK_PASSWORD_PEPPER: ${{ secrets.CRANK_PASSWORD_PEPPER }}
          CRANK_SESSION_TTL_HOURS: ${{ secrets.CRANK_SESSION_TTL_HOURS }}
          CRANK_BOOTSTRAP_ADMIN_EMAIL: ${{ secrets.CRANK_BOOTSTRAP_ADMIN_EMAIL }}
          CRANK_BOOTSTRAP_ADMIN_PASSWORD: ${{ secrets.CRANK_BOOTSTRAP_ADMIN_PASSWORD }}
          CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME: ${{ secrets.CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME }}
          CRANK_DEMO_SEED: ${{ secrets.CRANK_DEMO_SEED }}
        run: |
          tmp_env="$(mktemp)"
          append_if_set() {
            if [ -n "$2" ]; then
              printf '%s=%s\n' "$1" "$2" >> "$tmp_env"
            fi
          }
          : > "$tmp_env"
          append_if_set POSTGRES_DB "$POSTGRES_DB"
          append_if_set POSTGRES_USER "$POSTGRES_USER"
          append_if_set POSTGRES_PASSWORD "$POSTGRES_PASSWORD"
          append_if_set POSTGRES_HOST "$POSTGRES_HOST"
          append_if_set POSTGRES_PORT "$POSTGRES_PORT"
          append_if_set CRANK_STORAGE_ROOT "$CRANK_STORAGE_ROOT"
          append_if_set CRANK_PUBLISH_BIND "$CRANK_PUBLISH_BIND"
          append_if_set CRANK_ADMIN_BIND "$CRANK_ADMIN_BIND"
          append_if_set CRANK_MCP_BIND "$CRANK_MCP_BIND"
          append_if_set CRANK_MCP_REFRESH_MS "$CRANK_MCP_REFRESH_MS"
          append_if_set CRANK_LOG_LEVEL "$CRANK_LOG_LEVEL"
          append_if_set CRANK_MASTER_KEY "$CRANK_MASTER_KEY"
          append_if_set CRANK_BASE_URL "$CRANK_BASE_URL"
          append_if_set CRANK_SESSION_SECRET "$CRANK_SESSION_SECRET"
          append_if_set CRANK_PASSWORD_PEPPER "$CRANK_PASSWORD_PEPPER"
          append_if_set CRANK_SESSION_TTL_HOURS "$CRANK_SESSION_TTL_HOURS"
          append_if_set CRANK_BOOTSTRAP_ADMIN_EMAIL "$CRANK_BOOTSTRAP_ADMIN_EMAIL"
          append_if_set CRANK_BOOTSTRAP_ADMIN_PASSWORD "$CRANK_BOOTSTRAP_ADMIN_PASSWORD"
          append_if_set CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME "$CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME"
          append_if_set CRANK_DEMO_SEED "$CRANK_DEMO_SEED"
          {
            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 }}"
          } >> "$tmp_env"
          cat "$tmp_env" | ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" \
            "mkdir -p '${{ secrets.DEPLOY_PATH }}' && cat > '${{ secrets.DEPLOY_PATH }}/.env'"
          rm -f "$tmp_env"

      - name: Validate required environment variables
        run: |
          ssh "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" "
            set -e
            cd '${{ secrets.DEPLOY_PATH }}'
            required_vars='
              POSTGRES_HOST
              POSTGRES_PORT
              POSTGRES_DB
              POSTGRES_USER
              POSTGRES_PASSWORD
              CRANK_MASTER_KEY
              CRANK_SESSION_SECRET
              CRANK_PASSWORD_PEPPER
              CRANK_BOOTSTRAP_ADMIN_EMAIL
              CRANK_BOOTSTRAP_ADMIN_PASSWORD
              CRANK_BASE_URL
            '
            for var in \$required_vars; do
              value=\$(grep -E \"^\${var}=\" .env | tail -n1 | cut -d= -f2- || true)
              if [ -z \"\$value\" ]; then
                echo \"missing required env: \$var\" >&2
                exit 1
              fi
            done
          "

      - 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
          "
