///|
pub suberror ArchiveError {
  InvalidIndex(String)
  InvalidRange
  InvalidFrame(Int32, String)
  ChecksumMismatch(Int32)
  LimitExceeded(String)
  SourceError(String)
  SinkError(String)
}

///|
/// The callback reads exactly the requested bytes from an immutable snapshot.
pub struct Source {
  length : Int64
  read_at : (Int64, Int32) -> Bytes raise
}

///|
pub fn Source::new(
  length : Int64,
  read_at : (Int64, Int32) -> Bytes raise,
) -> Source {
  { length, read_at, }
}

///|
pub fn Source::from_bytes(bytes : Bytes) -> Source {
  Source::new(bytes.length().to_int64(), (offset, size) => {
    let start = offset.to_int()
    bytes[start:start + size].to_owned()
  })
}

///|
fn Source::read(
  self : Source,
  offset : Int64,
  size : Int32,
) -> Bytes raise ArchiveError {
  guard offset >= 0L &&
    size >= 0 &&
    offset <= self.length &&
    size.to_int64() <= self.length - offset else {
    raise SourceError("read outside the source")
  }
  let data = (self.read_at)(offset, size) catch {
    err => raise SourceError(err.to_string())
  }
  guard data.length() == size else { raise SourceError("short read") }
  data
}

///|
pub(all) struct Entry {
  compressed_size : UInt32
  plain_size : UInt32
  checksum : UInt32?
}

///|
pub struct Frame {
  compressed_offset : Int64
  plain_offset : Int64
  entry : Entry
}

///|
pub struct Archive {
  priv source : Source
  priv frames : Array[Frame]
  priv plain_size : Int64
  priv checksums : Bool
}

///|
pub fn Archive::plain_size(self : Archive) -> Int64 {
  self.plain_size
}

///|
pub fn Archive::frame_count(self : Archive) -> Int32 {
  self.frames.length()
}

///|
pub fn Archive::frame(self : Archive, index : Int32) -> Frame? {
  self.frames.get(index)
}

///|
let table_magic : UInt32 = 0x184d2a5e

///|
let footer_magic : UInt32 = 0x8f92eab1

///|
fn load32(bytes : BytesView, pos : Int32) -> UInt32 {
  bytes[pos].to_uint() |
  (bytes[pos + 1].to_uint() << 8) |
  (bytes[pos + 2].to_uint() << 16) |
  (bytes[pos + 3].to_uint() << 24)
}

///|
pub fn encode_table(
  entries : Array[Entry],
  checksums~ : Bool = true,
) -> Bytes raise ArchiveError {
  let width = if checksums { 12 } else { 8 }
  guard entries.length() <= (0x7fffffff - 17) / width else {
    raise LimitExceeded("table is too large for a Bytes value")
  }
  let out = @buffer.Buffer()
  out.write_uint_le(table_magic)
  out.write_uint_le((entries.length() * width + 9).reinterpret_as_uint())
  for i, entry in entries {
    guard entry.compressed_size >= 8U else {
      raise InvalidFrame(i, "invalid compressed size")
    }
    out.write_uint_le(entry.compressed_size)
    out.write_uint_le(entry.plain_size)
    if checksums {
      guard entry.checksum is Some(digest) else {
        raise InvalidFrame(i, "missing checksum")
      }
      out.write_uint_le(digest)
    }
  }
  out.write_uint_le(entries.length().reinterpret_as_uint())
  out.write_byte(if checksums { b'\x80' } else { b'\x00' })
  out.write_uint_le(footer_magic)
  out.to_bytes()
}

///|
/// Wrap frames supplied by a codec. Each pair is (compressed, uncompressed).
pub fn pack_frames(
  frames : Array[(Bytes, Bytes)],
  checksums~ : Bool = true,
) -> Bytes raise ArchiveError {
  let entries = frames.map(pair => {
    let (compressed, plain) = pair
    {
      compressed_size: compressed.length().reinterpret_as_uint(),
      plain_size: plain.length().reinterpret_as_uint(),
      checksum: if checksums {
        Some(checksum32(plain[:]))
      } else {
        None
      },
    }
  })
  let table = encode_table(entries, checksums~)
  let mut total = table.length().to_int64()
  for entry in entries {
    total += entry.compressed_size.to_int64()
    guard total <= 0x7fffffffL else {
      raise LimitExceeded("archive is too large for a Bytes value")
    }
  }
  let out = @buffer.Buffer()
  for pair in frames {
    out.write_bytes(pair.0[:])
  }
  out.write_bytes(table[:])
  out.to_bytes()
}

