#!/bin/bash
# LastID SDK Workbench Build Script
# Builds the WASM SDK and sets up the workbench for local development

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo "================================================"
echo "  LastID SDK Workbench Builder"
echo "================================================"
echo ""

# Check for wasm-pack
if ! command -v wasm-pack &> /dev/null; then
    echo "wasm-pack not found. Installing..."
    cargo install wasm-pack
fi

# Check for simple HTTP server
check_server() {
    if command -v python3 &> /dev/null; then
        echo "python3"
    elif command -v python &> /dev/null; then
        echo "python"
    elif command -v npx &> /dev/null; then
        echo "npx"
    else
        echo "none"
    fi
}

echo "[1/3] Building WASM SDK..."
cd "$PROJECT_DIR"

# Build with wasm-pack for web target (release is default)
# Include websocket feature for real-time status updates via WebSocket
wasm-pack build \
    --target web \
    --out-dir workbench/pkg \
    --features "full,wasm,websocket"

echo ""
echo "[2/3] WASM build complete!"
echo "      Output: workbench/pkg/"
echo ""

# List generated files
echo "Generated files:"
ls -la "$SCRIPT_DIR/pkg/" | grep -E '\.(js|wasm)$'

echo ""
echo "[3/3] Starting development server..."
echo ""

cd "$SCRIPT_DIR"

SERVER=$(check_server)

case $SERVER in
    "python3")
        echo "Using Python 3 HTTP server"
        echo "Workbench available at: http://localhost:3001"
        echo ""
        python3 -m http.server 3001
        ;;
    "python")
        echo "Using Python HTTP server"
        echo "Workbench available at: http://localhost:3001"
        echo ""
        python -m SimpleHTTPServer 3001
        ;;
    "npx")
        echo "Using npx serve"
        echo "Workbench available at: http://localhost:3001"
        echo ""
        npx serve -l 3001
        ;;
    *)
        echo "No HTTP server found!"
        echo "Install Python 3 or run: npx serve -l 8080"
        echo ""
        echo "Then open: http://localhost:8080"
        exit 1
        ;;
esac
