import type {
  EngineEnvironment,
  EngineMode,
  EnginePreference,
} from './ffmpeg.types';

export function detectEngineEnvironment(
  scope: Window = window
): EngineEnvironment {
  return {
    secureContext: scope.isSecureContext === true,
    crossOriginIsolated: scope.crossOriginIsolated === true,
    sharedArrayBuffer: typeof globalThis.SharedArrayBuffer !== 'undefined',
    hardwareConcurrency: scope.navigator.hardwareConcurrency,
  };
}

export function supportsMultithread(environment: EngineEnvironment): boolean {
  return (
    environment.secureContext &&
    environment.crossOriginIsolated &&
    environment.sharedArrayBuffer
  );
}

export function selectEngineMode(
  environment: EngineEnvironment,
  preference: EnginePreference
): EngineMode {
  if (preference === 'force-single-thread') {
    return 'single-thread';
  }
  return supportsMultithread(environment) ? 'multithread' : 'single-thread';
}

export function describeEngineMode(mode: EngineMode): string {
  return mode === 'multithread'
    ? 'Multithreaded'
    : 'Single-threaded compatibility mode';
}
