import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';

const root = new URL('../', import.meta.url);

test('blocking map-load presentation is throttled in every engine build', async () => {
  const [patch, wasmBuild, nativeBuild, sourceOffer] = await Promise.all([
    readFile(new URL('port/native/patches/0011-throttle-blocking-load-pacifier.patch', root), 'utf8'),
    readFile(new URL('tools/build-wasm.sh', root), 'utf8'),
    readFile(new URL('tools/build-native.sh', root), 'utf8'),
    readFile(new URL('tools/stage-source-offer.sh', root), 'utf8')
  ]);

  assert.match(patch, /minimumBlockingLoadFrameIntervalMsec = 100\.0f/);
  assert.match(patch, /static float Session_GetBlockingLoadFrameIntervalMsec/);
  assert.match(patch, /idImageManager::LoadLevelImages[\s\S]*if \( pacifier \)[\s\S]*session->PacifierUpdate\(\);/);
  assert.ok(patch.indexOf('session->PacifierUpdate();') < patch.indexOf('idImage\t*image = images[ i ];'),
    'image-load pacifier must run before retaining an image pointer');
  assert.match(patch, /requestAnimationFrame owns browser presentation pacing/);
  assert.match(patch, /Common_ResetPresentationThrottle\(\);[\s\S]*return;/);
  assert.match(patch, /Keep the[\s\S]*requestAnimationFrame scheduler throughout blocking browser map loads/);
  assert.match(patch, /static int R_GetEffectiveSwapIntervalForState[\s\S]*#if defined\( __EMSCRIPTEN__ \)[\s\S]*return configuredInterval;/);
  assert.doesNotMatch(patch, /idSessionLocal::Frame/);

  for (const build of [wasmBuild, nativeBuild, sourceOffer]) {
    assert.match(build, /0011-throttle-blocking-load-pacifier\.patch/);
  }
  assert.match(nativeBuild, /patch --batch --forward --no-backup-if-mismatch/);
});
