#!/usr/bin/env bash
#
# bun run publish [--deploy] "commit message"
#
# Local "dev machine is the CI" pipeline:
#   1. sequoia publish  → mints AT URI, cross-posts to Bluesky, mutates frontmatter + .sequoia-state.json
#   2. git stage + commit (scoped to publish artifacts)
#   3. (--deploy only) vercel build --prod → produces .vercel/output
#   4. (--deploy only) vercel deploy --prebuilt --prod → uploads prebuilt artifacts
#   5. revalidate so the new post is live (flushes Next.js data cache; blog reads PDS at request time)
#   6. git push  → keeps git in sync with deployed state
#
# By default, the Vercel build/deploy is skipped — the blog fetches posts from
# PDS at request time, so new content only needs the revalidate. Pass --deploy
# when you've also changed code that needs to ship.
set -euo pipefail

DEPLOY=false
ARGS=()
for arg in "$@"; do
  case "$arg" in
    --deploy) DEPLOY=true ;;
    *) ARGS+=("$arg") ;;
  esac
done

if [ "${#ARGS[@]}" -lt 1 ] || [ -z "${ARGS[0]}" ]; then
  echo "Usage: bun run publish [--deploy] \"commit message\"" >&2
  exit 1
fi

COMMIT_MSG="${ARGS[0]}"

# Pre-flight: nothing already staged (we manage staging ourselves)
if ! git diff --staged --quiet; then
  echo "Error: you have staged changes. Unstage or commit them separately first." >&2
  git diff --staged --name-only >&2
  exit 1
fi

# 1. Publish to PDS + Bluesky
bun run sequoia:publish

# 2. Stage only the artifacts sequoia produces
git add src/content/blog/ .sequoia-state.json

# 3. Commit (skip if sequoia made no changes — e.g., re-run on unchanged content)
if git diff --staged --quiet; then
  echo "No publish changes to commit. Continuing to build."
else
  git commit -m "$COMMIT_MSG"
fi

# 4. (--deploy only) Build with Vercel's toolchain → .vercel/output
# 5. (--deploy only) Upload prebuilt artifacts
if $DEPLOY; then
  bunx vercel build --prod
  bunx vercel deploy --prebuilt --prod
fi

# 6. Bust the Next.js data cache so the new post is live without waiting 7 days
if [ -n "${REVALIDATE_SECRET:-}" ]; then
  curl -sf -X POST "https://www.smart-knowledge-systems.com/api/revalidate" \
    -H "x-revalidate-secret: $REVALIDATE_SECRET" || \
    echo "Warning: revalidation request failed (continuing)"
fi

# 7. Push so origin/main matches deployed state
git push
