#include "math_utils.h"
#include <cmath>
#include <cstdlib>
#include <iostream>

// 包含 emscripten 头文件
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
// 非 Emscripten 环境的替代定义
#define EMSCRIPTEN_KEEPALIVE
#endif

// 所有函数都加上 EMSCRIPTEN_KEEPALIVE
EMSCRIPTEN_KEEPALIVE
int add(int a, int b)
{
    return a + b;
}

EMSCRIPTEN_KEEPALIVE
int subtract(int a, int b)
{
    return a - b;
}

EMSCRIPTEN_KEEPALIVE
float multiply(float a, float b)
{
    return a * b;
}

EMSCRIPTEN_KEEPALIVE
float divide(float a, float b)
{
    if (b == 0.0f)
    {
        std::cerr << "Error: Division by zero" << std::endl;
        return 0.0f;
    }
    return a / b;
}

EMSCRIPTEN_KEEPALIVE
int fibonacci(int n)
{
    if (n <= 1)
        return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

EMSCRIPTEN_KEEPALIVE
void *create_buffer(int size)
{
    if (size <= 0)
        return nullptr;
    return malloc(size * sizeof(char));
}

EMSCRIPTEN_KEEPALIVE
void destroy_buffer(void *p)
{
    if (p)
    {
        free(p);
    }
}

EMSCRIPTEN_KEEPALIVE
int compute_sum(int *arr, int size)
{
    if (arr == nullptr || size <= 0)
    {
        return 0;
    }

    int sum = 0;
    for (int i = 0; i < size; i++)
    {
        sum += arr[i];
    }
    return sum;
}

EMSCRIPTEN_KEEPALIVE
const char *get_greeting()
{
    return "Hello from Smart WebAssembly!";
}