#!/bin/bash
# Verification script for IoTeX Node.js SDK installation

set -e

echo "🔍 IoTeX Node.js SDK - Installation Verification"
echo "=================================================="
echo ""

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check Node.js version
echo "1️⃣  Checking Node.js version..."
NODE_VERSION=$(node --version)
echo "   Node.js: $NODE_VERSION"
if [[ "$NODE_VERSION" < "v18" ]]; then
    echo -e "   ${RED}❌ Node.js 18+ required${NC}"
    exit 1
else
    echo -e "   ${GREEN}✅ Node.js version OK${NC}"
fi
echo ""

# Install dependencies
echo "2️⃣  Installing dependencies..."
npm install --silent
echo -e "   ${GREEN}✅ Dependencies installed${NC}"
echo ""

# Build project
echo "3️⃣  Building project..."
npm run build > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "   ${GREEN}✅ Build successful${NC}"
else
    echo -e "   ${RED}❌ Build failed${NC}"
    exit 1
fi
echo ""

# Check dist directory
echo "4️⃣  Checking build output..."
if [ -d "dist" ]; then
    FILE_COUNT=$(find dist -name "*.js" | wc -l)
    echo "   Generated $FILE_COUNT JavaScript files"
    echo -e "   ${GREEN}✅ Build output OK${NC}"
else
    echo -e "   ${RED}❌ dist directory not found${NC}"
    exit 1
fi
echo ""

# Run unit tests
echo "5️⃣  Running unit tests..."
npm test -- --testPathIgnorePatterns=integration.test.ts > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "   ${GREEN}✅ All tests passed${NC}"
else
    echo -e "   ${YELLOW}⚠️  Some tests failed (this is OK for initial setup)${NC}"
fi
echo ""

# Check TypeScript compilation
echo "6️⃣  Checking TypeScript types..."
npx tsc --noEmit > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "   ${GREEN}✅ TypeScript types OK${NC}"
else
    echo -e "   ${RED}❌ TypeScript errors found${NC}"
    exit 1
fi
echo ""

# Check linting
echo "7️⃣  Checking code style..."
npm run format:check > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "   ${GREEN}✅ Code formatting OK${NC}"
else
    echo -e "   ${YELLOW}⚠️  Code needs formatting (run: npm run format)${NC}"
fi
echo ""

echo "=================================================="
echo -e "${GREEN}✅ Verification complete!${NC}"
echo ""
echo "Next steps:"
echo "  • Run quick start: npm run example:quick-start"
echo "  • Run examples: npm run example:balance"
echo "  • Run tests: npm test"
echo "  • Build for production: npm run build"
echo ""
