// Ported from crates/malice-core/src/media.rs's attachment_content_type, so the
// service worker can sniff decrypted bytes without a round trip to the wasm host.

function startsWith(bytes: Uint8Array, prefix: number[]): boolean {
  if (bytes.length < prefix.length) return false;
  for (let i = 0; i < prefix.length; i++) {
    if (bytes[i] !== prefix[i]) return false;
  }
  return true;
}

function ascii(text: string): number[] {
  return Array.from(text, (ch) => ch.charCodeAt(0));
}

function bytesEqual(bytes: Uint8Array, offset: number, text: string): boolean {
  const wanted = ascii(text);
  if (bytes.length < offset + wanted.length) return false;
  for (let i = 0; i < wanted.length; i++) {
    if (bytes[offset + i] !== wanted[i]) return false;
  }
  return true;
}

export function imageContentType(bytes: Uint8Array): string | null {
  if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png';
  if (startsWith(bytes, [0xff, 0xd8, 0xff])) return 'image/jpeg';
  if (bytesEqual(bytes, 0, 'GIF87a') || bytesEqual(bytes, 0, 'GIF89a')) return 'image/gif';
  if (bytes.length >= 12 && bytesEqual(bytes, 0, 'RIFF') && bytesEqual(bytes, 8, 'WEBP')) return 'image/webp';
  if (bytes.length >= 12 && bytesEqual(bytes, 4, 'ftyp') && (bytesEqual(bytes, 8, 'avif') || bytesEqual(bytes, 8, 'avis'))) {
    return 'image/avif';
  }
  return null;
}

export function attachmentContentType(bytes: Uint8Array): string | null {
  const image = imageContentType(bytes);
  if (image) return image;
  if (startsWith(bytes, [0x1a, 0x45, 0xdf, 0xa3])) return 'video/webm';
  if (bytes.length >= 12 && bytesEqual(bytes, 0, 'RIFF') && bytesEqual(bytes, 8, 'WAVE')) return 'audio/wav';
  if (bytesEqual(bytes, 0, 'OggS')) return 'audio/ogg';
  if (bytesEqual(bytes, 0, 'ID3') || startsWith(bytes, [0xff, 0xfb])) return 'audio/mpeg';
  if (
    bytes.length >= 12 &&
    bytesEqual(bytes, 4, 'ftyp') &&
    ['isom', 'iso2', 'mp41', 'mp42', 'avc1'].some((brand) => bytesEqual(bytes, 8, brand))
  ) {
    return 'video/mp4';
  }
  return null;
}
