#!/bin/bash

set -e  # يوقف السكربت عند أول خطأ
set -u  # يعتبر أي متغير غير معرف كخطأ

echo "🔧 Starting build process..."

# ───── مسارات الملفات ─────
SRC_DIR=src
BUILD_DIR=build

# ───── فلاغات عامة لـ Emscripten ─────
EMS_FLAGS="-O3 -s WASM=1 -s EXPORT_ES6=1 -s MODULARIZE=1"
RUNTIME_METHODS="-s EXPORTED_RUNTIME_METHODS=['cwrap','ccall','HEAPU8']"

mkdir -p "$BUILD_DIR"

# ───── Activation Module ─────
echo "⚙️  Compiling activation.cpp..."
emcc "$SRC_DIR/activation.cpp" \
    $EMS_FLAGS \
    -s EXPORT_NAME=Activation_Module \
    -s EXPORTED_FUNCTIONS="['_Activation_ReLu','_Activation_Sigmoid','_Activation_Tanh','_Activation_Softmax','_Activation_LeakyReLU','_Activation_Swish','_Activation_GELU','_Activation_ELU','_my_malloc','_my_free']" \
    $RUNTIME_METHODS \
    -o "$BUILD_DIR/Activation.js"

# ───── Loss Module ─────
echo "⚙️  Compiling loss.cpp..."
emcc "$SRC_DIR/loss.cpp" \
    $EMS_FLAGS \
    -s EXPORT_NAME=LossModule \
    -s EXPORTED_FUNCTIONS="['_my_malloc','_my_free','_Loss_MSE','_Loss_BinaryCrossEntropy','_Loss_CategoricalCrossEntropy','_Loss_MAE']" \
    $RUNTIME_METHODS \
    -o "$BUILD_DIR/Loss.js"

# ───── Layers Module ─────
echo "⚙️  Compiling layers.cpp..."
emcc "$SRC_DIR/layers.cpp" \
    $EMS_FLAGS \
    -s EXPORT_NAME=LayersModule \
    -s EXPORTED_FUNCTIONS="['_my_malloc','_my_free','_Layer_Dense','_Layer_Dropout','_Layer_Flatten','_Layer_Conv2D','_Layer_Embedding','_Layer_BatchNormalization']" \
    $RUNTIME_METHODS \
    -o "$BUILD_DIR/Layers.js"

# ───── Optimizers Module ─────
echo "⚙️  Compiling optimizers.cpp..."
emcc "$SRC_DIR/optimizers.cpp" \
    $EMS_FLAGS \
    -s EXPORT_NAME=OptimizersModule \
    -s EXPORTED_FUNCTIONS="['_my_malloc','_my_free','_Optimizer_SGD','_Optimizer_Adam']" \
    $RUNTIME_METHODS \
    -o "$BUILD_DIR/Optimizers.js"

echo "✅ Build completed successfully!"
