'use strict';

import { isBundleModeEnabled } from './debug/bundleMode';
import { getStaticFeatureFlag } from './featureFlags/featureFlags';
import { addNoBundleModeGuardImplementation } from './guardImplementation';
import {
  getMemorySafeCapturableConsole,
  setupConsole,
  setupConsoleForwarding,
  setupSerializer,
} from './initializers/initializers';
import {
  createSerializable,
  makeShareableCloneOnUIRecursive,
} from './memory/serializable';
import { serializableMappingCache } from './memory/serializableMappingCache';
import type { SerializableRef } from './memory/types';
import { setupRunLoop } from './runLoop/workletRuntime';
import { RuntimeKind } from './runtimeKind';
import type {
  WorkletFunction,
  WorkletRuntime,
  WorkletRuntimeConfig,
} from './types';
import { isWorkletFunction } from './workletFunction';
import { WorkletsModule } from './WorkletsModule/NativeWorklets';

const SHOULD_CAPTURE_SCHEDULE_STACK =
  __DEV__ && getStaticFeatureFlag('ENABLE_CROSS_RUNTIME_STACK_TRACES');

/**
 * The ID of the [UI Worklet
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#ui-runtime).
 */
export const UIRuntimeId = RuntimeKind.UI as 2;

/**
 * Lets you create a new JS runtime which can be used to run worklets possibly
 * on different threads than JS or UI thread.
 *
 * @param config - Runtime configuration object - {@link WorkletRuntimeConfig}.
 * @returns WorkletRuntime which is a
 *   `jsi::HostObject<worklets::WorkletRuntime>` - {@link WorkletRuntime}
 * @see https://docs.swmansion.com/react-native-worklets/docs/threading/createWorkletRuntime/
 */
// @ts-expect-error Public API overload.
export function createWorkletRuntime(
  config?: WorkletRuntimeConfig
): WorkletRuntime;

/**
 * @deprecated Please use the new config object signature instead:
 *   `createWorkletRuntime({ name, initializer })`
 *
 *   Lets you create a new JS runtime which can be used to run worklets possibly
 *   on different threads than JS or UI thread.
 * @param name - A name used to identify the runtime which will appear in
 *   devices list in Chrome DevTools.
 * @param initializer - An optional worklet that will be run synchronously on
 *   the same thread immediately after the runtime is created.
 * @returns WorkletRuntime which is a
 *   `jsi::HostObject<worklets::WorkletRuntime>` - {@link WorkletRuntime}
 * @see https://docs.swmansion.com/react-native-worklets/docs/threading/createWorkletRuntime/
 */
export function createWorkletRuntime(
  name?: string,
  initializer?: () => void
): WorkletRuntime;

