# 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:
    inputs:
      rollback_commit:
        description: 'Commit SHA to deploy for a deliberate rollback; leave empty for the run commit'
        required: false
        default: ''
        type: string
      force_stale_deploy:
        description: "Allow a deliberate rollback to this run's old commit (may overwrite a newer deployment)"
        required: false
        default: false
        type: boolean

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

jobs:
  # Re-runs retain their original SHA. Refuse an old run before release or deployment.
  validate_deploy_commit:
    name: 🚦 Validate Deployment Commit
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event_name == 'workflow_dispatch' && inputs.rollback_commit || github.sha }}
      # Check the actual checkout again on job-only retries; earlier jobs may not rerun.
      - name: 🚦 Refuse stale deployment
        shell: bash
        env:
          DEPLOY_BRANCH: ${{ github.event_name == 'workflow_dispatch' && inputs.environment || github.ref_name }}
          DEPLOY_EVENT: ${{ github.event_name }}
          FORCE_STALE_DEPLOY: ${{ github.event_name == 'workflow_dispatch' && inputs.force_stale_deploy == true }}
        run: |
          set -euo pipefail
          DEPLOY_SHA=$(git rev-parse HEAD)
          TARGET_REF="refs/heads/$DEPLOY_BRANCH"
          if ! git check-ref-format "$TARGET_REF"; then
            echo "::error::Invalid deployment branch: $DEPLOY_BRANCH. Choose an existing branch."
            exit 1
          fi
          if ! REMOTE=$(git ls-remote --exit-code --heads origin "$TARGET_REF"); then
            echo "::error::Cannot read the current tip of $DEPLOY_BRANCH. Nothing will be deployed. Check repository access and the branch name, then retry."
            exit 1
          fi
          read -r TIP RESOLVED_REF <<< "$REMOTE"
          if [[ ! "$TIP" =~ ^[0-9a-f]{40}$ ]] || [ "$RESOLVED_REF" != "$TARGET_REF" ]; then
            echo "::error::Could not verify the current tip of $DEPLOY_BRANCH. Nothing will be deployed."
            exit 1
          fi
          if [ "$DEPLOY_SHA" = "$TIP" ]; then
            echo "✅ Deployment commit $DEPLOY_SHA is the current tip of $DEPLOY_BRANCH."
            exit 0
          fi
          if [ "$DEPLOY_EVENT" = "workflow_dispatch" ] && [ "$FORCE_STALE_DEPLOY" = "true" ]; then
            echo "::warning title=Deliberate stale deployment::Deploying non-tip commit $DEPLOY_SHA to $DEPLOY_BRANCH; the current branch tip is $TIP. force_stale_deploy was explicitly enabled."
            echo "### ⚠️ Deliberate rollback: deploying $DEPLOY_SHA to $DEPLOY_BRANCH instead of current tip $TIP." >> "${GITHUB_STEP_SUMMARY:-/dev/stdout}"
            exit 0
          fi
          echo "::error title=Stale deployment refused::This run would deploy $DEPLOY_SHA, but $DEPLOY_BRANCH is now at $TIP. This is probably a re-run of an old run and would roll the environment back. Re-run the latest deploy run for this branch, or start workflow_dispatch on the branch tip. For a deliberate rollback only, explicitly enable force_stale_deploy in a manual run."
          exit 1

  # ── Pre-deploy gates ──────────────────────────────────────────────────────
  # Resolves `pre-deploy:<branch>` from the `gates` block of .lisa.config.json
  # and runs whatever is declared there, BEFORE the deploy job.
  #
  # This is what makes a declaration like
  #
  #   "runtime-web-vulnerability": { "pre-deploy:main": "required" }
  #
  # mean something. A required gate that fails — or that resolves to no prover at
  # all, which is UNPROVABLE rather than passing — stops the workflow here, so
  # nothing is deployed. A gate job running BESIDE the deploy would go red after
  # the thing had already shipped, which is a report.
  pre_deploy_gates:
    needs: [validate_deploy_commit]
    name: 🚦 Pre-Deploy Gates
    uses: CodySwannGT/lisa/.github/workflows/gates.yml@main
    with:
      # Travels with the `uses:` line above — the two are one unit. Lisa's
      # reusable workflows are tracked at `@main`, so that file changes under
      # this repository with no pull request here. This is the contract major it
      # spoke when Lisa seeded this file; the run fails loudly if it has since
      # declared a break, and says NOT DETERMINED if this line goes missing
      # (CodySwannGT/lisa#3698).
      expected_workflow_contract_major: '1'
      moment: pre-deploy:${{ github.ref_name }}
      node_version: '24.21.0'
      package_manager: 'bun'
    # No `secrets:` key: gates.yml declares none in its `workflow_call`, so
    # passing any grants everything to a callee that reads nothing (#3065).

  deploy:
    name: Build, deploy, and verify
    needs: [pre_deploy_gates]
    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
        with:
          ref: ${{ inputs.force_stale_deploy == true && (inputs.rollback_commit || github.sha) || github.sha }}

      # Check the actual checkout again on job-only retries; earlier jobs may not rerun.
      - name: 🚦 Refuse stale deployment
        shell: bash
        env:
          DEPLOY_BRANCH: ${{ github.event_name == 'workflow_dispatch' && inputs.environment || github.ref_name }}
          DEPLOY_EVENT: ${{ github.event_name }}
          FORCE_STALE_DEPLOY: ${{ github.event_name == 'workflow_dispatch' && inputs.force_stale_deploy == true }}
        run: |
          set -euo pipefail
          DEPLOY_SHA=$(git rev-parse HEAD)
          TARGET_REF="refs/heads/$DEPLOY_BRANCH"
          if ! git check-ref-format "$TARGET_REF"; then
            echo "::error::Invalid deployment branch: $DEPLOY_BRANCH. Choose an existing branch."
            exit 1
          fi
          if ! REMOTE=$(git ls-remote --exit-code --heads origin "$TARGET_REF"); then
            echo "::error::Cannot read the current tip of $DEPLOY_BRANCH. Nothing will be deployed. Check repository access and the branch name, then retry."
            exit 1
          fi
          read -r TIP RESOLVED_REF <<< "$REMOTE"
          if [[ ! "$TIP" =~ ^[0-9a-f]{40}$ ]] || [ "$RESOLVED_REF" != "$TARGET_REF" ]; then
            echo "::error::Could not verify the current tip of $DEPLOY_BRANCH. Nothing will be deployed."
            exit 1
          fi
          if [ "$DEPLOY_SHA" = "$TIP" ]; then
            echo "✅ Deployment commit $DEPLOY_SHA is the current tip of $DEPLOY_BRANCH."
            exit 0
          fi
          if [ "$DEPLOY_EVENT" = "workflow_dispatch" ] && [ "$FORCE_STALE_DEPLOY" = "true" ]; then
            echo "::warning title=Deliberate stale deployment::Deploying non-tip commit $DEPLOY_SHA to $DEPLOY_BRANCH; the current branch tip is $TIP. force_stale_deploy was explicitly enabled."
            echo "### ⚠️ Deliberate rollback: deploying $DEPLOY_SHA to $DEPLOY_BRANCH instead of current tip $TIP." >> "${GITHUB_STEP_SUMMARY:-/dev/stdout}"
            exit 0
          fi
          echo "::error title=Stale deployment refused::This run would deploy $DEPLOY_SHA, but $DEPLOY_BRANCH is now at $TIP. This is probably a re-run of an old run and would roll the environment back. Re-run the latest deploy run for this branch, or start workflow_dispatch on the branch tip. For a deliberate rollback only, explicitly enable force_stale_deploy in a manual run."
          exit 1

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

      - name: Setup Bun
        uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
        with:
          bun-version: '1.4.4'

      - 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

  # ── Post-deploy gates ─────────────────────────────────────────────────────
  # Proves a property of what is now live. A red here does not un-ship the
  # deploy; it names the gate that does not hold so an operator can act on it,
  # which is the difference between a post-deploy gate and a post-deploy log.
  post_deploy_gates:
    name: 🚦 Post-Deploy Gates
    uses: CodySwannGT/lisa/.github/workflows/gates.yml@main
    needs: [deploy]
    if: ${{ always() && !cancelled() && needs.deploy.result == 'success' }}
    with:
      # Travels with the `uses:` line above — the two are one unit. Lisa's
      # reusable workflows are tracked at `@main`, so that file changes under
      # this repository with no pull request here. This is the contract major it
      # spoke when Lisa seeded this file; the run fails loudly if it has since
      # declared a break, and says NOT DETERMINED if this line goes missing
      # (CodySwannGT/lisa#3698).
      expected_workflow_contract_major: '1'
      moment: post-deploy:${{ github.ref_name }}
      node_version: '24.21.0'
      package_manager: 'bun'
    # No `secrets:` key: gates.yml declares none in its `workflow_call`, so
    # passing any grants everything to a callee that reads nothing (#3065).
