export async function sniffBlobMediaKind(blob, { path = "", contentType = "" } = {}) {
  const type = String(contentType || blob?.type || "").toLowerCase();
  if (type.startsWith("video/")) return "video";
  if (type.startsWith("image/")) return "image";

  const lowerPath = String(path).toLowerCase();
  if (
    lowerPath.includes("video") ||
    lowerPath.endsWith(".mp4") ||
    lowerPath.endsWith(".webm") ||
    lowerPath.endsWith(".mov")
  ) {
    return "video";
  }

  if (!(blob instanceof Blob)) return "image";

  return sniffBytesMediaKind(blob);
}

export async function sniffBytesMediaKind(blob) {
  if (!(blob instanceof Blob)) return "image";

  try {
    const head = new Uint8Array(await blob.slice(0, 16).arrayBuffer());
    if (head.length < 4) return "image";

    if (head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) {
      return "video";
    }

    if (head.length >= 8) {
      const boxType = String.fromCharCode(head[4], head[5], head[6], head[7]);
      if (boxType === "ftyp") return "video";
    }

    if (
      head.length >= 12 &&
      head[0] === 0x52 &&
      head[1] === 0x49 &&
      head[2] === 0x46 &&
      head[3] === 0x46
    ) {
      const form = String.fromCharCode(head[8], head[9], head[10], head[11]);
      if (form === "AVI ") return "video";
      if (form === "WEBP") return "image";
    }

    if (head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return "image";
    if (head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47) {
      return "image";
    }
  } catch {
    /* fall through */
  }

  return "image";
}