export function createWorkletRuntime(
  nameOrConfig?: string | WorkletRuntimeConfigInternal,
  initializer?: WorkletFunction<[], void>
): WorkletRuntime {
  const runtimeBoundCapturableConsole =
    globalThis._WORKLETS_BUNDLE_MODE_ENABLED && !__DEV__
      ? null
      : getMemorySafeCapturableConsole();

  let name: string;
  let initializerFn: (() => void) | undefined;
  let queue: 'default' | object | null = 'default';
  let animationQueuePollingRate: number;
  let enableEventLoop = true;
  let enableLocking = true;
  let enableNetworking = true;
  if (typeof nameOrConfig === 'string') {
    name = nameOrConfig;
    initializerFn = initializer;
  } else {
    // TODO: Make anonymous name globally unique.
    name = nameOrConfig?.name ?? 'anonymous';
    initializerFn = nameOrConfig?.initializer;
    if (nameOrConfig?.queue !== undefined) {
      queue = nameOrConfig.queue;
    } else if (nameOrConfig?.useDefaultQueue === false) {
      queue = nameOrConfig.customQueue ?? null;
    }
    animationQueuePollingRate = Math.round(
      nameOrConfig?.animationQueuePollingRate ?? 16
    );
    enableLocking = nameOrConfig?.enableLocking ?? true;
    if (__DEV__ && !enableLocking && nameOrConfig?.enableEventLoop) {
      throw new Error(
        '[Worklets] The Event Loop cannot be enabled on a runtime with locking disabled.'
      );
    }
    enableEventLoop = enableLocking
      ? (nameOrConfig?.enableEventLoop ?? true)
      : false;
    /**
     * The networking API depends on the Event Loop - `whatwg-fetch` resolves
     * its responses through `setTimeout`. Without it, requests would hang
     * instead of failing visibly.
     */
    enableNetworking =
      (nameOrConfig?.enableNetworking ?? true) && enableEventLoop;
  }

  const useDefaultQueue = queue === 'default';
  const customQueue =
    typeof queue === 'object' && queue !== null ? queue : undefined;

  if (initializerFn && !isWorkletFunction(initializerFn)) {
    throw new Error(
      '[Worklets] The initializer passed to `createWorkletRuntime` is not a worklet.'
    );
  }

  return WorkletsModule.createWorkletRuntime(
    name,
    createSerializable(() => {
      'worklet';
      setupSerializer();
      if (!globalThis._WORKLETS_BUNDLE_MODE_ENABLED) {
        setupConsole(runtimeBoundCapturableConsole!);
      } else if (__DEV__) {
        setupConsoleForwarding(runtimeBoundCapturableConsole!);
      }
      if (enableEventLoop) {
        setupRunLoop(animationQueuePollingRate);
      }
      initializerFn?.();
    }),
    useDefaultQueue,
    customQueue,
    enableEventLoop,
    enableLocking,
    enableNetworking
  );
}

/**
 * Lets you asynchronously run a
 * [worklet](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#worklet)
 * on a [Worker
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime).
 *
 * Check
 * {@link https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds}
 * for more information about the different runtime kinds.
 *
 * - The worklet is scheduled on the Worker Runtime's [Async
 *   Queue](https://github.com/software-mansion/react-native-reanimated/blob/main/packages/react-native-worklets/Common/cpp/worklets/RunLoop/AsyncQueue.h)
 *
 * @param workletRuntime - The runtime to schedule the worklet on.
 * @param worklet - The worklet to schedule.
 * @param args - The arguments to pass to the worklet.
 * @returns The return value of the worklet.
 */
// @ts-expect-error This overload is correct since it's what user sees in their code
// before it's transformed by Worklets Babel plugin.
export function scheduleOnRuntime<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: (...args: Args) => ReturnValue,
  ...args: Args
): void;

export function scheduleOnRuntime<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: WorkletFunction<Args, ReturnValue>,
  ...args: Args
): void {
  if (__DEV__ && !isWorkletFunction(worklet)) {
    throw new Error(
      '[Worklets] The function passed to `scheduleOnRuntime` is not a worklet.'
    );
  }

  WorkletsModule.scheduleOnRuntime(
    workletRuntime,
    createSerializable(() => {
      'worklet';
      worklet(...args);
    }),
    SHOULD_CAPTURE_SCHEDULE_STACK ? new Error().stack : undefined
  );
}

if (!isBundleModeEnabled()) {
  function scheduleOnRuntimeWorklet<Args extends unknown[], ReturnValue>(
    workletRuntime: WorkletRuntime,
    worklet: WorkletFunction<Args, ReturnValue>,
    ...args: Args
  ): void {
    'worklet';
    if (__DEV__ && !isWorkletFunction(worklet)) {
      throw new Error(
        '[Worklets] The function passed to `scheduleOnRuntime` is not a worklet.'
      );
    }

    globalThis.__workletsModuleProxy.scheduleOnRuntime(
      workletRuntime,
      globalThis.__serializer(() => {
        'worklet';
        worklet(...args);
      })
    );
  }

  serializableMappingCache.set(
    scheduleOnRuntime,
    createSerializable(scheduleOnRuntimeWorklet)
  );
}

