///|
/// The number of bytes of a frame header.
pub const FRAME_HEADER_LENGTH : Int32 = 16

///|
/// The version of the frame format that this library reads and writes.
pub const FRAME_VERSION : UInt32 = 1

///|
/// The mark at the start of each frame: the bytes "MLWF".
let frame_mark : UInt32 = 0x46574C4D

///|
/// The largest frame limit: 1 GiB.
let largest_frame_limit : Int32 = 1073741824

///|
/// The largest body of a frame that a reader accepts. A reader checks the length in the
/// header against the limit before it reads the body.
#derive(Eq, Debug)
pub struct FrameLimit {
  priv bytes : Int32
}

///|
pub extend FrameLimit with Eq::{equal, not_equal}

///|
pub extend FrameLimit with @debug.Debug::{to_repr}

///|
/// A limit of `count` bytes, from 1 byte to 1 GiB.
pub fn FrameLimit::bytes(count : Int32) -> FrameLimit raise FrameError {
  guard count >= 1 && count <= largest_frame_limit else {
    raise InvalidLimit(count)
  }
  { bytes: count, }
}

///|
/// The default limit: 16 MiB.
pub fn FrameLimit::default() -> FrameLimit {
  { bytes: 16 * 1024 * 1024, }
}

///|
/// The number of bytes.
pub fn FrameLimit::to_bytes(self : FrameLimit) -> Int32 {
  self.bytes
}

///|
/// One message between a host and a worker process (WRK-2). There is one call at a
/// time, so a frame has no identifier. The log frames of a call come before its reply.
#derive(Eq, Debug)
pub(all) enum Frame {
  /// A call of the host, with the request bytes of the contract.
  Call(Operation, Bytes)
  /// The reply of the worker, with the response bytes of the contract.
  Reply(Status, Bytes)
  /// A log entry of the plugin. `Critical` goes as `Error`, because the ABI has five
  /// levels.
  Log(@logging.Level, String)
  /// The plugin asks for a tick.
  Wake
}

///|
pub extend Frame with Eq::{equal, not_equal}

///|
pub extend Frame with @debug.Debug::{to_repr}

///|
/// The kind of a frame, as its header gives it.
#derive(Eq, Debug)
pub(all) enum FrameKind {
  Call
  Reply
  Log
  Wake
}

///|
pub extend FrameKind with Eq::{equal, not_equal}

///|
pub extend FrameKind with @debug.Debug::{to_repr}

///|
fn FrameKind::code(self : FrameKind) -> UInt32 {
  match self {
    Call => 1
    Reply => 2
    Log => 3
    Wake => 4
  }
}

///|
/// The name of the kind: `call`, `reply`, `log` or `wake`.
pub fn FrameKind::name(self : FrameKind) -> String {
  match self {
    Call => "call"
    Reply => "reply"
    Log => "log"
    Wake => "wake"
  }
}

///|
/// The kind of the frame.
pub fn Frame::kind(self : Frame) -> FrameKind {
  match self {
    Call(_, _) => Call
    Reply(_, _) => Reply
    Log(_, _) => Log
    Wake => Wake
  }
}

///|
fn operation_code(operation : Operation) -> UInt32 {
  match operation {
    Describe => 0
    Start => 1
    Handle => 2
    Tick => 3
    Stop => 4
  }
}

///|
fn level_code(level : @logging.Level) -> UInt32 {
  match level {
    Trace => 0
    Debug => 1
    Information => 2
    Warning => 3
    Error | Critical => 4
  }
}

///|
/// The frame as bytes: the header, then the body.
pub fn Frame::encode(self : Frame) -> Bytes {
  let (kind, code, body) = match self {
    Call(operation, request) =>
      (FrameKind::Call, operation_code(operation), request)
    Reply(status, response) => (Reply, status.code(), response)
    Log(level, text) => (Log, level_code(level), @utf8.encode(text))
    Wake => (Wake, 0, b"")
  }
  let out = @buffer.Buffer(capacity=FRAME_HEADER_LENGTH + body.length())
  out.write_uint_le(frame_mark)
  out.write_uint16_le(FRAME_VERSION.to_uint16())
  out.write_uint16_le(kind.code().to_uint16())
  out.write_uint_le(code)
  out.write_uint_le(body.length().reinterpret_as_uint())
  out.write_bytesview(body[:])
  out.to_bytes()
}

///|
fn read_u16(bytes : BytesView, at : Int32) -> UInt32 {
  bytes[at].to_uint() | (bytes[at + 1].to_uint() << 8)
}

///|
fn read_u32_view(bytes : BytesView, at : Int32) -> UInt32 {
  read_u16(bytes, at) | (read_u16(bytes, at + 2) << 16)
}

///|
/// The header of a frame, after its checks. The body has `length()` bytes.
#derive(Eq, Debug)
pub struct FrameHeader {
  priv kind : FrameKind
  priv code : UInt32
  priv length : Int32
}

///|
pub extend FrameHeader with Eq::{equal, not_equal}

///|
pub extend FrameHeader with @debug.Debug::{to_repr}

