#!/usr/bin/env bash
# build-gioser-web.sh — wrapper para compilar gioser-web a WASM
# y generar los bindings JS via wasm-bindgen.
#
# Uso:
#   ./scripts/build-gioser-web.sh [dev|release]   (default: release)
#
# Output:
#   crates/apps/gioser-web/pkg/{gioser_web.js, gioser_web_bg.wasm, ...}

set -euo pipefail

MODE="${1:-release}"
case "$MODE" in
    dev)
        PROFILE_FLAG=""
        PROFILE_DIR="debug"
        ;;
    release)
        PROFILE_FLAG="--release"
        PROFILE_DIR="release"
        ;;
    *)
        echo "Uso: $0 [dev|release]" >&2
        exit 1
        ;;
esac

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$REPO_ROOT"

# Sanity check: target wasm32-unknown-unknown disponible.
if ! ls /usr/lib/rustlib/wasm32-unknown-unknown >/dev/null 2>&1 \
   && ! (command -v rustup >/dev/null 2>&1 \
         && rustup target list --installed 2>/dev/null | grep -q wasm32-unknown-unknown); then
    echo "✗ falta el target wasm32-unknown-unknown" >&2
    echo "  con rustup: rustup target add wasm32-unknown-unknown" >&2
    echo "  en Artix/Arch suele venir con el paquete rust base" >&2
    exit 1
fi

# Sanity check: wasm-bindgen-cli disponible.
if ! command -v wasm-bindgen >/dev/null 2>&1; then
    echo "✗ falta wasm-bindgen-cli" >&2
    echo "  instalar con: cargo install wasm-bindgen-cli --version 0.2.99" >&2
    echo "  (la versión debe coincidir con la del Cargo.lock — buscá la entrada"  >&2
    echo "   [[package]] name = \"wasm-bindgen\")" >&2
    exit 1
fi

echo "▶ cargo build $MODE → wasm32-unknown-unknown"
cargo build $PROFILE_FLAG --target wasm32-unknown-unknown -p gioser-web

WASM_IN="target/wasm32-unknown-unknown/$PROFILE_DIR/gioser_web.wasm"
PKG_OUT="crates/apps/gioser-web/pkg"

if [[ ! -f "$WASM_IN" ]]; then
    echo "✗ no se generó $WASM_IN" >&2
    exit 1
fi

echo "▶ wasm-bindgen → $PKG_OUT"
mkdir -p "$PKG_OUT"
wasm-bindgen "$WASM_IN" --out-dir "$PKG_OUT" --target web

# Reporte de tamaños.
WASM_OUT="$PKG_OUT/gioser_web_bg.wasm"
if [[ -f "$WASM_OUT" ]]; then
    size_bytes=$(stat -c%s "$WASM_OUT")
    size_kib=$(( size_bytes / 1024 ))
    if command -v gzip >/dev/null 2>&1; then
        gz_bytes=$(gzip -c "$WASM_OUT" | wc -c)
        gz_kib=$(( gz_bytes / 1024 ))
        echo "✓ $WASM_OUT — ${size_kib} KiB (~${gz_kib} KiB gzipped)"
    else
        echo "✓ $WASM_OUT — ${size_kib} KiB"
    fi
fi

echo ""
echo "Para probarlo:"
echo "  python3 -m http.server -d crates/apps/gioser-web 8080"
echo "  → http://localhost:8080/"
