#include "log_softmax.h"
#include "../tensor.h"
#include <torch/torch.h>

namespace TensorOps {

Napi::Value LogSoftmax(Tensor* self, const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  try {
    // Parse optional dim parameter (default: -1)
    int64_t dim = -1;
    if (info.Length() > 0 && info[0].IsNumber()) {
      dim = info[0].As<Napi::Number>().Int64Value();
    }

    // Apply log_softmax: log(exp(x_i) / sum(exp(x_j))) = x_i - log(sum(exp(x_j)))
    // This is numerically stable compared to log(softmax(x))
    // PyTorch implements it as: x_i - log_sum_exp(x)
    torch::Tensor result = torch::log_softmax(self->tensor, dim);
    return Tensor::NewInstance(env, result);
  } catch (const std::exception& e) {
    Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
    return env.Undefined();
  }
}

}  // namespace TensorOps