///|
/// Read a header of `FRAME_HEADER_LENGTH` bytes. It checks the mark, the version, the
/// kind and the length, so a reader allocates no body over `limit`.
pub fn FrameHeader::decode(
  bytes : BytesView,
  limit : FrameLimit,
) -> FrameHeader raise FrameError {
  guard bytes.length() == FRAME_HEADER_LENGTH else {
    raise WrongHeaderLength(bytes.length())
  }
  let mark = read_u32_view(bytes, 0)
  guard mark == frame_mark else { raise WrongMark(mark) }
  let version = read_u16(bytes, 4)
  guard version == FRAME_VERSION else {
    raise UnsupportedVersion(found=version, supported=FRAME_VERSION)
  }
  let kind = match read_u16(bytes, 6) {
    1 => FrameKind::Call
    2 => Reply
    3 => Log
    4 => Wake
    code => raise UnknownKind(code)
  }
  let length = read_u32_view(bytes, 12)
  guard length <= limit.bytes.reinterpret_as_uint() else {
    raise TooLong(length~, limit=limit.bytes)
  }
  { kind, code: read_u32_view(bytes, 8), length: length.reinterpret_as_int(), }
}

///|
/// The kind of the frame.
pub fn FrameHeader::kind(self : FrameHeader) -> FrameKind {
  self.kind
}

///|
/// The number of bytes of the body.
pub fn FrameHeader::length(self : FrameHeader) -> Int32 {
  self.length
}

///|
/// Read the frame from its header and its body of `length()` bytes.
pub fn FrameHeader::decode_body(
  self : FrameHeader,
  body : Bytes,
) -> Frame raise FrameError {
  guard body.length() == self.length else {
    raise WrongBodyLength(expected=self.length, actual=body.length())
  }
  match self.kind {
    Call => {
      let operation = match self.code {
        0 => Operation::Describe
        1 => Start
        2 => Handle
        3 => Tick
        4 => Stop
        code => raise UnknownCode(Call, code)
      }
      Call(operation, body)
    }
    Reply => {
      let status = Status::from_code(self.code) catch {
        _ => raise UnknownCode(Reply, self.code)
      }
      Reply(status, body)
    }
    Log => {
      let level : @logging.Level = match self.code {
        0 => Trace
        1 => Debug
        2 => Information
        3 => Warning
        4 => Error
        code => raise UnknownCode(Log, code)
      }
      let text = @utf8.decode(body) catch { _ => raise InvalidLogText }
      Log(level, text)
    }
    Wake => {
      guard self.code == 0 else { raise UnknownCode(Wake, self.code) }
      guard body.length() == 0 else {
        raise WrongBodyLength(expected=0, actual=body.length())
      }
      Wake
    }
  }
}

///|
/// Why a frame or a frame limit is not valid.
#derive(Eq, Debug)
pub suberror FrameError {
  /// A frame limit outside 1 byte to 1 GiB.
  InvalidLimit(Int32)
  /// A header that does not have 16 bytes.
  WrongHeaderLength(Int32)
  /// The first four bytes are not the mark: for example plain text on standard output.
  WrongMark(UInt32)
  /// Another version of the frame format.
  UnsupportedVersion(found~ : UInt32, supported~ : UInt32)
  /// A kind with no meaning.
  UnknownKind(UInt32)
  /// A body longer than the limit.
  TooLong(length~ : UInt32, limit~ : Int32)
  /// A code with no meaning for the kind.
  UnknownCode(FrameKind, UInt32)
  /// A body with another length than the header gives, or a wake with a body.
  WrongBodyLength(expected~ : Int32, actual~ : Int32)
  /// The text of a log frame is not valid UTF-8.
  InvalidLogText
}

///|
pub extend FrameError with Eq::{equal, not_equal}

///|
pub extend FrameError with @debug.Debug::{to_repr}

///|
/// Text for people that describes the error.
pub fn FrameError::message(self : FrameError) -> String {
  match self {
    InvalidLimit(count) =>
      "the frame limit \{count} is not between 1 byte and 1 GiB"
    WrongHeaderLength(length) =>
      "the frame header has \{length} bytes; expected \{FRAME_HEADER_LENGTH}"
    WrongMark(mark) =>
      "the frame does not start with the mark MLWF (found 0x\{mark.to_string(radix=16)}); a worker must not write other text to standard output"
    UnsupportedVersion(found~, supported~) =>
      "the frame has version \{found}; this host supports version \{supported}"
    UnknownKind(code) => "the frame kind \{code} is not known"
    TooLong(length~, limit~) =>
      "the frame body of \{length} bytes is longer than the limit of \{limit} bytes"
    UnknownCode(kind, code) =>
      "the code \{code} of a \{kind.name()} frame is not known"
    WrongBodyLength(expected~, actual~) =>
      "the frame body has \{actual} bytes; expected \{expected}"
    InvalidLogText => "the text of a log frame is not valid UTF-8"
  }
}

///|
pub impl Show for FrameError with fn output(self, logger) {
  logger.write_string(self.message())
}

///|
pub extend FrameError with Show::{output, to_string}