/**
 * Lets you asynchronously run a
 * [worklet](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#worklet)
 * on a [Worker
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime)
 * identified by the runtime's id.
 *
 * Check
 * {@link https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds}
 * for more information about the different runtime kinds.
 *
 * - The worklet is scheduled on the Worker Runtime's [Async
 *   Queue](https://github.com/software-mansion/react-native-reanimated/blob/main/packages/react-native-worklets/Common/cpp/worklets/RunLoop/AsyncQueue.h)
 *
 * @param runtimeId - The id of the runtime to schedule the worklet on.
 * @param worklet - The worklet to schedule.
 * @param args - The arguments to pass to the worklet.
 * @returns The return value of the worklet.
 */
// @ts-expect-error This overload is correct since it's what user sees in their code
// before it's transformed by Worklets Babel plugin.
export function scheduleOnRuntimeWithId<Args extends unknown[], ReturnValue>(
  runtimeId: number,
  worklet: (...args: Args) => ReturnValue,
  ...args: Args
): void;

export function scheduleOnRuntimeWithId<Args extends unknown[], ReturnValue>(
  runtimeId: number,
  worklet: WorkletFunction<Args, ReturnValue>,
  ...args: Args
): void {
  if (__DEV__ && !isWorkletFunction(worklet)) {
    throw new Error(
      '[Worklets] The function passed to `scheduleOnRuntimeWithId` is not a worklet.'
    );
  }

  WorkletsModule.scheduleOnRuntimeWithId(
    runtimeId,
    createSerializable(() => {
      'worklet';
      worklet(...args);
    }),
    SHOULD_CAPTURE_SCHEDULE_STACK ? new Error().stack : undefined
  );
}

if (!isBundleModeEnabled()) {
  function scheduleOnRuntimeWithIdWorklet<Args extends unknown[], ReturnValue>(
    runtimeId: number,
    worklet: WorkletFunction<Args, ReturnValue>,
    ...args: Args
  ): void {
    'worklet';
    if (__DEV__ && !isWorkletFunction(worklet)) {
      throw new Error(
        '[Worklets] The function passed to `scheduleOnRuntimeWithId` is not a worklet.'
      );
    }

    globalThis.__workletsModuleProxy.scheduleOnRuntimeWithId(
      runtimeId,
      globalThis.__serializer(() => {
        'worklet';
        worklet(...args);
      })
    );
  }

  serializableMappingCache.set(
    scheduleOnRuntimeWithId,
    createSerializable(scheduleOnRuntimeWithIdWorklet)
  );
}

/**
 * @deprecated Use `scheduleOnRuntime` instead.
 *
 *   Schedule a worklet to execute on the background queue.
 */
// @ts-expect-error This overload is correct since it's what user sees in their code
// before it's transformed by Worklets Babel plugin.
export function runOnRuntime<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: (...args: Args) => ReturnValue
): WorkletFunction<Args, ReturnValue>;

export function runOnRuntime<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: WorkletFunction<Args, ReturnValue>
): (...args: Args) => void {
  'worklet';
  if (__DEV__ && !isWorkletFunction(worklet)) {
    throw new Error(
      '[Worklets] The function passed to `runOnRuntime` is not a worklet.'
    );
  }
  return (...args) => scheduleOnRuntime(workletRuntime, worklet, ...args);
}

type WorkletRuntimeConfigInternal = WorkletRuntimeConfig & {
  initializer?: WorkletFunction<[], void>;
};

/**
 * Lets you run a function synchronously on a [Worker
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime).
 *
 * - This function cannot be called from the [UI
 *   Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#ui-runtime).
 *   or another [Worker
 *   Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime),
 *   unless the [Bundle
 *   Mode](https://docs.swmansion.com/react-native-worklets/docs/bundleMode/) is
 *   enabled.
 *
 * @param workletRuntime - The runtime to run the worklet on.
 * @param worklet - The worklet to run.
 * @param args - The arguments to pass to the worklet.
 * @returns The return value of the worklet.
 */
