#!/usr/bin/env bash
set -euo pipefail

BIGSTACK_DIR="$(cd "$(dirname "$0")" && pwd)"
SKILLS_DIR="$HOME/.claude/skills"
VERSION=$(cat "$BIGSTACK_DIR/VERSION")

# Clean up old nested installation layout (skills were inside bigstack/)
OLD_NESTED="$SKILLS_DIR/bigstack"
if [ -d "$OLD_NESTED/bigstack-review" ]; then
  echo "Cleaning up old nested installation..."
  for old_skill_dir in "$OLD_NESTED"/bigstack-*/; do
    [ -d "$old_skill_dir" ] && rm -rf "$old_skill_dir"
  done
fi

echo "bigstack v$VERSION — setup"
echo "=========================="
echo ""

# Step 1: Check Node.js
if ! command -v node &>/dev/null; then
  echo "ERROR: Node.js is required but not found."
  echo "Install via https://nodejs.org or volta: volta install node"
  exit 1
fi
echo "Node.js: $(node --version)"

# Step 2: Install dependencies
if [ ! -d "$BIGSTACK_DIR/node_modules" ]; then
  echo ""
  echo "Installing dependencies..."
  cd "$BIGSTACK_DIR"
  npm install
fi

# Step 3: Generate skill docs
echo ""
echo "Generating skill docs..."
cd "$BIGSTACK_DIR"
npm run gen:skill-docs

# Step 4: Install skills
echo ""
echo "Installing skills to $SKILLS_DIR..."
mkdir -p "$SKILLS_DIR/bigstack"

# Copy root skill
cp "$BIGSTACK_DIR/SKILL.md" "$SKILLS_DIR/bigstack/SKILL.md"
echo "  [installed] SKILL.md (root router)"

# Copy VERSION for staleness detection
cp "$BIGSTACK_DIR/VERSION" "$SKILLS_DIR/bigstack/VERSION"

# Find and copy all skill directories
SKILL_COUNT=0
for tmpl in "$BIGSTACK_DIR"/*/SKILL.md.tmpl; do
  [ -f "$tmpl" ] || continue
  skill_dir=$(dirname "$tmpl")
  skill_name=$(basename "$skill_dir")
  skill_md="$skill_dir/SKILL.md"

  if [ ! -f "$skill_md" ]; then
    echo "  [SKIP] $skill_name — SKILL.md not found (generation may have failed)"
    continue
  fi

  # Create skill directory and copy SKILL.md
  mkdir -p "$SKILLS_DIR/$skill_name"
  cp "$skill_md" "$SKILLS_DIR/$skill_name/SKILL.md"

  # Copy auxiliary files (bin/, etc.)
  if [ -d "$skill_dir/bin" ]; then
    mkdir -p "$SKILLS_DIR/$skill_name/bin"
    cp -r "$skill_dir/bin/"* "$SKILLS_DIR/$skill_name/bin/"
    chmod +x "$SKILLS_DIR/$skill_name/bin/"* 2>/dev/null || true
  fi

  echo "  [installed] $skill_name"
  SKILL_COUNT=$((SKILL_COUNT + 1))
done

echo ""
echo "=========================="
echo "Done! Installed $SKILL_COUNT skills to $SKILLS_DIR"
echo ""
echo "Start a new Claude Code session to use bigstack skills."
echo "Try: /bigstack, /bigstack-review, /bigstack-ship, /bigstack-qa, etc."
