#!/bin/bash
# Build the package: hooks, tests, pack tarball.
# Outputs: evolvconsulting-evolv-coder-kit-*.tgz in repo root.
# Run uninstall-package.sh first to remove the previous install.
# Usage: bash scripts/build-package.sh [--skip-tests]
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'
YELLOW='\033[1;33m'
NC='\033[0m'

SKIP_TESTS=false
for arg in "$@"; do
  case "$arg" in
    --skip-tests) SKIP_TESTS=true ;;
    *)
      echo -e "${RED}Unknown flag: $arg${NC}"
      echo "Usage: bash scripts/build-package.sh [--skip-tests]"
      exit 1
      ;;
  esac
done

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"

echo -e "${CYAN}=== evolv-coder-kit Build ===${NC}"
echo ""

# --- Step 1: Build hooks ---
echo -e "${CYAN}Step 1: Building hooks...${NC}"
if npm run build:hooks; then
  echo -e "    ${GREEN}PASS${NC}"
else
  echo -e "    ${RED}FAIL — aborting.${NC}"
  exit 1
fi

# --- Step 1b: Verify catalog checksums ---
echo -e "${CYAN}Step 1b: Verifying catalog checksums...${NC}"
if node scripts/build-catalog-checksums.js --verify; then
  echo -e "    ${GREEN}PASS${NC}"
else
  echo -e "    ${RED}FAIL — catalog checksums are stale. Run: npm run build:catalog${NC}"
  exit 1
fi

# --- Step 2: Quality gates ---
if [ "$SKIP_TESTS" = true ]; then
  echo -e "${YELLOW}Step 2: Quality gates — SKIPPED (--skip-tests)${NC}"
else
  echo -e "${CYAN}Step 2: Quality gates...${NC}"
  if node --check bin/install.js && npm test; then
    echo -e "    ${GREEN}PASS${NC}"
  else
    echo -e "    ${RED}FAIL — aborting.${NC}"
    exit 1
  fi
fi

# --- Step 3: Pack ---
echo -e "${CYAN}Step 3: Packing tarball...${NC}"
rm -f evolvconsulting-evolv-coder-kit-*.tgz
npm pack --quiet
TARBALL=$(find . -maxdepth 1 -name 'evolvconsulting-evolv-coder-kit-*.tgz' 2>/dev/null | head -1)
if [ -z "$TARBALL" ]; then
  echo -e "    ${RED}FAIL: npm pack produced no tarball — aborting.${NC}"
  exit 1
fi
echo -e "    Tarball: ${TARBALL}"
echo -e "    ${GREEN}PASS${NC}"

# --- Step 3b: Verify tarball contents ---
echo -e "${CYAN}Step 3b: Verifying tarball contents...${NC}"
if node scripts/verify-tarball.js; then
  echo -e "    ${GREEN}PASS${NC}"
else
  echo -e "    ${RED}FAIL — tarball contents invalid. Check verify-tarball.js output.${NC}"
  exit 1
fi

echo ""
echo -e "${GREEN}Build complete.${NC} Run: bash scripts/install-package.sh (or bash scripts/local-install.sh for full pipeline)"
