#!/usr/bin/env bash
# TextASite -> Cloudflare Pages deploy helper.
#
# Usage: deploy_site.sh <project-name> <build-dir>
#   project-name: lowercase-dashes (becomes https://<project-name>.pages.dev)
#   build-dir:    folder of static files to publish (e.g. dist/ or the site root)
#
# Self-contained: needs only node/npx + network. Wrangler is pulled via npx (no PATH
# install needed). Creds are resolved in this order:
#   1. CLOUDFLARE_ACCOUNT_ID / CLOUDFLARE_API_TOKEN already in the env
#   2. /app/data/cloudflare.json  {"account_id":..., "api_token":...}
#   3. /app/data/credentials.json  (service == "Cloudflare", value is JSON with both)
set -euo pipefail

PROJECT="${1:?usage: deploy_site.sh <project-name> <build-dir>}"
DIR="${2:?usage: deploy_site.sh <project-name> <build-dir>}"
[ -d "$DIR" ] || { echo "build dir not found: $DIR" >&2; exit 1; }

if [ -z "${CLOUDFLARE_ACCOUNT_ID:-}" ] || [ -z "${CLOUDFLARE_API_TOKEN:-}" ]; then
  eval "$(python3 - <<'PY'
import json, os, shlex
acct = tok = None
try:
    d = json.load(open('/app/data/cloudflare.json'))
    acct, tok = d.get('account_id'), d.get('api_token')
except Exception:
    pass
if not (acct and tok):
    try:
        for e in json.load(open('/app/data/credentials.json')):
            if str(e.get('service','')).lower() == 'cloudflare':
                v = e.get('value')
                v = json.loads(v) if isinstance(v, str) else (v or {})
                acct, tok = v.get('account_id'), v.get('api_token')
                if acct and tok:
                    break
    except Exception:
        pass
if not (acct and tok):
    raise SystemExit("echo 'no cloudflare creds found (env, /app/data/cloudflare.json, /app/data/credentials.json)' >&2; exit 1")
print(f"export CLOUDFLARE_ACCOUNT_ID={shlex.quote(acct)}")
print(f"export CLOUDFLARE_API_TOKEN={shlex.quote(tok)}")
PY
)"
fi

WRANGLER="npx --yes wrangler@latest"

# create the pages project on first deploy.
# --force is required: new Pages is merged into Workers, and without it you get a
# workers.dev subdomain prompt instead of a classic *.pages.dev url.
if ! $WRANGLER pages project list 2>/dev/null | grep -q "\b$PROJECT\b"; then
  echo "creating pages project: $PROJECT"
  $WRANGLER pages project create "$PROJECT" --production-branch main --force
fi

echo "deploying $DIR -> $PROJECT"
$WRANGLER pages deploy "$DIR" --project-name "$PROJECT" --branch main --commit-dirty=true

echo "live at: https://$PROJECT.pages.dev"
