#include "permute.h"
#include "../tensor.h"
#include "../utils.h"
#include <torch/torch.h>

namespace TensorOps {

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

  if (info.Length() < 1) {
    Napi::TypeError::New(env, "Expected dimensions array as argument").ThrowAsJavaScriptException();
    return env.Null();
  }

  if (!info[0].IsArray()) {
    Napi::TypeError::New(env, "Expected dimensions to be an array of numbers").ThrowAsJavaScriptException();
    return env.Null();
  }

  Napi::Array dims_array = info[0].As<Napi::Array>();
  std::vector<int64_t> dims;

  for (uint32_t i = 0; i < dims_array.Length(); i++) {
    Napi::Value val = dims_array[i];
    if (!val.IsNumber()) {
      Napi::TypeError::New(env, "Dimensions array must contain only numbers").ThrowAsJavaScriptException();
      return env.Null();
    }
    dims.push_back(val.As<Napi::Number>().Int64Value());
  }

  // Use PyTorch's permute method
  torch::Tensor result = self->tensor.permute(dims);
  return Tensor::NewInstance(env, result);
}

}  // namespace TensorOps