export function runOnRuntimeSync<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: (...args: Args) => ReturnValue,
  ...args: Args
): ReturnValue {
  if (__DEV__ && !isWorkletFunction(worklet)) {
    throw new Error(
      '[Worklets] The function passed to `runOnRuntimeSync` is not a worklet.'
    );
  }

  return WorkletsModule.runOnRuntimeSync(
    workletRuntime,
    createSerializable(() => {
      'worklet';
      const result = worklet(...args);
      return makeShareableCloneOnUIRecursive(result);
    }),
    SHOULD_CAPTURE_SCHEDULE_STACK ? new Error().stack : undefined
  );
}

/**
 * Lets you run a function synchronously on a [Worklet
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worklet-runtime)
 * identified by the runtime's id.
 *
 * - This function cannot be called from the [UI
 *   Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#ui-runtime)
 *   or a [Worker
 *   Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime),
 *   unless the [Bundle
 *   Mode](https://docs.swmansion.com/react-native-worklets/docs/bundleMode/) is
 *   enabled.
 * - You can target the UI Runtime with this function by passing
 *   {@link UIRuntimeId} as the `runtimeId` argument.
 *
 * @param runtimeId - The id of the runtime to run the worklet on.
 * @param worklet - The worklet to run.
 * @param args - The arguments to pass to the worklet.
 * @returns The return value of the worklet.
 */
// @ts-expect-error This overload is correct since it's what user sees in their code
// before it's transformed by Worklets Babel plugin.
export function runOnRuntimeSyncWithId<Args extends unknown[], ReturnValue>(
  runtimeId: number,
  worklet: (...args: Args) => ReturnValue,
  ...args: Args
): ReturnValue;

export function runOnRuntimeSyncWithId<Args extends unknown[], ReturnValue>(
  runtimeId: number,
  worklet: WorkletFunction<Args, ReturnValue>,
  ...args: Args
): ReturnValue {
  if (__DEV__ && !isWorkletFunction(worklet)) {
    throw new Error(
      '[Worklets] The function passed to `runOnRuntimeSyncWithId` is not a worklet.'
    );
  }

  return WorkletsModule.runOnRuntimeSyncWithId(
    runtimeId,
    createSerializable(() => {
      'worklet';
      const result = worklet(...args);
      return makeShareableCloneOnUIRecursive(result);
    }),
    SHOULD_CAPTURE_SCHEDULE_STACK ? new Error().stack : undefined
  );
}

/**
 * Lets you asynchronously run a
 * [worklet](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#worklet)
 * on a [Worker
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime)
 * and get the result via a Promise.
 *
 * - The worklet is scheduled on the Worker Runtime's Async Queue
 * - Returns a Promise that resolves with the worklet's return value
 *
 * @param workletRuntime - The runtime to run the worklet on.
 * @param worklet - The worklet to run.
 * @param args - The arguments to pass to the worklet.
 * @returns A Promise that resolves to the return value of the worklet.
 * @see https://docs.swmansion.com/react-native-worklets/docs/threading/runOnRuntimeAsync
 */
// @ts-expect-error This overload is correct since it's what user sees in their code
// before it's transformed by Worklets Babel plugin.
export function runOnRuntimeAsync<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: (...args: Args) => ReturnValue,
  ...args: Args
): Promise<ReturnValue>;

