#pragma once
#include <cstdint>
#include <vector>

namespace bmp2tile
{

// A permissively-licensed implementation of Jorgen Ibsen's aPLib
// compression format -- devkitSMS's UNSAFE_SMS_loadaPLibcompressedTiles/
// SMS_decompressaPLib expect exactly this bitstream.
//
// This is a hybrid port, not a line-for-line translation of any single
// source, because none of the available reference implementations were a
// clean fit on their own:
//   - Ibsen's own aPLib is not permissively licensed for this use.
//   - svendahl/cap's "aplibsharp" (MIT) and emmanuel-marty/apultra (zlib
//     + CC0 for its match-finder) both produce genuinely optimal aPLib
//     streams, but both do it via a real suffix-array-based optimal
//     parser -- apultra alone pulls in ~2200 lines of libdivsufsort on
//     top of its own ~3400. That's a lot of intricate, hard-to-verify
//     code for a feature this project doesn't strictly need to be
//     optimal, just correct.
//
// So the format-defining parts -- the bit-cost/validity rules for each
// encoding, the state (repeat-offset / "last write was a match")
// tracking, and the actual bit emission -- are faithfully ported from
// aplibsharp's model.cs/state.cs/tobinary.cs (cross-checked against
// apultra's format.h, which independently defines the same offset
// thresholds -- 128/1280/32000 -- confirming both target the same real,
// standard aPLib bitstream, not a variant). The *search* for what to
// encode (aplibsharp's esa.cs/path.cs/cstates.cs/dstates.cs, apultra's
// libdivsufsort-based one) is deliberately NOT ported -- it's replaced
// with a simple hash-chain match finder plus a greedy left-to-right
// parse, the same style already used for ZX7 in this project. Any
// correct match finder produces valid, decoder-compatible output; a
// simpler one just compresses a little worse. That's the trade this
// project is making here: real format compatibility, without importing
// thousands of lines of suffix-array construction.
//
// Verified by porting a matching decoder (aplibsharp's decode.cs) purely
// as a local test oracle -- not shipped, since devkitSMS supplies its
// own -- and round-trip fuzz testing thousands of random inputs through
// it, in addition to hand-traced small cases.
std::vector<uint8_t> CompressApLib(const std::vector<uint8_t>& input);

}  // namespace bmp2tile
