#!/bin/bash
# Full local pipeline: uninstall → build → install → verify.
# Usage: bash scripts/local-install.sh [--skip-tests] [--no-cleanup]
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'

# --- Parse flags ---
SKIP_TESTS=false
NO_CLEANUP=false
for arg in "$@"; do
  case "$arg" in
    --skip-tests) SKIP_TESTS=true ;;
    --no-cleanup) NO_CLEANUP=true ;;
    *)
      echo -e "${RED}Unknown flag: $arg${NC}"
      echo "Usage: bash scripts/local-install.sh [--skip-tests] [--no-cleanup]"
      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 Local Install Pipeline ===${NC}"
echo ""

# --- Phase 1: Uninstall ---
bash "$SCRIPT_DIR/uninstall-package.sh"
echo ""

# --- Phase 2: Build ---
BUILD_FLAGS=()
[ "$SKIP_TESTS" = true ] && BUILD_FLAGS+=(--skip-tests)
bash "$SCRIPT_DIR/build-package.sh" "${BUILD_FLAGS[@]+"${BUILD_FLAGS[@]}"}"
echo ""

# --- Phase 3: Install ---
bash "$SCRIPT_DIR/install-package.sh"
echo ""

# --- Phase 4: Verify ---
bash "$SCRIPT_DIR/verify-package.sh"

# --- Cleanup tarball ---
TARBALL=$(find "$REPO_ROOT" -maxdepth 1 -name 'evolvconsulting-evolv-coder-kit-*.tgz' 2>/dev/null | head -1 || true)
if [ -n "$TARBALL" ]; then
  if [ "$NO_CLEANUP" = true ]; then
    echo ""
    echo -e "${YELLOW}Tarball kept (--no-cleanup): ${TARBALL}${NC}"
  else
    rm -f "$TARBALL"
  fi
fi

echo ""
echo -e "${GREEN}=== Pipeline complete ===${NC}"
