#!/usr/bin/env bash
set -e

# CF Workers Builds injects: CI=true, WORKERS_CI=1, WORKERS_CI_BUILD_UUID,
# WORKERS_CI_COMMIT_SHA, WORKERS_CI_BRANCH, CLOUDFLARE_ACCOUNT_ID.
# Our trigger env vars add: ENV_NAME, BUILD_CUSTOMER, DNS_ZONE_NAME,
# LEED_API_TOKEN (secret).

# Ensure bun global bin is on PATH for the entire script.
export PATH="$HOME/.bun/bin:$PATH"

# ── Validate required environment variables ──────────────────────────────────
missing=()
[ -z "${ENV_NAME:-}" ] && missing+=("ENV_NAME")
[ -z "${LEED_API_TOKEN:-}" ] && missing+=("LEED_API_TOKEN")

if [ ${#missing[@]} -gt 0 ]; then
  echo "ERROR: Required environment variables are not set:"
  for var in "${missing[@]}"; do
    echo "  - $var"
  done
  exit 1
fi

# ── Environment info ─────────────────────────────────────────────────────────
echo "Bun: $(bun --version) | Node: $(node --version)"
echo "Branch: ${WORKERS_CI_BRANCH:-unknown} | Commit: ${WORKERS_CI_COMMIT_SHA:-unknown}"
echo "Build UUID: ${WORKERS_CI_BUILD_UUID:-unknown}"
# Entitlements baked into this build (#309 G3). The site builder trusts ONLY
# this trigger env var in CI and fails closed when it is missing.
echo "LEED_ENTITLEMENTS: ${LEED_ENTITLEMENTS:-<unset>}"

# ── Install the Leed CLI ─────────────────────────────────────────────────────
# From public npm in every environment, with no registry config and no token.
# Production installs the @release dist-tag; every other environment installs
# @staging, the build awaiting release.
if [ "$ENV_NAME" = "production" ]; then
  TAG="release"
else
  TAG="staging"
fi

echo "Installing @leed-ai/cli@$TAG and wrangler"
bun install -g @leed-ai/cli@$TAG wrangler

# ── Font Awesome ─────────────────────────────────────────────────────────────
# The build downloads no fonts (#458). A repo with no Font Awesome committed
# gets Free here, for this build only; a repo whose src/static/webfonts holds
# fa-*.woff2 or fa-version.txt (its own Pro, or Free) is left untouched. A
# failed download stops the build, so the live site keeps its icons rather
# than being replaced by one without them.
leed site init --font-awesome

# ── Build the site ───────────────────────────────────────────────────────────
leed site build

# ── Upload: push worker version and notify CMS ──────────────────────────────
leed site upload
