#!/bin/bash
# Verify the installed package against the expected version.
# Usage: bash scripts/verify-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'
YELLOW='\033[1;33m'
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"

PASS=0
FAIL=0

check_pass() { ((PASS++)); echo -e "${GREEN}OK${NC}"; }
check_fail() { ((FAIL++)); echo -e "${RED}FAIL${NC}"; }

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

EXPECTED_VERSION=$(node -p "require('./package.json').version")

# --- version ---
echo -n "    --version ... "
ACTUAL_VERSION=$(evolv-coder-kit --version 2>&1 || true)
if [ "$ACTUAL_VERSION" = "$EXPECTED_VERSION" ]; then
  echo -e "${GREEN}OK${NC} ($ACTUAL_VERSION)"
  ((PASS++))
else
  echo -e "${RED}MISMATCH${NC} (expected $EXPECTED_VERSION, got $ACTUAL_VERSION)"
  ((FAIL++))
fi

# --- help ---
echo -n "    --help ... "
if evolv-coder-kit --help >/dev/null 2>&1; then
  check_pass
else
  check_fail
fi

# --- doctor ---
echo -n "    --doctor ... "
if evolv-coder-kit --doctor >/dev/null 2>&1; then
  check_pass
else
  check_fail
fi

# --- verify / drift ---
echo -n "    --verify ... "
VERIFY_OUT=$(evolv-coder-kit --verify 2>&1 || true)
if echo "$VERIFY_OUT" | grep -q "clean"; then
  echo -e "${GREEN}OK${NC} (clean)"
  ((PASS++))
else
  echo -e "${YELLOW}DRIFT${NC} (not a failure — template customizations expected)"
  ((PASS++))
fi

# --- status ---
echo -n "    --status ... "
if evolv-coder-kit --status >/dev/null 2>&1; then
  check_pass
else
  check_fail
fi

echo ""
TOTAL=$((PASS + FAIL))
if [ "$FAIL" -eq 0 ]; then
  echo -e "${GREEN}=== ALL $TOTAL CHECKS PASSED ===${NC}"
  exit 0
else
  echo -e "${RED}=== $FAIL/$TOTAL CHECKS FAILED ===${NC}"
  exit 1
fi
