#!/bin/bash
# Build TSS WASM module for browser

set -e

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

echo "=== Building TSS WASM Module ==="

# Download dependencies
echo "Downloading dependencies..."
go mod tidy

# Build WASM
echo "Building WASM..."
GOOS=js GOARCH=wasm go build -o tss.wasm .

# Get wasm_exec.js from Go installation
GOROOT=$(go env GOROOT)
if [ -f "$GOROOT/misc/wasm/wasm_exec.js" ]; then
    cp "$GOROOT/misc/wasm/wasm_exec.js" ./wasm_exec.js
    echo "Copied wasm_exec.js"
else
    echo "Warning: wasm_exec.js not found at $GOROOT/misc/wasm/wasm_exec.js"
fi

# Output size
if [ -f "tss.wasm" ]; then
    SIZE=$(ls -lh tss.wasm | awk '{print $5}')
    echo "=== Build Complete ==="
    echo "Output: tss.wasm ($SIZE)"
    echo "Runtime: wasm_exec.js"
else
    echo "Build failed!"
    exit 1
fi
