import sharp from "sharp";
const PNG_SIGNATURE = Buffer.from([
    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
]);
/**
 * Drop C2PA (`caBX`) chunks from a PNG byte stream. Every other chunk —
 * IHDR, IDAT, IEND, ancillary metadata — is copied byte-for-byte, CRCs
 * included, so pixel data is untouched. If the buffer is not a valid
 * PNG or is malformed mid-stream, the input is returned unchanged.
 */
export function stripC2paFromPng(data) {
    if (data.length < 8 || !data.subarray(0, 8).equals(PNG_SIGNATURE)) {
        return data;
    }
    const parts = [data.subarray(0, 8)];
    let i = 8;
    let sawIend = false;
    while (i + 8 <= data.length) {
        const length = data.readUInt32BE(i);
        const chunkEnd = i + 12 + length; // 4 len + 4 type + N data + 4 CRC
        if (chunkEnd > data.length) {
            // Truncated chunk — bail out and hand back the original buffer
            // rather than emit a corrupt PNG.
            return data;
        }
        const type = data.subarray(i + 4, i + 8).toString("ascii");
        if (type !== "caBX") {
            parts.push(data.subarray(i, chunkEnd));
        }
        i = chunkEnd;
        if (type === "IEND") {
            sawIend = true;
            break;
        }
    }
    if (!sawIend)
        return data;
    return Buffer.concat(parts);
}
/**
 * Decode the PNG and re-encode as JPEG quality 85. Lossy re-compression
 * disturbs pixel-domain watermarks; the decode/encode round-trip also
 * drops any non-pixel metadata that survived the chunk strip. Alpha is
 * flattened to white since JPEG has no transparency.
 */
export async function pngToJpegQ85(pngBuffer) {
    return sharp(pngBuffer)
        .flatten({ background: { r: 255, g: 255, b: 255 } })
        .jpeg({ quality: 85, mozjpeg: false })
        .toBuffer();
}
/**
 * End-to-end post-process: strip C2PA, then JPEG-recompress. Returns the
 * new bytes plus the file extension to use ("jpg" on success, "png" if
 * we had to fall back). On strip success but encode failure, callers
 * still benefit from the C2PA-free PNG.
 */
export async function sanitizeGeneratedImage(raw) {
    let stripped;
    try {
        stripped = stripC2paFromPng(raw);
    }
    catch (err) {
        return {
            buffer: raw,
            ext: "png",
            note: `c2pa-strip failed: ${err instanceof Error ? err.message : String(err)}`,
        };
    }
    try {
        const jpeg = await pngToJpegQ85(stripped);
        return { buffer: jpeg, ext: "jpg" };
    }
    catch (err) {
        return {
            buffer: stripped,
            ext: "png",
            note: `jpeg-reencode failed: ${err instanceof Error ? err.message : String(err)}`,
        };
    }
}
//# sourceMappingURL=image-postprocess.js.map