export const BUNDLED_CONTACT_SHEET_FONT = Object.freeze({
  family: 'DejaVu Sans',
  fileName: 'DejaVuSans.ttf',
  byteLength: 757_076,
  sha256: '7da195a74c55bef988d0d48f9508bd5d849425c1770dba5d7bfc6ce9ed848954',
  licenseFile: 'LICENSES/DEJAVU_FONTS.txt',
});

let fontPromise: Promise<File> | undefined;

/**
 * Loads the same-origin reviewed font and verifies its release identity before
 * it is mounted read-only for FFmpeg. A failed check is never silently replaced
 * with a system or remote font.
 */
export function loadBundledContactSheetFont(): Promise<File> {
  fontPromise ??= loadAndVerifyFont().catch((error: unknown) => {
    fontPromise = undefined;
    throw error;
  });
  return fontPromise;
}

async function loadAndVerifyFont(): Promise<File> {
  const response = await fetch(
    `${import.meta.env.BASE_URL}fonts/${BUNDLED_CONTACT_SHEET_FONT.fileName}`,
    {
      cache: 'force-cache',
      credentials: 'same-origin',
    }
  );
  if (!response.ok) {
    throw new Error(
      `The bundled contact-sheet font could not be loaded (${response.status}).`
    );
  }
  const bytes = new Uint8Array(await response.arrayBuffer());
  if (bytes.byteLength !== BUNDLED_CONTACT_SHEET_FONT.byteLength) {
    throw new Error('The bundled contact-sheet font has an unexpected size.');
  }
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  const sha256 = [...new Uint8Array(digest)]
    .map((value) => value.toString(16).padStart(2, '0'))
    .join('');
  if (sha256 !== BUNDLED_CONTACT_SHEET_FONT.sha256) {
    throw new Error(
      'The bundled contact-sheet font failed its SHA-256 identity check.'
    );
  }
  return new File([bytes], BUNDLED_CONTACT_SHEET_FONT.fileName, {
    type: 'font/ttf',
    lastModified: 0,
  });
}
