# Seeded by Lisa on first setup — this file is YOURS.
# Lisa will not overwrite it. (copy-overwrite assets ARE replaced each run.)

# This file is create-only from Lisa.
# Customize it for your Harper Fabric target; Lisa will not overwrite it.

name: Deploy Harper Fabric

on:
  push:
    branches:
      - main
  workflow_dispatch:

concurrency:
  group: harper-fabric-deploy-${{ github.ref }}
  cancel-in-progress: true

jobs:
  deploy:
    name: Build, deploy, and verify
    runs-on: ubuntu-latest
    timeout-minutes: 30
    env:
      HARPER_PROJECT: ${{ vars.HARPER_PROJECT || github.event.repository.name }}
      HARPER_PACKAGE: ${{ vars.HARPER_PACKAGE || 'harper-app' }}
      CLI_TARGET: ${{ secrets.CLI_TARGET || secrets.HARPER_FABRIC_TARGET }}
      CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}
      CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '22.21.1'
          package-manager-cache: false

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: '1.3.8'

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Build Harper component
        run: bun run build

      - name: Verify Fabric secrets
        run: |
          test -n "${CLI_TARGET}" || { echo "Missing CLI_TARGET or HARPER_FABRIC_TARGET secret"; exit 1; }
          test -n "${CLI_TARGET_USERNAME}" || { echo "Missing CLI_TARGET_USERNAME secret"; exit 1; }
          test -n "${CLI_TARGET_PASSWORD}" || { echo "Missing CLI_TARGET_PASSWORD secret"; exit 1; }

      - name: Deploy component to Harper Fabric
        run: |
          if command -v harper >/dev/null 2>&1; then
            HARPER_BIN="harper"
          elif [ -x node_modules/.bin/harper ]; then
            HARPER_BIN="node_modules/.bin/harper"
          elif [ -x node_modules/.bin/harperdb ]; then
            HARPER_BIN="node_modules/.bin/harperdb"
          else
            echo "Missing Harper CLI. Add harper/harperdb to devDependencies or install it before deploy."
            exit 1
          fi

          "$HARPER_BIN" deploy_component \
            project="${HARPER_PROJECT}" \
            package="${HARPER_PACKAGE}" \
            target="${CLI_TARGET}" \
            username="${CLI_TARGET_USERNAME}" \
            password="${CLI_TARGET_PASSWORD}" \
            restart=true \
            replicated=true

      - name: Smoke verify deployed component
        run: |
          if bun run | grep -qE '^[[:space:]]*verify[[:space:]]'; then
            bun run verify
          else
            echo "No verify script defined; add one to smoke-test the deployed Harper endpoint."
          fi
