#!/bin/bash
# Install the built tarball globally and deploy to ~/.claude/.
# Run build-package.sh first.
# Usage: bash scripts/install-package.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'

if [ ! -f "$REPO_ROOT/package.json" ]; then
  echo -e "${RED}ERROR: package.json not found. Run from the repo root.${NC}"
  exit 1
fi

cd "$REPO_ROOT"

TARBALL=$(find . -maxdepth 1 -name 'evolvconsulting-evolv-coder-kit-*.tgz' 2>/dev/null | head -1)
if [ -z "$TARBALL" ]; then
  echo -e "${RED}ERROR: No tarball found. Run build-package.sh first.${NC}"
  exit 1
fi

echo -e "${CYAN}=== evolv-coder-kit Install ===${NC}"
echo -e "    Tarball: ${TARBALL}"
echo ""

# --- Step 1: Install globally from tarball ---
echo -e "${CYAN}Step 1: Installing globally from tarball...${NC}"
if npm install -g "./$TARBALL" --force; then
  echo -e "    ${GREEN}PASS${NC}"
else
  echo -e "    ${RED}FAIL — aborting.${NC}"
  exit 1
fi

# --- Step 2: Deploy to ~/.claude/ ---
echo -e "${CYAN}Step 2: Deploying to ~/.claude/ ...${NC}"
if evolv-coder-kit; then
  echo -e "    ${GREEN}PASS${NC}"
else
  echo -e "    ${RED}FAIL${NC}"
  exit 1
fi

echo ""
echo -e "${GREEN}Install complete.${NC} Run: bash scripts/verify-package.sh"
