export async function loadBinary(url) {
    const response = await fetch(url);
    if (!response.ok) throw new Error("Failed to load " + url);
    const buffer = await response.arrayBuffer();
    return buffer;
}

// Loads MNIST 28x28 grayscale images + labels
export async function loadMNIST() {
    const imgBuf = await loadBinary("/models/MNIST-2k-images.bin");
    const lblBuf = await loadBinary("/models/MNIST-2k-labels.bin");

    const images = new Float32Array(imgBuf); // already normalized [0..1]
    const labels = new Uint8Array(lblBuf);

    const sampleCount = labels.length;
    console.log("MNIST Loaded:", sampleCount, "samples");

    return { images, labels, sampleCount };
}

// Utility visualization helper for debugging
export function showImage(img784, canvas) {
    const size = 28;
    canvas.width = size;
    canvas.height = size;

    const ctx = canvas.getContext("2d");
    const imgData = ctx.createImageData(size, size);

    for (let i = 0; i < size * size; i++) {
        const v = Math.floor(img784[i] * 255);
        imgData.data[i * 4 + 0] = v;
        imgData.data[i * 4 + 1] = v;
        imgData.data[i * 4 + 2] = v;
        imgData.data[i * 4 + 3] = 255;
    }

    ctx.putImageData(imgData, 0, 0);
}
