#include "addon.h"
#include "executor.h"
#include "function_marshal.h"

namespace ctypes {

Napi::Value FFIFunction::CallAsyncChecked(const Napi::CallbackInfo& info) {
  std::unique_ptr<StructExtras> structs;
  const TypedExtras typed = TakeTypedExtras(structs, std::max(info.Length(), size_t{1}) - 1);
  if (info.Length() < 1 || !info[0].IsFunction()) {
    throw Napi::TypeError::New(info.Env(), "a result handler function is required");
  }
  const Napi::Function errcheck = info[0].As<Napi::Function>();
  return CallAsyncArguments(FunctionArguments{info, 1}, &errcheck, nullptr, typed);
}

Napi::Value FFIFunction::CallOn(const Napi::CallbackInfo& info) {
  std::unique_ptr<StructExtras> structs;
  const TypedExtras typed = TakeTypedExtras(structs, std::max(info.Length(), size_t{1}) - 1);
  if (info.Length() < 1 || !info[0].IsObject()) {
    throw Napi::TypeError::New(info.Env(), "callOn requires a call target");
  }
  const Napi::Object call = info[0].As<Napi::Object>();
  const Napi::Function errcheck = SnapshotErrcheck();
  return CallAsyncArguments(FunctionArguments{info, 1, false}, errcheck.IsEmpty() ? nullptr : &errcheck, &call, typed);
}

Napi::Value FFIFunction::CallOnChecked(const Napi::CallbackInfo& info) {
  std::unique_ptr<StructExtras> structs;
  const TypedExtras typed = TakeTypedExtras(structs, std::max(info.Length(), size_t{2}) - 2);
  if (info.Length() < 2 || !info[0].IsObject() || !info[1].IsFunction()) {
    throw Napi::TypeError::New(info.Env(), "a call target and a result handler function are required");
  }
  const Napi::Object call = info[0].As<Napi::Object>();
  const Napi::Function errcheck = info[1].As<Napi::Function>();
  return CallAsyncArguments(FunctionArguments{info, 2, true}, &errcheck, &call, typed);
}

// ============================================================================
// CallAsync - Esegue l'invoker fisso o libffi su un worker, ritorna Promise
// Supporta variadic, buffer pinning, string fixup
// ============================================================================

Napi::Value FFIFunction::CallAsync(const Napi::CallbackInfo& info) {
  std::unique_ptr<StructExtras> structs;
  const TypedExtras typed = TakeTypedExtras(structs, info.Length());
  const Napi::Function errcheck = SnapshotErrcheck();
  return CallAsyncArguments(FunctionArguments{info}, errcheck.IsEmpty() ? nullptr : &errcheck, nullptr, typed);
}

napi_value FFIFunction::FastCallAsync(napi_env env, napi_callback_info info) {
  return GuardNapiCall(env, [&]() -> napi_value {
    Napi::CallbackInfo cb(env, info);
    return static_cast<FFIFunction*>(cb.Data())->CallAsync(cb);
  });
}

napi_value FFIFunction::FastCallAsyncResult(napi_env env, napi_callback_info info) {
  return GuardNapiCall(env, [&]() -> napi_value {
    Napi::CallbackInfo cb(env, info);
    return static_cast<FFIFunction*>(cb.Data())->CallAsyncResult(cb);
  });
}

Napi::Value FFIFunction::InstallFastAsync(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  Napi::Object self = Value();
  const napi_property_descriptor owner_prop = {"_ffiFunction", nullptr, nullptr,      nullptr,
                                               nullptr,        self,    napi_default, nullptr};
  const Napi::Function fast_async = napi_fast::NewFunction(env, "callAsync", &FFIFunction::FastCallAsync, this);
  const Napi::Function fast_async_res =
    napi_fast::NewFunction(env, "_callAsyncResult", &FFIFunction::FastCallAsyncResult, this);
  napi_fast::DefineProperties(env, fast_async, std::span(&owner_prop, 1));
  napi_fast::DefineProperties(env, fast_async_res, std::span(&owner_prop, 1));
  const auto writable_cfg = static_cast<napi_property_attributes>(napi_writable | napi_configurable);
  const std::array<napi_property_descriptor, 2> async_props = {{
    {"callAsync", nullptr, nullptr, nullptr, nullptr, fast_async, writable_cfg, nullptr},
    {"_callAsyncResult", nullptr, nullptr, nullptr, nullptr, fast_async_res, writable_cfg, nullptr},
  }};
  napi_fast::DefineProperties(env, self, async_props);
  return env.Undefined();
}

Napi::Value FFIFunction::SetAsyncResultHandler(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  if (info.Length() < 1 || !info[0].IsFunction()) {
    throw Napi::TypeError::New(env, "_setAsyncResultHandler(handler[, 'word' | 'borrowed'])");
  }
  size_t word_size = 0;
  if (info.Length() > 1 && !info[1].IsUndefined()) {
    if (!info[1].IsString()) {
      throw Napi::TypeError::New(env, "async result mode must be a string");
    }
    const std::string mode = info[1].As<Napi::String>().Utf8Value();
    if (mode == "word") {
      word_size = return_struct_info_ && struct_as_buffer_ ? return_struct_info_->GetSize() : 0;
      if (word_size != 4 && word_size != 8) {
        throw Napi::TypeError::New(env, "word result handler requires a 4- or 8-byte structure");
      }
    } else if (mode == "borrowed") {
      if (!return_struct_info_ || !struct_as_buffer_ || struct_result_data_ == nullptr) {
        throw Napi::TypeError::New(env, "borrowed result handler requires a struct_buffer return");
      }
      word_size = kAsyncResultBorrowed;
    } else {
      throw Napi::TypeError::New(env, "unsupported async result handler mode");
    }
  }
  async_result_handler_ = Napi::Weak(info[0].As<Napi::Function>());
  async_result_word_size_ = word_size;
  return env.Undefined();
}

Napi::Value FFIFunction::CallAsyncResult(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  if (async_result_handler_.IsEmpty() || async_result_handler_.Value().IsEmpty()) {
    throw Napi::TypeError::New(env, "an async result handler is not configured");
  }
  std::unique_ptr<StructExtras> structs;
  const TypedExtras typed = TakeTypedExtras(structs, info.Length());
  return CallAsyncArguments(FunctionArguments{info, 0, true}, nullptr, nullptr, typed, true);
}

template <typename Target>
std::unique_ptr<Target> FFIFunction::PrepareAsyncCall(const FunctionArguments& info,
                                                      const Napi::Function* errcheck,
                                                      TypedExtras typed,
                                                      bool use_cached_result_handler) {
  Napi::Env env = info.Env();

  size_t argc;
  bool is_variadic = false;
  if (!ValidateAndResolveArgc(env, info, argc, is_variadic)) {
    return nullptr;
  }
  const LibraryCallScope library_scope(library_, env);
  const size_t expected_argc = arg_types_.size();

  // ---- Validazione di argc (condivisa con Call sincrona) -----------
  //       fatta da ValidateAndResolveArgc sopra.

  // ---- Tipi dedotti degli argomenti extra variadici ----------------
  // =====================================================================
  // Tipi per argomenti extra variadic (inferiti dai valori JS)
  // =====================================================================
  std::vector<CType> extra_types;
  std::vector<Napi::Value> extra_values;
  const std::span<const std::shared_ptr<StructInfo>> extra_structs =
    is_variadic ? typed.Structs(argc - expected_argc) : std::span<const std::shared_ptr<StructInfo>>{};
  if (is_variadic) {
    extra_types.reserve(argc - expected_argc);
    extra_values.reserve(argc - expected_argc);
    for (size_t i = expected_argc; i < argc; i++) {
      const size_t position = i - expected_argc;
      // Struttura passata per valore (vedi StructExtras): i suoi byte, convertiti dal wrapper JS.
      if (position < extra_structs.size() && extra_structs[position]) [[unlikely]] {
        extra_types.push_back(CType::CTYPES_STRUCT);
        extra_values.push_back(info[i]);
        continue;
      }
      // Tipo dichiarato dal wrapper JS (istanza SimpleCData): nessuna deduzione.
      const CType declared = typed.At(position, expected_argc);
      const VariadicValue extra =
        declared != CType::CTYPES_VOID ? VariadicValue{declared, info[i]} : InferVariadic(info[i], i, expected_argc);
      extra_types.push_back(extra.type);
      extra_values.push_back(extra.value);
    }
  }

  // Le firme extra hanno una firma AOT propria, preparata sul thread JS.
  AotAsyncCallState aot;

  if (is_variadic) {
    if (!PrepareAsyncFFI(env, argc, extra_types, extra_structs, aot)) {
      return nullptr;
    }
  } else if (!abi_plan_.fixed && !PrepareFFI(env)) {
    return nullptr;
  }

  // =====================================================================
  // ---- Conversione JS → C (thread principale), con i Buffer tenuti vivi
  //              e fixup post-move per le stringhe --------------------
  //
  // Tutto va su heap. Tracciamo string offsets per fixup post-move
  // e pinniamo i Buffer JS.
  // =====================================================================

  // SBO: per <= PreparedCall::kInlineArgs evita le allocazioni heap di arg_storage/arg_values.
  alignas(16) std::array<uint8_t, PreparedCall::kInlineArgs * ARG_SLOT_SIZE> inline_arg_storage{};
  uint8_t inline_large_arg_index = PreparedCall::kNoInlineLargeArg;
  std::vector<uint8_t> heap_arg_storage;
  if (argc > PreparedCall::kInlineArgs) {
    heap_arg_storage.resize(argc * ARG_SLOT_SIZE, 0);
  }
  std::vector<char> async_string_buffer;
  std::vector<std::pair<size_t, size_t>> string_fixups;
  std::vector<std::pair<size_t, size_t>> wstring_fixups;
  std::vector<Napi::ObjectReference> buffer_refs;
  std::vector<Napi::ObjectReference> copied_refs;
  std::vector<std::vector<uint8_t>> large_arg_buffers;
  std::vector<size_t> large_arg_indices;  // slot degli argomenti che usano large_arg_buffers (in ordine)

  // Stima spazio stringhe (saltata quando la firma fissa non ha parametri stringa)
  if (is_variadic || has_string_args_) {
    size_t str_count = 0;
    for (size_t i = 0; i < argc; i++) {
      CType t = (i < expected_argc) ? arg_types_[i] : extra_types[i - expected_argc];
      if (t == CType::CTYPES_STRING || t == CType::CTYPES_WSTRING) {
        str_count++;
      }
    }
    if (str_count > 0) {
      async_string_buffer.reserve(str_count * 128);
    }
  }

  uint8_t* arg_storage = argc <= PreparedCall::kInlineArgs ? inline_arg_storage.data() : heap_arg_storage.data();

  for (size_t i = 0; i < argc; i++) {
    uint8_t* slot = arg_storage + (i * ARG_SLOT_SIZE);
    void* arg_value_placeholder = slot;

    CType type = (i < expected_argc) ? arg_types_[i] : extra_types[i - expected_argc];
    const Napi::Value val = (i < expected_argc) ? info[i] : extra_values[i - expected_argc];
    // Un'istanza SimpleCData variadica sostituita dal suo valore resta viva
    // (con i suoi _objects) per tutta la chiamata, come in Python.
    if (i >= expected_argc && info[i].IsObject() && !val.StrictEquals(info[i])) {
      buffer_refs.push_back(Napi::Persistent(info[i].As<Napi::Object>()));
    }
    // Ogni argomento oggetto resta vivo fino al completamento (un riferimento
    // solo): la memoria delle viste è usata in place, come nelle chiamate
    // sincrone. La memoria di una struttura o di un array per valore è invece
    // copiata qui: resta viva (i suoi puntatori possono riferirsi ad altra
    // memoria JS che tiene viva), ma staccarla (transfer()) non invalida il
    // risultato e Complete() non la controlla.
    if (val.IsObject()) {
      const bool plain_struct_view = type == CType::CTYPES_STRUCT && i < expected_argc && arg_struct_infos_[i] &&
                                     !arg_struct_infos_[i]->HasAddressFields() &&
                                     napi_fast::TryViewData(val) != nullptr;
      if (!plain_struct_view) {
        (IsByValueAggregate(type) && MemoryBytes(val) ? copied_refs : buffer_refs)
          .push_back(Napi::Persistent(val.As<Napi::Object>()));
      }
    }

    // Percorso rapido: tipi primitivi (implementazione condivisa)
    try {
      if (MarshalPrimitive(val, type, slot)) {
        continue;
      }
    } catch (const Napi::Error& e) {
      throw ArgumentErrorFor(env, i, e);
    }

    // c_void_p.from_param(str) di CPython: una stringa JS passa come wchar_t*.
    if (type == CType::CTYPES_POINTER && val.IsString()) {
      type = CType::CTYPES_WSTRING;
    }

    try {
      switch (type) {
        case CType::CTYPES_POINTER: {
          void* const ptr = PointerArg(val, val.Type(), type);
          memcpy(slot, &ptr, sizeof(ptr));
          break;
        }

        case CType::CTYPES_STRING: {
          const napi_valuetype kind = val.Type();
          if (kind == napi_string) {
            const size_t offset = async_string_buffer.size();
            napi_fast::AppendUtf8(val.As<Napi::String>(), async_string_buffer);

            // Puntatore provvisorio (verrà fixato dal worker)
            const char* str_ptr = async_string_buffer.data() + offset;
            memcpy(slot, &str_ptr, sizeof(str_ptr));

            // Registra per fixup post-move
            string_fixups.emplace_back(i, offset);
          } else {
            // Memoria, indirizzo o NULL, come nel percorso sincrono.
            const void* const ptr = PointerArg(val, kind, type);
            memcpy(slot, &ptr, sizeof(ptr));
          }
          break;
        }

        case CType::CTYPES_WSTRING: {
          const napi_valuetype kind = val.Type();
          if (kind == napi_string) {
            std::u16string u16str = val.As<Napi::String>().Utf16Value();
            if (i >= expected_argc) {
              ThrowIfEmbeddedNull(env, u16str);
            }
            size_t wchar_size = sizeof(wchar_t);
            size_t byte_len = (u16str.length() + 1) * wchar_size;

            // Offset allineato a wchar_t per evitare accessi non allineati
            // (critici su ARM, più lenti su x86)
            size_t offset = async_string_buffer.size();
            constexpr size_t wchar_align = alignof(wchar_t);
            offset = (offset + wchar_align - 1) & ~(wchar_align - 1);
            async_string_buffer.resize(offset + byte_len);

            Utf16ToWide(u16str,
                        std::span(reinterpret_cast<wchar_t*>(async_string_buffer.data() + offset), u16str.size() + 1));

            const wchar_t* str_ptr = reinterpret_cast<const wchar_t*>(async_string_buffer.data() + offset);
            memcpy(slot, &str_ptr, sizeof(str_ptr));

            wstring_fixups.emplace_back(i, offset);
          } else {
            // Memoria, indirizzo o NULL, come nel percorso sincrono.
            const void* const ptr = PointerArg(val, kind, type);
            memcpy(slot, &ptr, sizeof(ptr));
          }
          break;
        }

        case CType::CTYPES_STRUCT: {
          if (i < expected_argc && arg_struct_infos_[i]) {
            const size_t struct_size = arg_struct_infos_[i]->GetSize();
            if (argc <= PreparedCall::kInlineLargeArgMaxArgs && struct_size > ARG_SLOT_SIZE &&
                struct_size <= PreparedCall::kInlineLargeArgSize &&
                inline_large_arg_index == PreparedCall::kNoInlineLargeArg) {
              size_t view_len = 0;
              if (void* view_data = napi_fast::TryViewData(val, &view_len);
                  view_data != nullptr && view_len >= struct_size) [[likely]] {
                std::memcpy(inline_arg_storage.data() + PreparedCall::kInlineLargeArgOffset, view_data, struct_size);
                inline_large_arg_index = static_cast<uint8_t>(i);
                break;
              }
            }
            MarshalStructArg(env, val, i, arg_struct_infos_[i], slot, &arg_value_placeholder, large_arg_buffers,
                             &large_arg_indices, &buffer_refs, &copied_refs);
          } else if (i >= expected_argc && i - expected_argc < extra_structs.size() &&
                     extra_structs[i - expected_argc]) {
            // Struttura extra: copiata come una struttura dichiarata (i layout restano
            // vivi con la firma, LibffiAsyncSignature::structs).
            MarshalStructArg(env, val, i, extra_structs[i - expected_argc], slot, &arg_value_placeholder,
                             large_arg_buffers, &large_arg_indices, &buffer_refs, &copied_refs);
          } else {
            MarshalOther(val, type, slot);
          }
          break;
        }

        case CType::CTYPES_ARRAY: {
          if (i < expected_argc && arg_array_infos_[i]) {
            MarshalArrayArg(env, val, i, arg_array_infos_[i], slot, &arg_value_placeholder, large_arg_buffers,
                            &large_arg_indices, &buffer_refs);
          } else {
            MarshalOther(val, type, slot);
          }
          break;
        }

        default:
          MarshalOther(val, type, slot);
          break;
      }
    } catch (const Napi::Error& e) {
      throw ArgumentErrorFor(env, i, e);
    }
  }

  // =====================================================================
  // ---- PreparedCall: possiede gli argomenti convertiti fino alla fine ----
  // =====================================================================

  // Memoria per valore (copiata) dopo quella usata in place: solo tenuta viva.
  const size_t checked_refs = buffer_refs.size();
  for (Napi::ObjectReference& ref : copied_refs) {
    buffer_refs.push_back(std::move(ref));
  }

  const size_t inline_copy_bytes = inline_large_arg_index != PreparedCall::kNoInlineLargeArg
                                     ? inline_arg_storage.size()
                                     : std::min(argc, PreparedCall::kInlineArgs) * ARG_SLOT_SIZE;
  return std::make_unique<Target>(
    env, this, is_variadic ? nullptr : abi_plan_.fixed, fn_ptr_, return_type_, return_struct_info_, return_array_info_,
    argc, std::span(inline_arg_storage).first(inline_copy_bytes), std::move(heap_arg_storage),
    std::move(async_string_buffer), std::move(string_fixups), std::move(wstring_fixups), std::move(buffer_refs),
    checked_refs, std::move(aot), std::move(large_arg_buffers), std::move(large_arg_indices), inline_large_arg_index,
    errcheck, info.HasResultHandler(), use_cached_result_handler);
}

// callAsync(): un worker del pool libuv. callOn(): la coda dell'Executor
// indicato da `target`, l'oggetto di questa sola invocazione: le conversioni
// degli argomenti (from_param) e gli errcheck possono eseguire altre callOn,
// che hanno ciascuna il proprio. Conversioni, errcheck e risultato sono gli stessi.
Napi::Value FFIFunction::CallAsyncArguments(const FunctionArguments& info,
                                            const Napi::Function* errcheck,
                                            const Napi::Object* target,
                                            TypedExtras typed,
                                            bool use_cached_result_handler) {
  Napi::Env env = info.Env();
  Executor* executor = nullptr;
  if (target != nullptr) {
    executor = UnwrapTagged<Executor>(target->Get("executor"));
    if (executor == nullptr) {
      throw Napi::TypeError::New(env, "callOn requires an Executor");
    }
  }

  const bool keep_args = errcheck != nullptr && !info.HasResultHandler();
  if (executor != nullptr) {
    std::unique_ptr<PreparedCall> call = PrepareAsyncCall<PreparedCall>(info, errcheck, typed);
    if (!call) {
      return env.Undefined();
    }
    if (keep_args) {
      call->KeepArguments(info);
    }
    Napi::Promise promise = call->GetPromise();
    // Un segnale annullato durante la preparazione degli argomenti (un
    // adattatore può farlo): la chiamata non viene accodata.
    if (const Napi::Value signal = target->Get("signal"); signal.IsObject()) {
      const Napi::Object abort = signal.As<Napi::Object>();
      if (abort.Get("aborted").ToBoolean().Value()) {
        call->Reject(abort.Get("reason"));
        return promise;
      }
    }
    // L'identità della chiamata, per annullarla finché è in coda: scritta
    // nell'oggetto dell'invocazione, non ricostruita in seguito.
    const uint64_t job = executor->Submit(env, std::move(call));
    target->Set("job", Napi::Number::New(env, static_cast<double>(job)));
    return promise;
  }

  // callAsync: CallWorker incorpora PreparedCall per valore (una sola allocazione heap).
  std::unique_ptr<CallWorker> worker = PrepareAsyncCall<CallWorker>(info, errcheck, typed, use_cached_result_handler);
  if (!worker) {
    return env.Undefined();
  }
  if (keep_args) {
    worker->Call().KeepArguments(info);
  }
  Napi::Promise promise = worker->Call().GetPromise();
  worker->Queue();
  worker.release();
  return promise;
}

// ============================================================================
// Implementazioni di PreparedCall / CallWorker (classi annidate)
// ============================================================================

FFIFunction::PreparedCall::PreparedCall(Napi::Env env,
                                        FFIFunction* parent,
                                        abi::FixedInvoker invoker,
                                        void* fn_ptr,
                                        CType return_type,
                                        std::shared_ptr<StructInfo> return_struct_info,
                                        std::shared_ptr<ArrayInfo> return_array_info,
                                        size_t argc,
                                        std::span<const uint8_t> inline_arg_storage,
                                        std::vector<uint8_t>&& heap_arg_storage,
                                        std::vector<char>&& string_buffer,
                                        std::vector<std::pair<size_t, size_t>>&& string_fixups,
                                        std::vector<std::pair<size_t, size_t>>&& wstring_fixups,
                                        std::vector<Napi::ObjectReference>&& buffer_refs,
                                        size_t checked_refs,
                                        AotAsyncCallState&& aot,
                                        std::vector<std::vector<uint8_t>>&& large_arg_buffers,
                                        std::vector<size_t>&& large_arg_indices,
                                        uint8_t inline_large_arg_index,
                                        const Napi::Function* errcheck,
                                        bool result_handler,
                                        bool use_cached_result_handler)
  : AotAsyncCallState(std::move(aot)),
    ffi_function_(parent),
    invoker_(invoker),
    fn_ptr_(fn_ptr),
    return_type_(return_type),
    return_struct_info_(std::move(return_struct_info)),
    return_array_info_(std::move(return_array_info)),
    argc_(argc),
    arg_storage_(std::move(heap_arg_storage)),
    string_buffer_(std::move(string_buffer)),
    string_fixups_(std::move(string_fixups)),
    wstring_fixups_(std::move(wstring_fixups)),
    buffer_refs_(std::move(buffer_refs)),
    checked_refs_(checked_refs),
    large_arg_buffers_(std::move(large_arg_buffers)),
    large_arg_indices_(std::move(large_arg_indices)),
    return_ptr_(nullptr),
    deferred_(Napi::Promise::Deferred::New(env)),
    errcheck_ref_(errcheck == nullptr ? Napi::FunctionReference() : Napi::Persistent(*errcheck)),
    result_handler_(result_handler || use_cached_result_handler),
    use_cached_result_handler_(use_cached_result_handler),
    capture_last_error_(parent->capture_last_error_),
    capture_errno_(parent->capture_errno_),
    struct_as_buffer_(parent->struct_as_buffer_),
    scalar_as_buffer_(parent->scalar_as_buffer_),
    inline_large_arg_index_(inline_large_arg_index) {
  if (parent->addon_ != nullptr) {
    last_error_in_ = parent->addon_->captured_last_error;
    errno_in_ = parent->addon_->captured_errno;
  }

  if (argc_ <= kInlineArgs) {
    if (!inline_arg_storage.empty()) {
      std::memcpy(inline_arg_storage_.data(), inline_arg_storage.data(), inline_arg_storage.size());
    }
  } else {
    arg_values_.resize(argc_);
  }

  Activate(*parent, invoker_ != nullptr);

  // Storage inline fino a kInlineReturnSize (64 B): evita allocazione heap per struct/HFA comuni.
  return_ptr_ = inline_return_storage_.data();
  size_t ret_size = 0;
  size_t ret_alignment = 0;
  if (return_type_ == CType::CTYPES_STRUCT && return_struct_info_) {
    ret_size = return_struct_info_->GetSize();
    ret_alignment = return_struct_info_->GetAlignment();
  } else if (return_type_ == CType::CTYPES_ARRAY && return_array_info_) {
    ret_size = return_array_info_->GetSize();
    ret_alignment = return_array_info_->GetAlignment();
  }
  if (ret_size > kInlineReturnSize || ret_alignment > kInlineReturnAlignment) {
    return_ptr_ = AlignedReturnArea(return_buffer_, ret_size, ret_alignment);
    std::memset(return_ptr_, 0, ret_size);
  }

  // Ricalcola tutti i puntatori dopo il move
  FixupPointers();
  // Il parent trattiene libreria e metadata.
  ffi_function_->Ref();
  if (ffi_function_->library_ != nullptr) {
    ffi_function_->library_->BeginCall();
  }
}

void FFIFunction::PreparedCall::FixupPointers() {
  uint8_t* base = argc_ <= kInlineArgs ? inline_arg_storage_.data() : arg_storage_.data();
  void** values = argc_ <= kInlineArgs ? inline_arg_values_.data() : arg_values_.data();

  // 1. Ricalcola i puntatori agli slot dal base definitivo
  for (size_t i = 0; i < argc_; i++) {
    values[i] = base + (i * ARG_SLOT_SIZE);
  }

  // 2. Struct/array grandi: puntano allo storage inline (SBO) o ai buffer di overflow
  if (inline_large_arg_index_ != kNoInlineLargeArg) {
    values[inline_large_arg_index_] = inline_arg_storage_.data() + kInlineLargeArgOffset;
  }
  for (size_t k = 0; k < large_arg_indices_.size(); k++) {
    const size_t arg_idx = large_arg_indices_[k];
    values[arg_idx] = large_arg_buffers_[k].data();
  }

  // 3. Fixup puntatori a stringhe (char*) dentro gli slot
  const char* str_base = string_buffer_.data();
  for (const auto& [slot_index, str_offset] : string_fixups_) {
    uint8_t* slot = base + (slot_index * ARG_SLOT_SIZE);
    const char* new_ptr = str_base + str_offset;
    memcpy(slot, &new_ptr, sizeof(new_ptr));
  }

  // 4. Fixup puntatori a wstring (wchar_t*) dentro gli slot
  for (const auto& [slot_index, str_offset] : wstring_fixups_) {
    uint8_t* slot = base + (slot_index * ARG_SLOT_SIZE);
    const wchar_t* new_ptr = reinterpret_cast<const wchar_t*>(str_base + str_offset);
    memcpy(slot, &new_ptr, sizeof(new_ptr));
  }
}

void FFIFunction::PreparedCall::KeepArguments(const FunctionArguments& info) {
  Napi::Array args = Napi::Array::New(info.Env(), info.Length());
  for (size_t i = 0; i < info.Length(); i++) {
    args.Set(static_cast<uint32_t>(i), info[i]);
  }
  args_ref_ = Napi::Persistent(args.As<Napi::Object>());
}

FFIFunction::PreparedCall::~PreparedCall() {
  if (signature_ && signature_->types.size() <= MAX_INLINE_ARGS && !ffi_function_->idle_async_signature_) {
    ffi_function_->idle_async_signature_ = std::move(signature_);
  }
  if (ffi_function_->library_ != nullptr) {
    ffi_function_->library_->EndCall();
  }
  // Rilascia l'istanza FFIFunction. Un distruttore non deve lanciare: durante
  // la chiusura dell'environment Node-API può rifiutare la chiamata.
  try {
    ffi_function_->Unref();
  } catch (...) {
  }
}

void FFIFunction::PreparedCall::Run(bool measure_duration) noexcept {
  // *** THREAD NATIVO - Nessun accesso a V8! ***
  const auto started = measure_duration ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
  try {
    const SavedErrorState saved = SwapErrorStateIn(capture_last_error_, capture_errno_, last_error_in_, errno_in_);
    void** args = argc_ == 0 ? nullptr : (argc_ <= kInlineArgs ? inline_arg_values_.data() : arg_values_.data());
    InvokeForeign(fault_, [&] {
      if (invoker_) {
        invoker_(fn_ptr_, args, return_ptr_);
      } else {
        InvokeAot(*this, fn_ptr_, return_ptr_, args);
      }
    });
    // Snapshot su questo thread, subito dopo la chiamata (come CaptureErrorState).
    SwapErrorStateOut(capture_last_error_, capture_errno_, saved, last_error_, last_errno_);
    if (fault_.code != 0) [[unlikely]] {
      failed_ = true;
      failure_ = "exception";
    }
  } catch (...) {
    failed_ = true;
    failure_ = "Native function threw an exception";
  }
  if (measure_duration) {
    run_duration_ = std::chrono::steady_clock::now() - started;
  }
}

void FFIFunction::PreparedCall::Reject(Napi::Value reason) {
  deferred_.Reject(reason);
}

void FFIFunction::PreparedCall::Complete(Napi::Env env, bool open_scope) {
  // *** THREAD PRINCIPALE ***
  std::optional<Napi::HandleScope> scope;
  if (open_scope) {
    scope.emplace(env);
  }

  if (failed_) {
    deferred_.Reject(fault_.code != 0 ? ForeignFaultError(env, fault_).Value()
                                      : Napi::Error::New(env, failure_).Value());
    return;
  }

  // get_last_error() / get_errno() vedono questa chiamata, anche dentro errcheck.
  if (capture_last_error_ || capture_errno_) {
    ffi_function_->PublishErrorState(last_error_, last_errno_);
  }

  // La memoria delle viste è stata usata in place: se una vista è stata
  // staccata nel frattempo, il codice nativo può aver letto o scritto memoria
  // già liberata e il risultato non è affidabile.
  for (const Napi::ObjectReference& ref : std::span(buffer_refs_).first(checked_refs_)) {
    if (IsDetachedView(ref.Value())) {
      deferred_.Reject(Napi::Error::New(env, std::format("buffer argument: {}", kDetachedArgumentMessage)).Value());
      return;
    }
  }

  try {
    Napi::Function cached_handler;
    if (use_cached_result_handler_) {
      if (!ffi_function_->async_result_handler_.IsEmpty()) {
        cached_handler = ffi_function_->async_result_handler_.Value();
      }
      if (cached_handler.IsEmpty()) {
        deferred_.Reject(Napi::TypeError::New(env, "an async result handler is not configured").Value());
        return;
      }
    }
    Napi::Value result;
    // Per i reader scalari piccoli la parola JS possiede tutti i bit, incluso
    // il padding: nessun Buffer condiviso né allocazione di memoria esterna.
    const size_t word_size = cached_handler.IsEmpty() ? 0 : ffi_function_->async_result_word_size_;
    if (word_size == 8) {
      result = Napi::BigInt::New(env, LoadAs<uint64_t>(return_ptr_));
    } else if (word_size == 4) {
      result = Napi::Number::New(env, LoadAs<uint32_t>(return_ptr_));
    } else if (word_size == kAsyncResultBorrowed && ffi_function_->struct_result_data_ != nullptr) {
      result = ffi_function_->StructResult(return_ptr_);
    } else {
      result = FFIFunction::ConvertReturn(env, return_ptr_, return_type_, return_struct_info_, return_array_info_,
                                          struct_as_buffer_, scalar_as_buffer_);
    }

    if (!cached_handler.IsEmpty()) {
      napi_value raw_out = nullptr;
      const napi_value raw_result = result;
      if (!napi_fast::CallFunction(env, napi_fast::Undefined(env), cached_handler, 1, &raw_result, raw_out)) {
        deferred_.Reject(env.IsExceptionPending() ? env.GetAndClearPendingException().Value()
                                                  : Napi::Error::New(env, "Result handler failed").Value());
        return;
      }
      deferred_.Resolve(Napi::Value(env, raw_out));
      return;
    }

    // Errcheck (se presente)
    if (!errcheck_ref_.IsEmpty()) {
      try {
        if (result_handler_) {
          result = errcheck_ref_.Call({result});
        } else {
          Napi::Value args_array = args_ref_.IsEmpty() ? Napi::Array::New(env, 0) : args_ref_.Value();
          result = errcheck_ref_.Call({result, ffi_function_->Value(), args_array});
        }
      } catch (const Napi::Error& e) {
        deferred_.Reject(e.Value());
        return;
      }
    }

    deferred_.Resolve(result);
  } catch (const Napi::Error& e) {
    deferred_.Reject(e.Value());
  }
}

void FFIFunction::CallWorker::Execute() {
  // *** THREAD DEL WORKER - Nessun accesso a V8! ***
  call_.Run(false);
}

void FFIFunction::CallWorker::OnWorkComplete(Napi::Env env, napi_status status) {
  if (status != napi_ok) [[unlikely]] {
    if (env == nullptr || status == napi_closing || napi_fast::CannotRunJs(env)) {
      Destroy();
      return;
    }
    SetError(status == napi_cancelled ? "Asynchronous call cancelled" : "Asynchronous work did not complete");
  }
  // AsyncWorker salta il callback per napi_cancelled. Qui anche l'annullamento
  // passa da OnError, sotto l'HandleScope gestito da AsyncWorker.
  Napi::AsyncWorker::OnWorkComplete(env, napi_ok);
}

void FFIFunction::CallWorker::OnOK() {
  try {
    call_.Complete(Env(), false);
  } catch (const Napi::Error& error) {
    OnError(error);
  } catch (const std::exception& error) {
    OnError(Napi::Error::New(Env(), error.what()));
  }
}

void FFIFunction::CallWorker::OnError(const Napi::Error& error) {
  call_.Reject(error.Value());
}

}  // namespace ctypes
