// Copyright 2026 Leo Cheng
// SPDX-License-Identifier: Apache-2.0

///|
/// Open compressor contract allowing codecs to be swapped or registered uniformly.
pub(open) trait Compressor {
  fn name(Self) -> String
  fn compress(Self, BytesView) -> Bytes raise Refused
}

///|
/// Open decompressor contract with streaming/output limit enforcement.
pub(open) trait Decompressor {
  fn name(Self) -> String
  fn decompress(Self, BytesView, limit~ : Int32) -> Bytes raise Refused
}

///|
/// Registry of named compressors and decompressors for DIY codec extensions.
pub struct Registry {
  priv compressors : Map[String, &Compressor]
  priv decompressors : Map[String, &Decompressor]
}

///|
/// Creates an empty codec registry.
pub fn Registry::new() -> Registry {
  { compressors: Map([]), decompressors: Map([]), }
}

///|
/// Registers a compressor under its `name()`.
pub fn Registry::register_compressor(
  self : Registry,
  codec : &Compressor,
) -> Unit {
  self.compressors[codec.name()] = codec
}

///|
/// Registers a decompressor under its `name()`.
pub fn Registry::register_decompressor(
  self : Registry,
  codec : &Decompressor,
) -> Unit {
  self.decompressors[codec.name()] = codec
}

///|
/// Registers a codec that implements both `Compressor` and `Decompressor`.
pub fn[C : Compressor + Decompressor] Registry::register(
  self : Registry,
  codec : C,
) -> Unit {
  self.register_compressor(codec)
  self.register_decompressor(codec)
}

///|
/// Returns true when a compressor with `name` is registered.
pub fn Registry::has_compressor(self : Registry, name : String) -> Bool {
  self.compressors.contains(name)
}

///|
/// Returns true when a decompressor with `name` is registered.
pub fn Registry::has_decompressor(self : Registry, name : String) -> Bool {
  self.decompressors.contains(name)
}

///|
/// Compresses `input` using the registered compressor named `name`.
pub fn Registry::compress(
  self : Registry,
  name : String,
  input : BytesView,
) -> Bytes raise Refused {
  match self.compressors.get(name) {
    Some(c) => c.compress(input)
    None => raise Refused::Header(at=0, what="unknown codec: " + name)
  }
}

///|
/// Decompresses `input` using the registered decompressor named `name`, bounded by `limit`.
pub fn Registry::decompress(
  self : Registry,
  name : String,
  input : BytesView,
  limit~ : Int32 = 16 << 20,
) -> Bytes raise Refused {
  match self.decompressors.get(name) {
    Some(d) => d.decompress(input, limit~)
    None => raise Refused::Header(at=0, what="unknown codec: " + name)
  }
}