#!/usr/bin/env bash
# ---------------------------------------------------------------------------
# new-site.sh — turn a fresh clone of the SeedProject base into a new site.
#
# Usage (from the repo root, after cloning):
#     ./scripts/new-site.sh
#
# Prompts for this site's identity, writes site.config.json, stamps it across
# every engine (Astro theme, agents, astroagent), optionally resets
# git history and installs dependencies.
# ---------------------------------------------------------------------------
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

echo "=================================================="
echo "  SeedProject — new site setup"
echo "=================================================="
echo "  Press Enter to accept each [default]."
echo

# Current values from site.config.json become the defaults.
get() { node -e "process.stdout.write(String((JSON.parse(require('fs').readFileSync('site.config.json','utf8'))$1) ?? ''))"; }
ask() { local var; read -r -p "$1 [$2]: " var || true; printf '%s' "${var:-$2}"; }

NAME="$(ask 'Site name'            "$(get .name)")"
URL="$(ask 'Site URL'             "$(get .url)")"
DESC="$(ask 'One-line description' "$(get .description)")"
TAG="$(ask 'Tagline'              "$(get .tagline)")"
TOPIC="$(ask 'Topic / niche'        "$(get .topic)")"
AUD="$(ask 'Audience'            "$(get .audience)")"
TZ="$(ask 'Timezone'            "$(get .timezone)")"
AUTHOR="$(ask 'Author name'         "$(get '.author.name')")"
TW="$(ask 'Twitter/X URL (optional)' "$(get '.social.twitter')")"

# Derive a URL-safe author slug from the name.
SLUG="$(printf '%s' "$AUTHOR" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g')"

echo
echo "Writing site.config.json ..."
NAME="$NAME" URL="$URL" DESC="$DESC" TAG="$TAG" TOPIC="$TOPIC" AUD="$AUD" TZ="$TZ" AUTHOR="$AUTHOR" SLUG="$SLUG" TW="$TW" \
node -e '
  const fs = require("fs");
  const c = JSON.parse(fs.readFileSync("site.config.json", "utf8"));
  const e = process.env;
  c.name = e.NAME; c.url = e.URL; c.description = e.DESC; c.tagline = e.TAG;
  c.topic = e.TOPIC; c.audience = e.AUD; c.timezone = e.TZ;
  c.author = { ...c.author, name: e.AUTHOR, slug: e.SLUG };
  c.social = { ...c.social, twitter: e.TW };
  fs.writeFileSync("site.config.json", JSON.stringify(c, null, 2) + "\n");
'

echo "Stamping identity across engines ..."
node scripts/configure.mjs

read -r -p "Reset git history for this new site? [y/N]: " RESETGIT || true
if [[ "${RESETGIT:-}" =~ ^[Yy]$ ]]; then
  rm -rf .git
  git init -q -b main
  git add -A
  git commit -q -m "chore: initialize ${NAME} from SeedProject base"
  echo "  fresh git history initialized."
fi

read -r -p "Install dependencies now (npm + composer)? [Y/n]: " DEPS || true
if [[ ! "${DEPS:-Y}" =~ ^[Nn]$ ]]; then
  echo "  npm install (app) ..."
  ( cd app && npm install --no-audit --no-fund )
  if command -v composer >/dev/null 2>&1; then
    echo "  composer install (api) ..."
    ( cd api && composer install --no-interaction ) || echo "  (composer install failed — run it manually in api/)"
  else
    echo "  composer not found — run 'composer install' in api/ manually."
  fi
fi

cat <<EOF

--------------------------------------------------
Done — "${NAME}" is configured.

Next steps:
  1. Build the site:     cd app && npm run build   (outputs to ./public)
  2. Serve it:           point your web server's document root at ./public,
                         and alias /api -> ./api for the PHP backend (see README.md).
  3. Backend (optional): the /api PHP backend needs api/config.php with DB
                         credentials. See README.md > "Backend (/api)".

Change identity anytime: edit site.config.json, then run
  node scripts/configure.mjs
--------------------------------------------------
EOF