export function runOnRuntimeAsync<Args extends unknown[], ReturnValue>(
  workletRuntime: WorkletRuntime,
  worklet: WorkletFunction<Args, ReturnValue>,
  ...args: Args
): Promise<ReturnValue> {
  if (__DEV__) {
    if (!isWorkletFunction(worklet)) {
      throw new Error(
        '[Worklets] The function passed to `runOnRuntimeAsync` is not a worklet.'
      );
    }
  }

  return new Promise<ReturnValue>((resolve, reject) => {
    if (__DEV__) {
      createSerializable(worklet);
      createSerializable(args);
    }

    const scheduleStack = SHOULD_CAPTURE_SCHEDULE_STACK
      ? new Error().stack
      : undefined;

    WorkletsModule.scheduleOnRuntime(
      workletRuntime,
      createSerializable(() => {
        'worklet';
        try {
          const result = worklet(...args);
          const serializedResult = globalThis.__serializer(
            result
          ) as SerializableRef<ReturnValue>;
          globalThis.__workletsModuleProxy.handlePromise(
            resolve,
            serializedResult
          );
        } catch (error) {
          const serializedError = globalThis.__serializer(error);
          globalThis.__workletsModuleProxy.handlePromise(
            reject,
            serializedError
          );
        }
      }),
      scheduleStack
    );
  });
}

/**
 * Lets you asynchronously run a
 * [worklet](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#worklet)
 * on a [Worker
 * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds#worker-runtime)
 * identified by the runtime's id.
 *
 * Check
 * {@link https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds}
 * for more information about the different runtime kinds.
 *
 * - The worklet is scheduled on the Worker Runtime's [Async
 *   Queue](https://github.com/software-mansion/react-native-reanimated/blob/main/packages/react-native-worklets/Common/cpp/worklets/RunLoop/AsyncQueue.h)
 *
 * @param runtimeId - The id of the runtime to schedule the worklet on.
 * @param worklet - The worklet to schedule.
 * @param args - The arguments to pass to the worklet.
 * @returns The return value of the worklet.
 */
// @ts-expect-error This overload is correct since it's what user sees in their code
// before it's transformed by Worklets Babel plugin.
export function runOnRuntimeAsyncWithId<Args extends unknown[], ReturnValue>(
  runtimeId: number,
  worklet: (...args: Args) => ReturnValue,
  ...args: Args
): Promise<ReturnValue>;

export function runOnRuntimeAsyncWithId<Args extends unknown[], ReturnValue>(
  runtimeId: number,
  worklet: WorkletFunction<Args, ReturnValue>,
  ...args: Args
): Promise<ReturnValue> {
  if (__DEV__ && !isWorkletFunction(worklet)) {
    throw new Error(
      '[Worklets] The function passed to `runOnRuntimeAsyncWithId` is not a worklet.'
    );
  }

  return new Promise<ReturnValue>((resolve, reject) => {
    if (__DEV__) {
      createSerializable(worklet);
      createSerializable(args);
    }

    const scheduleStack = SHOULD_CAPTURE_SCHEDULE_STACK
      ? new Error().stack
      : undefined;

    WorkletsModule.scheduleOnRuntimeWithId(
      runtimeId,
      createSerializable(() => {
        'worklet';
        try {
          const result = worklet(...args);
          const serializedResult = globalThis.__serializer(
            result
          ) as SerializableRef<ReturnValue>;
          globalThis.__workletsModuleProxy.handlePromise(
            resolve,
            serializedResult
          );
        } catch (error) {
          const serializedError = globalThis.__serializer(error);
          globalThis.__workletsModuleProxy.handlePromise(
            reject,
            serializedError
          );
        }
      }),
      scheduleStack
    );
  });
}

if (__DEV__ && !isBundleModeEnabled()) {
  /**
   * QoL guards to give a meaningful error message when the user tries to call
   * these functions on Worklet Runtimes outside of the Bundle Mode.
   */
  addNoBundleModeGuardImplementation(runOnRuntimeAsync);
  addNoBundleModeGuardImplementation(runOnRuntimeAsyncWithId);
  addNoBundleModeGuardImplementation(runOnRuntimeSync);
  addNoBundleModeGuardImplementation(runOnRuntimeSyncWithId);
}

export function getUIRuntimeHolder(): object {
  return WorkletsModule.getUIRuntimeHolder();
}

export function getUISchedulerHolder(): object {
  return WorkletsModule.getUISchedulerHolder();
}
