name: CD

# Continuous deployment: after CI passes on a push (merge) to master:
#   1. Build the app image and push it to ghcr.io/lightup-data/polaris:<sha>, then
#      SSH to the prod host and run deploy.sh for that commit (fast-forward, pull
#      image, up, prune, post-deploy health check). Nothing is built on the server.
#   2. Publish @lightupai/polaris to npm if the version in package.json has been
#      bumped beyond what is already published (i.e. only when there are client-side
#      changes that warrant a release).
#
# Required repository secrets (Settings → Secrets and variables → Actions):
#   DEPLOY_HOST     — hostname or IP of the prod box (e.g. polaris.lightup.ai)
#   DEPLOY_SSH_KEY  — private SSH key (OpenSSH format) for the deploy user
#   NPM_TOKEN       — npm Automation token (bypasses OTP; create at npmjs.com)
#
# Optional repository secrets (deploy.sh has sensible defaults):
#   DEPLOY_USER     — SSH user on the prod box (default: deploy)
#   DEPLOY_DIR      — checkout directory on the prod box (default: /opt/polaris)
#
# If DEPLOY_HOST / DEPLOY_SSH_KEY are not configured, the deploy job is
# skipped cleanly (check-secrets still succeeds), so this workflow is a
# safe no-op on forks and on repos where CD has not been set up yet.

on:
  # Only after CI passes for a push to master, so a merge that fails tests never ships
  workflow_run:
    workflows: [CI]
    types: [completed]
    branches: [master]
  workflow_dispatch:
    inputs:
      force:
        description: "Build and deploy even if no server-side files changed"
        type: boolean
        default: false

# Never run two deploys at once; queue (don't cancel) an in-flight deploy.
concurrency:
  group: deploy-prod
  cancel-in-progress: false

jobs:
  check-secrets:
    if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
    runs-on: ubuntu-latest
    outputs:
      configured: ${{ steps.check.outputs.configured }}
    steps:
      # Secrets are not directly readable in a job-level `if`, so expose a
      # boolean output here and gate the deploy job on it.
      - name: Check deploy secrets
        id: check
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        run: |
          if [ -n "$DEPLOY_HOST" ] && [ -n "$DEPLOY_SSH_KEY" ]; then
            echo "configured=true" >> "$GITHUB_OUTPUT"
            echo "Deploy secrets present — deploy job will run."
          else
            echo "configured=false" >> "$GITHUB_OUTPUT"
            echo "DEPLOY_HOST / DEPLOY_SSH_KEY not configured — skipping deploy."
          fi

  # Fast path: client-only merges (CLI, MCP client, daemon, hooks, docs) ship via npm
  # alone. Diff the commit the server is actually running (the api container's image
  # tag) against this one; build + deploy only when server-side paths changed
  # (.github/server-paths.regex) or deps changed. Any doubt → deploy.
  plan:
    needs: check-secrets
    if: needs.check-secrets.outputs.configured == 'true'
    runs-on: ubuntu-latest
    outputs:
      deploy: ${{ steps.plan.outputs.deploy }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.workflow_run.head_sha || github.sha }}
          fetch-depth: 0
      - name: Set up SSH
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_deploy
          chmod 600 ~/.ssh/id_deploy
          printf 'Host *\n  IdentityFile ~/.ssh/id_deploy\n  StrictHostKeyChecking accept-new\n' >> ~/.ssh/config
          chmod 600 ~/.ssh/config
      - name: Decide
        id: plan
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          SHA: ${{ github.event.workflow_run.head_sha || github.sha }}
          FORCE: ${{ inputs.force }}
        run: |
          if [ "$FORCE" = "true" ]; then echo "deploy=true" >> "$GITHUB_OUTPUT"; echo "forced"; exit 0; fi
          image=$(ssh "${DEPLOY_USER:-deploy}@$DEPLOY_HOST" "docker inspect -f '{{.Config.Image}}' polaris-api-1" 2>/dev/null || true)
          deployed="${image##*:}"
          echo "server is running: ${image:-unknown}"
          echo "deploy=$(./scripts/needs-server-deploy.sh "$deployed" "$SHA")" >> "$GITHUB_OUTPUT"

  # The prod box never builds: CI builds the single app image (api/web/bridge all
  # use docker/Dockerfile) and pushes it to GHCR tagged with the commit SHA.
  build-image:
    needs: plan
    if: needs.plan.outputs.deploy == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.workflow_run.head_sha || github.sha }}
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          context: .
          file: docker/Dockerfile
          push: true
          tags: ghcr.io/lightup-data/polaris:${{ github.event.workflow_run.head_sha || github.sha }}
          labels: org.opencontainers.image.source=https://github.com/${{ github.repository }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  deploy:
    needs: [plan, build-image]
    if: needs.plan.outputs.deploy == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: read

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.workflow_run.head_sha || github.sha }}

      - name: Set up SSH
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_deploy
          chmod 600 ~/.ssh/id_deploy
          {
            echo "Host *"
            echo "  IdentityFile ~/.ssh/id_deploy"
            echo "  StrictHostKeyChecking accept-new"
          } >> ~/.ssh/config
          chmod 600 ~/.ssh/config

      - name: Deploy
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_DIR: ${{ secrets.DEPLOY_DIR }}
          DEPLOY_REF: ${{ github.event.workflow_run.head_sha || github.sha }}
          GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: ./deploy.sh

  publish-npm:
    if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.workflow_run.head_sha || github.sha }}

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - name: Check if version needs publishing
        id: version-check
        run: |
          LOCAL=$(node -p "require('./package.json').version")
          echo "local=$LOCAL" >> "$GITHUB_OUTPUT"
          # Check the exact version, not just the latest tag — handles the case where
          # a version was manually published but is still staging on the registry.
          if npm view "@lightupai/polaris@${LOCAL}" version > /dev/null 2>&1; then
            echo "should_publish=false" >> "$GITHUB_OUTPUT"
            echo "Version $LOCAL already published — skipping npm publish."
          else
            echo "should_publish=true" >> "$GITHUB_OUTPUT"
            echo "Version $LOCAL not yet published — will publish."
          fi

      - name: Publish to npm
        if: steps.version-check.outputs.should_publish == 'true'
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          LOCAL=${{ steps.version-check.outputs.local }}
          npm publish --access public || {
            # E409 = staged/in-flight (manual publish beat us here). Retry npm view
            # with longer backoff to let propagation settle, then treat as success.
            for i in 1 2 3 4 5; do
              sleep 15
              if npm view "@lightupai/polaris@${LOCAL}" version > /dev/null 2>&1; then
                echo "Version ${LOCAL} confirmed published — skipping (race condition, attempt $i)."
                exit 0
              fi
            done
            exit 1
          }