///|
/// Read the footer and the preceding table bytes. No data frames are read.
pub fn Archive::open(
  source : Source,
  max_frames~ : Int32 = default_max_frames,
) -> Archive raise ArchiveError {
  guard source.length >= 17L else {
    raise InvalidIndex("missing or truncated footer")
  }
  let footer = source.read(source.length - 9L, 9)
  guard load32(footer[:], 5) == footer_magic else {
    raise InvalidIndex("wrong footer magic")
  }
  let descriptor = footer[4].to_uint()
  guard (descriptor & 0x7cU) == 0U else {
    raise InvalidIndex("reserved descriptor bits are set")
  }
  let checksums = (descriptor & 0x80U) != 0U
  let width = if checksums { 12 } else { 8 }
  let count = load32(footer[:], 0).to_int64()
  let preceding_size = 8L + count * width.to_int64()
  let payload_size = preceding_size + 1L
  let table_offset = source.length - 9L - preceding_size
  guard table_offset >= 0L && payload_size <= 0xffffffffL else {
    raise InvalidIndex("table does not fit in the source")
  }
  guard count <= max_frames.to_int64() && preceding_size <= 0x7fffffffL else {
    raise LimitExceeded("table exceeds the configured frame limit")
  }
  let preceding = source.read(table_offset, preceding_size.to_int())
  guard load32(preceding[:], 0) == table_magic &&
    load32(preceding[:], 4).to_int64() == payload_size else {
    raise InvalidIndex("invalid seek-table frame header")
  }
  let frames = Array(capacity=count.to_int())
  let mut compressed_offset = 0L
  let mut plain_offset = 0L
  for i in 0..= 8U &&
      compressed_size.to_int64() <= table_offset - compressed_offset else {
      raise InvalidFrame(
        i, "compressed size exceeds the data area or is too small",
      )
    }
    let checksum = if checksums {
      Some(load32(preceding[:], pos + 8))
    } else {
      None
    }
    frames.push({
      compressed_offset,
      plain_offset,
      entry: { compressed_size, plain_size, checksum, },
    })
    compressed_offset += compressed_size.to_int64()
    plain_offset += plain_size.to_int64()
  }
  guard compressed_offset == table_offset else {
    raise InvalidIndex("compressed sizes do not cover the data area")
  }
  { source, frames, plain_size: plain_offset, checksums, }
}

///|
fn Archive::first_frame_after(self : Archive, offset : Int64) -> Int32 {
  let mut lo = 0
  let mut hi = self.frames.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    let frame = self.frames[mid]
    if frame.plain_offset + frame.entry.plain_size.to_int64() <= offset {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  lo
}

///|
/// The decoder must consume exactly one frame and honor the given output bound.
pub fn Archive::extract(
  self : Archive,
  offset : Int64,
  length : Int32,
  decode : (BytesView, Int32) -> Bytes raise,
  max_frame_bytes~ : Int32 = default_frame_limit,
) -> Bytes raise ArchiveError {
  guard offset >= 0L &&
    offset <= self.plain_size &&
    length >= 0 &&
    length.to_int64() <= self.plain_size - offset else {
    raise InvalidRange
  }
  if length == 0 {
    return b""
  }
  let end = offset + length.to_int64()
  let out = @buffer.Buffer()
  for i in self.first_frame_after(offset)..= end {
      break
    }
    let entry = frame.entry
    if entry.plain_size == 0U {
      continue
    }
    guard entry.compressed_size.to_int64() <= max_frame_bytes.to_int64() &&
      entry.plain_size.to_int64() <= max_frame_bytes.to_int64() else {
      raise LimitExceeded("selected frame exceeds the configured byte limit")
    }
    let compressed = self.source.read(
      frame.compressed_offset,
      entry.compressed_size.to_int64().to_int(),
    )
    let plain = decode(compressed[:], entry.plain_size.to_int64().to_int()) catch {
      err => raise InvalidFrame(i, err.to_string())
    }
    guard plain.length().to_int64() == entry.plain_size.to_int64() else {
      raise InvalidFrame(
        i,
        "decoded size disagrees with the index: expected \{entry.plain_size}, got \{plain.length()}",
      )
    }
    if entry.checksum is Some(digest) && checksum32(plain[:]) != digest {
      raise ChecksumMismatch(i)
    }
    let start_in_frame = (offset.max(plain_start) - plain_start).to_int()
    let end_in_frame = (end - plain_start)
      .min(plain.length().to_int64())
      .to_int()
    out.write_bytes(plain[start_in_frame:end_in_frame])
  }
  out.to_bytes()
}

///|
let default_max_frames = 1_000_000

///|
pub fn Archive::has_checksums(self : Archive) -> Bool {
  self.checksums
}

///|
/// Describe an archive error including the affected frame when available.
pub fn ArchiveError::describe(self : ArchiveError) -> String {
  match self {
    InvalidIndex(detail) => "InvalidIndex: \{detail}"
    InvalidRange => "InvalidRange: byte range is outside the archive"
    InvalidFrame(index, detail) => "InvalidFrame: frame \{index}: \{detail}"
    ChecksumMismatch(index) =>
      "ChecksumMismatch: frame \{index}: seek-table checksum failed"
    LimitExceeded(detail) => "LimitExceeded: \{detail}"
    SourceError(detail) => "SourceError: \{detail}"
    SinkError(detail) => "SinkError: \{detail}"
  }
}

///|
/// Report a failed write from a streaming archive sink.
pub fn ArchiveError::sink_error(detail : String) -> ArchiveError {
  SinkError(detail)
}