/**
 * DreamStack Delta Codec — C port for ESP32-P4
 *
 * Ported from engine/ds-stream/src/codec.rs
 * Handles XOR+RLE delta decompression for the thin client.
 */

#pragma once
#include <stdint.h>
#include <stddef.h>

/**
 * RLE-decode a compressed delta buffer (in-place to output).
 *
 * Encoding: 0x00 followed by 2-byte LE count = zero run.
 * Non-zero bytes pass through literally.
 *
 * @param compressed  RLE-compressed data from relay
 * @param comp_len    Length of compressed data
 * @param output      Pre-allocated output buffer
 * @param out_cap     Capacity of output buffer
 * @return            Actual decoded length, or 0 on error
 */
size_t ds_rle_decode(const uint8_t *compressed, size_t comp_len,
                     uint8_t *output, size_t out_cap);

/**
 * Apply XOR delta to reconstruct current frame.
 *
 * framebuffer[i] ^= delta[i] for each byte.
 * Modifies framebuffer in-place.
 *
 * @param framebuffer  Current framebuffer (modified in-place)
 * @param delta        Decoded delta buffer
 * @param len          Length (must match for both buffers)
 */
void ds_xor_apply(uint8_t *framebuffer, const uint8_t *delta, size_t len);

/**
 * Decode an RLE-compressed delta and apply it to the framebuffer.
 * Convenience function combining rle_decode + xor_apply.
 *
 * Uses a scratch buffer for the intermediate decoded delta.
 *
 * @param framebuffer  Current framebuffer (modified in-place)
 * @param fb_len       Framebuffer length
 * @param compressed   RLE-compressed delta from relay
 * @param comp_len     Length of compressed data
 * @param scratch      Temporary buffer (must be >= fb_len)
 * @return             0 on success, -1 on error
 */
int ds_apply_delta_rle(uint8_t *framebuffer, size_t fb_len,
                       const uint8_t *compressed, size_t comp_len,
                       uint8_t *scratch);
