#!/usr/bin/env bash
# memeroot-claude-code-setup.sh
#
# One-shot setup for using Memeroot inside Claude Code:
#   - extracts the two production skill packs into ~/.claude/skills/
#   - installs memeroot-cli globally so Claude Code can invoke it via bash
#   - creates a working directory at ~/memeroot-work/ with CLAUDE.md, tools/, outputs/
#
# Usage:
#   ./memeroot-claude-code-setup.sh [path/to/memeroot-delivery.zip]
#
# If no path provided, looks for memeroot-delivery.zip in the current directory.
# Re-running is safe — it overwrites the skills and refreshes the working directory's
# tools/ folder, but does NOT touch outputs/, packets/, or snapshots/.

set -euo pipefail

# ───── colors ─────
if [ -t 1 ]; then
  R=$'\033[31m' G=$'\033[32m' Y=$'\033[33m' B=$'\033[2m' N=$'\033[0m'
else
  R='' G='' Y='' B='' N=''
fi
say() { echo "$G$1$N $2"; }
warn() { echo "$Y!$N $1"; }
die() { echo "$R✗$N $1" >&2; exit 1; }

# ───── prerequisites ─────
echo ""
echo "Memeroot · Claude Code setup"
echo "────────────────────────────"
echo ""

command -v node >/dev/null || die "Node.js 18+ required. Install from https://nodejs.org"
NODE_MAJOR=$(node -v | sed 's/v\([0-9]*\).*/\1/')
[ "$NODE_MAJOR" -ge 18 ] || die "Node.js 18+ required (have $(node -v))"
say "✓" "Node.js $(node -v)"

command -v npm >/dev/null || die "npm required (usually bundled with Node.js)"
say "✓" "npm $(npm -v)"

command -v unzip >/dev/null || die "unzip required. On macOS: brew install unzip · On Debian/Ubuntu: apt install unzip"
say "✓" "unzip available"

if command -v claude >/dev/null 2>&1; then
  say "✓" "Claude Code $(claude --version 2>/dev/null || echo 'installed')"
else
  warn "Claude Code (\`claude\` command) not found in PATH"
  warn "  Install with: npm install -g @anthropic-ai/claude-code"
  warn "  Or follow https://docs.claude.com/en/docs/claude-code/overview"
  warn "  Continuing — skills + CLI will still install, just won't be wired up to Claude Code until you install it."
fi

echo ""

# ───── locate delivery zip ─────
DELIVERY_ZIP="${1:-./memeroot-delivery.zip}"
if [ ! -f "$DELIVERY_ZIP" ]; then
  die "memeroot-delivery.zip not found at: $DELIVERY_ZIP

Pass the path as the first argument:
  $0 ~/Downloads/memeroot-delivery.zip"
fi
say "✓" "Found delivery: $DELIVERY_ZIP ($(du -h "$DELIVERY_ZIP" | cut -f1))"

# ───── extract delivery to temp ─────
TMP=$(mktemp -d -t memeroot-setup.XXXXXX)
trap 'rm -rf "$TMP"' EXIT
unzip -q "$DELIVERY_ZIP" -d "$TMP"
DELIVERY="$TMP/memeroot-delivery"
[ -d "$DELIVERY" ] || die "Unexpected zip structure — couldn't find memeroot-delivery/ inside the zip"
say "✓" "Extracted to $TMP"

echo ""

# ───── install skill packs ─────
SKILLS_DIR="$HOME/.claude/skills"
mkdir -p "$SKILLS_DIR"

for pack in regulated-document-author memeroot-bridge; do
  ZIP="$DELIVERY/${pack}.zip"
  [ -f "$ZIP" ] || { warn "${pack}.zip not in delivery — skipping"; continue; }
  rm -rf "$SKILLS_DIR/$pack"
  unzip -oq "$ZIP" -d "$SKILLS_DIR/"
  if [ -f "$SKILLS_DIR/$pack/SKILL.md" ]; then
    LINES=$(wc -l < "$SKILLS_DIR/$pack/SKILL.md")
    say "✓" "Installed skill: $pack ($LINES-line SKILL.md, $(ls "$SKILLS_DIR/$pack/templates" 2>/dev/null | wc -l | tr -d ' ') templates)"
  else
    warn "  $pack installed but SKILL.md not found at expected path"
  fi
done

echo ""

