#!/usr/bin/env bash
# slides-builder/scripts/scaffold.sh
# Bootstrap a new presentation folder from a chosen template.
#
# Usage:
#   bash scaffold.sh <template> <folder-name>
#
# Args:
#   template     Template name (must match a folder under assets/templates/)
#                e.g., academic-scholarly | academic-minimal | business-pitch
#   folder-name  Target folder name under docs/slides/.
#                Convention: YYYY-MM-DD_<name>
#                e.g., 2026-06-03_advisor-progress
#
# What it does:
#   1. Validates template exists
#   2. Creates docs/slides/<folder-name>/
#   3. Copies template files (package.json, slides.md, style.css, README.md)
#   4. Generates dev.sh and build.sh helpers
#   5. Prints next-step commands

set -euo pipefail

# --- argument parsing -------------------------------------------------------
if [[ $# -lt 2 ]]; then
  echo "Usage: bash scaffold.sh <template> <folder-name>" >&2
  echo "Templates available:" >&2
  ls "$(dirname "$0")/../assets/templates/" 2>/dev/null | sed 's/^/  - /' >&2
  exit 1
fi

TEMPLATE="$1"
FOLDER="$2"

# --- resolve paths ----------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TEMPLATE_DIR="$SKILL_ROOT/assets/templates/$TEMPLATE"

# Find project root (where docs/ lives) - walk up from cwd
PROJECT_ROOT="$(pwd)"
while [[ "$PROJECT_ROOT" != "/" ]]; do
  if [[ -d "$PROJECT_ROOT/docs" ]]; then
    break
  fi
  PROJECT_ROOT="$(dirname "$PROJECT_ROOT")"
done

if [[ ! -d "$PROJECT_ROOT/docs" ]]; then
  echo "Error: could not find project root (no 'docs/' folder found walking up from $(pwd))" >&2
  exit 1
fi

TARGET_DIR="$PROJECT_ROOT/docs/slides/$FOLDER"

# --- validate ---------------------------------------------------------------
if [[ ! -d "$TEMPLATE_DIR" ]]; then
  echo "Error: template '$TEMPLATE' not found at $TEMPLATE_DIR" >&2
  echo "Available templates:" >&2
  ls "$SKILL_ROOT/assets/templates/" | sed 's/^/  - /' >&2
  exit 1
fi

if [[ -d "$TARGET_DIR" ]]; then
  echo "Error: target folder already exists: $TARGET_DIR" >&2
  echo "Either pick a different name or delete the existing folder first." >&2
  exit 1
fi

# --- validate folder name follows YYYY-MM-DD_<name> convention --------------
if [[ ! "$FOLDER" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}_[a-z0-9-]+$ ]]; then
  echo "Warning: folder name '$FOLDER' does not match YYYY-MM-DD_<kebab-name> convention." >&2
  echo "Recommended: e.g. 2026-06-03_advisor-progress" >&2
  echo "Proceeding anyway..." >&2
fi

# --- ensure docs/slides/.gitignore exists (one-time, shared by all decks) ---
SLIDES_DIR="$PROJECT_ROOT/docs/slides"
GITIGNORE="$SLIDES_DIR/.gitignore"
if [[ ! -f "$GITIGNORE" ]]; then
  mkdir -p "$SLIDES_DIR"
  cat > "$GITIGNORE" <<'GI_EOF'
# Per-deck build artifacts - auto-regenerated by pnpm install + bash build.sh
*/node_modules/
*/dist/
*/.slidev/
*/pnpm-lock.yaml.bak

# Keep slides.pptx + slides.pdf out of git? Uncomment if you don't want exports in history.
# */slides.pptx
# */slides.pdf

# Editor + OS
.DS_Store
*.swp
*~
GI_EOF
  echo "📝 Created shared .gitignore: $GITIGNORE"
fi

# --- create + copy ----------------------------------------------------------
mkdir -p "$TARGET_DIR"

cp "$TEMPLATE_DIR/package.json"        "$TARGET_DIR/package.json"
cp "$TEMPLATE_DIR/pnpm-workspace.yaml" "$TARGET_DIR/pnpm-workspace.yaml"
cp "$TEMPLATE_DIR/slides.md"           "$TARGET_DIR/slides.md"
cp "$TEMPLATE_DIR/style.css"           "$TARGET_DIR/style.css"
cp "$TEMPLATE_DIR/README.md"           "$TARGET_DIR/_template-README.md"

# global-bottom.vue (optional - only academic-scholarly currently ships one for
# the auto-rendered page-number + author·title footer)
if [[ -f "$TEMPLATE_DIR/global-bottom.vue" ]]; then
  cp "$TEMPLATE_DIR/global-bottom.vue" "$TARGET_DIR/global-bottom.vue"
fi

# --- generate dev.sh --------------------------------------------------------
cat > "$TARGET_DIR/dev.sh" <<'DEV_EOF'
#!/usr/bin/env bash
# Live preview at http://localhost:3030
set -e
cd "$(dirname "$0")"
if [[ ! -d node_modules ]]; then
  echo "📦 node_modules not found. Running pnpm install..."
  pnpm install
fi
pnpm run dev "$@"
DEV_EOF
chmod +x "$TARGET_DIR/dev.sh"

# --- generate build.sh ------------------------------------------------------
cat > "$TARGET_DIR/build.sh" <<'BUILD_EOF'
#!/usr/bin/env bash
# Export to slides.pptx + slides.pdf
set -e
cd "$(dirname "$0")"
if [[ ! -d node_modules ]]; then
  echo "📦 node_modules not found. Running pnpm install..."
  pnpm install
fi
echo "📊 Exporting PPTX..."
pnpm run export-pptx
echo "📄 Exporting PDF..."
pnpm run export-pdf
echo "✅ Done. Output: slides.pptx, slides.pdf"
BUILD_EOF
chmod +x "$TARGET_DIR/build.sh"

# --- generate README.md -----------------------------------------------------
cat > "$TARGET_DIR/README.md" <<README_EOF
# $FOLDER

Slide deck scaffolded from \`$TEMPLATE\` template by the slides-builder skill.

## Quick commands

\`\`\`bash
# First-time install (pnpm symlink cache - fast + small disk footprint)
pnpm install

# Live preview (hot reload)
bash dev.sh
# → opens http://localhost:3030

# Export pptx + pdf
bash build.sh
# → output: slides.pptx, slides.pdf
\`\`\`

## Files

- \`slides.md\` - main content (edit this)
- \`style.css\` - visual customization
- \`package.json\` - Slidev + deps
- \`_template-README.md\` - notes on the original template

## Template

\`$TEMPLATE\` - see \`_template-README.md\` for style notes.

## Editing

Open \`slides.md\` in your editor. Slides separated by \`---\` on its own line.
Live preview auto-reloads as you edit.

See [Slidev docs](https://sli.dev) for syntax.

## Disk note

Multiple decks share one pnpm content store (\`~/.local/share/pnpm/store/\`). Each
deck's \`node_modules/\` is a symlink tree - adding more decks costs ~MB, not GB.
The shared \`docs/slides/.gitignore\` keeps all \`node_modules/\` out of git.
README_EOF

# --- print summary ----------------------------------------------------------
cat <<SUMMARY
✅ Scaffold complete: $TARGET_DIR

Files created:
  - slides.md         (entry - edit this)
  - style.css         (visual customization)
  - package.json      (Slidev + deps)
  - pnpm-workspace.yaml (pre-approves native deps so pnpm install doesn't prompt)
  - global-bottom.vue (auto-rendered footer: page X/N + author·title - academic-scholarly only)
  - dev.sh            (live preview)
  - build.sh          (export pptx + pdf)
  - README.md         (this folder's guide)
  - _template-README.md  (notes from $TEMPLATE template)

Shared (created once at docs/slides/):
  - .gitignore        (ignores node_modules/, dist/, .slidev/ across all decks)

Next steps:
  cd $TARGET_DIR
  pnpm install           # one-time, ~30s (symlinked from shared store afterwards)
  bash dev.sh            # live preview at localhost:3030
SUMMARY
