#include <worklets/NativeModules/JSIWorkletsModuleProxy.h>
#include <worklets/WorkletRuntime/RuntimeData.h>
#include <worklets/WorkletRuntime/RuntimeManager.h>

#include <worklets/Compat/ReactNativeDebug.h>

#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

namespace worklets {

#ifndef NDEBUG
namespace {
void evaluateModuleUpdate(
    const std::shared_ptr<WorkletRuntime> &workletRuntime,
    const std::string &code,
    const std::string &sourceUrl) {
  workletRuntime->runSync([&code, &sourceUrl](jsi::Runtime &rt) -> void {
    const auto buffer = std::make_shared<jsi::StringBuffer>(code);
    rt.evaluateJavaScript(buffer, sourceUrl);
  });
}
} // namespace
#endif // NDEBUG

std::shared_ptr<WorkletRuntime> RuntimeManager::getRuntime(uint64_t runtimeId) {
  std::shared_lock lock(weakRuntimesMutex_);
  if (weakRuntimes_.contains(runtimeId)) {
    return weakRuntimes_.at(runtimeId).lock();
  }
  return nullptr;
}

std::vector<std::shared_ptr<WorkletRuntime>> RuntimeManager::getAllRuntimes() {
  std::shared_lock lock(weakRuntimesMutex_);

  std::vector<std::shared_ptr<WorkletRuntime>> runtimes;
  runtimes.reserve(weakRuntimes_.size());

  for (const auto &[id, weakRuntime] : weakRuntimes_) {
    if (auto runtime = weakRuntime.lock()) {
      if (runtime->isAborted()) [[unlikely]] {
        continue;
      }
      runtimes.push_back(runtime);
    }
  }

  return runtimes;
}

std::shared_ptr<WorkletRuntime> RuntimeManager::getUIRuntime() {
  return getRuntime(RuntimeData::uiRuntimeId);
}

bool RuntimeManager::isRuntimeAlive(RuntimeData::RuntimeId runtimeId) {
  std::shared_lock lock(weakRuntimesMutex_);
  return weakRuntimes_.contains(runtimeId);
}

std::shared_ptr<WorkletRuntime> RuntimeManager::createWorkletRuntime(
    const std::shared_ptr<const JSIWorkletsModuleProxy> &sourceProxy,
    const std::string &name,
    const std::shared_ptr<SerializableWorklet> &initializer,
    const std::shared_ptr<AsyncQueue> &queue,
    bool enableEventLoop,
    bool enableLocking,
    bool enableNetworking,
    bool abortable) {
  const auto runtimeId = getNextRuntimeId();

  const auto workletRuntime = std::make_shared<WorkletRuntime>(
      runtimeId,
      weak_from_this(),
      RuntimeData::RuntimeKind::Worker,
      name,
      queue,
      enableEventLoop,
      enableLocking,
      enableNetworking,
      abortable);
  const auto targetProxy = JSIWorkletsModuleProxy::createForNewRuntime(sourceProxy, runtimeId);

  workletRuntime->init(targetProxy);

#ifndef NDEBUG
  withRuntimeReadyPaused([&] { loadModuleUpdates(workletRuntime); });
#endif // NDEBUG

  if (initializer) {
    try {
      workletRuntime->runSyncAndDiscard(initializer);
    } catch (const jsi::JSError &error) {
      throw std::runtime_error(error.getMessage());
    }
  }

  onRuntimeReady(runtimeId, workletRuntime);

  return workletRuntime;
}

#ifndef NDEBUG
void RuntimeManager::propagateModuleUpdate(const std::string &code, const std::string &sourceUrl) {
  std::unique_lock runtimeReadyLock(runtimeReadyMutex_);

  moduleUpdates_.push_back(ModuleUpdate{.sourceUrl = sourceUrl, .code = code});

  for (const auto &runtime : getAllRuntimes()) {
    if (runtime->isLockingEnabled()) {
      evaluateModuleUpdate(runtime, code, sourceUrl);
    }
  }
}

void RuntimeManager::loadModuleUpdates(const std::shared_ptr<WorkletRuntime> &workletRuntime) {
  for (const auto &update : moduleUpdates_) {
    evaluateModuleUpdate(workletRuntime, update.code, update.sourceUrl);
  }
}
#endif // NDEBUG

std::shared_ptr<WorkletRuntime> RuntimeManager::createUninitializedUIRuntime(
    const std::shared_ptr<AsyncQueue> &uiAsyncQueue) {
  const auto uiRuntime = std::make_shared<WorkletRuntime>(
      RuntimeData::uiRuntimeId,
      weak_from_this(),
      RuntimeData::RuntimeKind::UI,
      RuntimeData::uiRuntimeName,
      uiAsyncQueue,
      /*enableEventLoop*/ false);

  onRuntimeReady(RuntimeData::uiRuntimeId, uiRuntime);

  return uiRuntime;
}

uint64_t RuntimeManager::getNextRuntimeId() {
  return nextRuntimeId_.fetch_add(1, std::memory_order_relaxed);
}

void RuntimeManager::onRuntimeCreated(RuntimeData::RuntimeId runtimeId) {
  std::unique_lock lock(weakRuntimesMutex_);
  weakRuntimes_.try_emplace(runtimeId);
}

void RuntimeManager::onRuntimeDestroyed(RuntimeData::RuntimeId runtimeId) {
  std::unique_lock lock(weakRuntimesMutex_);
  weakRuntimes_.erase(runtimeId);
}

void RuntimeManager::onRuntimeReady(const uint64_t runtimeId, const std::shared_ptr<WorkletRuntime> &workletRuntime) {
  std::unique_lock runtimeReadyLock(runtimeReadyMutex_);
  std::unique_lock lock(weakRuntimesMutex_);
  const auto it = weakRuntimes_.find(runtimeId);
  react_native_assert(it != weakRuntimes_.end() && "[Worklets] onRuntimeReady called before onRuntimeCreated.");
  if (it != weakRuntimes_.end()) {
    it->second = workletRuntime;
  }
}

} // namespace worklets