# ───── install memeroot-cli globally ─────
CLI_ZIP="$DELIVERY/memeroot-cli.zip"
if [ -f "$CLI_ZIP" ]; then
  CLI_TMP="$TMP/cli-install"
  unzip -oq "$CLI_ZIP" -d "$CLI_TMP"
  cd "$CLI_TMP/memeroot-cli"
  if npm install -g . >/dev/null 2>&1; then
    say "✓" "memeroot-cli installed globally — $(which memeroot 2>/dev/null || echo '(in npm prefix)')"
  else
    warn "  npm install -g failed without sudo; trying with sudo..."
    if sudo npm install -g . >/dev/null 2>&1; then
      say "✓" "memeroot-cli installed globally (sudo) — $(which memeroot 2>/dev/null)"
    else
      warn "  Couldn't install globally. You can run it directly: node $CLI_TMP/memeroot-cli/bin/memeroot ..."
      warn "  Or set up an npm prefix in your home: npm config set prefix ~/.local && npm install -g ."
    fi
  fi
  cd - >/dev/null
else
  warn "memeroot-cli.zip not in delivery — skipping CLI install"
fi

echo ""

# ───── set up working directory ─────
WORK="${MEMEROOT_WORK:-$HOME/memeroot-work}"
mkdir -p "$WORK/tools" "$WORK/outputs" "$WORK/packets" "$WORK/snapshots" "$WORK/identities"

# Copy tools (overwrite — these get updated with new deliveries)
for f in MR-CANVAS-v0.8.html iframe-region-builder.html memeroot-bridge-bundle.html regulated-document-author-bundle.html memeroot-cli-showcase.html memeroot-catalog.html; do
  if [ -f "$DELIVERY/$f" ]; then
    cp "$DELIVERY/$f" "$WORK/tools/"
  fi
done
say "✓" "Working directory: $WORK"
say " " "  ├── tools/         canvas, builders, bundles, catalog"
say " " "  ├── packets/       audit packets you produce"
say " " "  ├── snapshots/     captured-hash HTML evidence"
say " " "  ├── identities/    keys for signing (you create these in the canvas)"
say " " "  └── outputs/       general work outputs"

# Write CLAUDE.md only if it doesn't exist — don't clobber user edits
if [ -f "$WORK/CLAUDE.md" ]; then
  warn "  $WORK/CLAUDE.md already exists — not overwriting"
  warn "  Compare with the template if you want: $WORK/tools/CLAUDE.md.template"
  cp "$DELIVERY/memeroot-claude-code-CLAUDE.md" "$WORK/tools/CLAUDE.md.template" 2>/dev/null || true
else
  # Write the template (in this script as a heredoc would balloon size; we copy from the delivery if present, otherwise write a minimal one)
  if [ -f "$DELIVERY/memeroot-claude-code-CLAUDE.md" ]; then
    cp "$DELIVERY/memeroot-claude-code-CLAUDE.md" "$WORK/CLAUDE.md"
    say "✓" "Wrote $WORK/CLAUDE.md"
  else
    cat > "$WORK/CLAUDE.md" << 'MINIMAL_CLAUDE_MD'
# Memeroot working directory

Two skills are available: `regulated-document-author` (SOX/FDA/IRB/audit) and `memeroot-bridge` (XML region structure).

Default workflow when producing regulated content as Memeroot output:
1. Produce region XML files in `packets/<scope>/`
2. Validate: `memeroot validate packets/<scope>/*.xml`
3. Package: `memeroot package packets/<scope>/*.xml -o packets/<scope>/audit-packet.html`
4. Open audit-packet.html in browser, sign in canvas, export bundle.

Tools available in `tools/`: MR-CANVAS-v0.8.html, iframe-region-builder.html, *-bundle.html viewers.

Communication: terse, ship the deliverable, don't narrate.
MINIMAL_CLAUDE_MD
    say "✓" "Wrote $WORK/CLAUDE.md (minimal — full template not in delivery)"
  fi
fi

echo ""
echo "────────────────────────────"
say "✓" "Setup complete."
echo ""
echo "Next steps:"
echo "  cd $WORK"
echo "  claude              ${B}# start Claude Code with skills + CLI + canvas tooling all wired up${N}"
echo ""
echo "Try saying:"
echo "  \"Document the REV-002 expense approval control for SOX 404 as a Memeroot packet.\""
echo ""
