#include <zlib.h>

#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>

int main() try {
    if (std::string_view(zlibVersion()) != "1.4") {
        throw std::runtime_error("This demo pins zlib 1.4");
    }

    std::string svg = R"(<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 16" stroke="black" fill="none">)";
    for (int x = 0; x < 128; x += 2) {
        svg += "<path d=\"M" + std::to_string(x) + " 0v16\"/>";
    }
    svg += "</svg>";
    const auto* input = reinterpret_cast<const Bytef*>(svg.data());
    const auto inputSize = static_cast<uLong>(svg.size());
    uLongf compressedSize = compressBound(inputSize);
    std::vector<Bytef> compressed(compressedSize);
    if (compress2(compressed.data(), &compressedSize, input, inputSize, 6) != Z_OK) {
        throw std::runtime_error("Could not compress SVG");
    }

    // This local fixture has a known size. Bound the output buffer to that size.
    std::string decoded(svg.size(), '\0');
    auto* output = reinterpret_cast<Bytef*>(decoded.data());
    uLongf decodedSize = static_cast<uLongf>(decoded.size());
    uLong consumedSize = compressedSize;
    if (uncompress2(output, &decodedSize, compressed.data(), &consumedSize) != Z_OK ||
        decodedSize != inputSize || consumedSize != compressedSize || decoded != svg) {
        throw std::runtime_error("Round trip mismatch");
    }

    // Flip one bit in the zlib wrapper's trailing Adler-32 field.
    compressed[compressedSize - 1] ^= 1;
    decodedSize = static_cast<uLongf>(decoded.size());
    consumedSize = compressedSize;
    const int status = uncompress2(output, &decodedSize, compressed.data(), &consumedSize);

    std::cout << "zlib " << zlibVersion() << '\n'
              << "svg_bytes=" << svg.size() << " compressed_bytes=" << compressedSize << '\n'
              << "roundtrip=equal crc32=" << std::hex << std::setfill('0') << std::setw(8)
              << crc32(0L, input, static_cast<uInt>(inputSize)) << '\n'
              << "changed_trailer=" << (status == Z_DATA_ERROR ? "Z_DATA_ERROR" : "unexpected")
              << '\n';
    return status == Z_DATA_ERROR ? 0 : 1;
} catch (const std::exception& error) {
    std::cerr << error.what() << '\n';
    return 1;
}
