///|
fn invalid(why : String) -> Result[Unit, ProtocolError] {
  Err(Malformed(why, 0))
}

///|
pub fn validate_message(value : Message) -> Result[Unit, ProtocolError] {
  for (name, content) in value.headers {
    if !token(name) || !safe_value(content) {
      return invalid("invalid header")
    }
  }
  for name in ["Host", "Preview", "Encapsulated", "ISTag"] {
    if value.headers
      .filter(pair => pair.0.to_lower() == name.to_lower())
      .length() >
      1 {
      return invalid("duplicate " + name)
    }
  }
  if value.body_kind == NoBody &&
    (!value.body.is_empty() || value.ieof || !value.trailers.is_empty()) {
    return invalid("null-body cannot carry body data")
  }
  if value.ieof && header(value.headers, "Preview") is None {
    return invalid("ieof requires Preview")
  }
  if value.start is Request(Reqmod | Respmod, _) &&
    header(value.headers, "Preview") is Some(raw_preview) {
    let preview = match decimal(raw_preview) {
      Some(n) => n
      None => return invalid("invalid Preview")
    }
    if value.body.length() > preview {
      return invalid("body exceeds Preview")
    }
    if !value.ieof &&
      value.body_kind != NoBody &&
      value.body.length() != preview {
      return invalid("partial preview must contain Preview bytes")
    }
  }
  match value.start {
    Request(verb, uri) => {
      if parse_uri(uri) is Err(_) {
        return invalid("invalid service URI")
      }
      if header(value.headers, "Host") is None {
        return invalid("request requires Host")
      }
      match verb {
        Options =>
          if value.request_headers is Some(_) ||
            value.response_headers is Some(_) ||
            value.body_kind != NoBody {
            return invalid("OPTIONS request cannot encapsulate HTTP")
          }
        Reqmod =>
          if value.response_headers is Some(_) ||
            (value.body_kind != NoBody && value.body_kind != RequestBody) {
            return invalid("invalid REQMOD request layout")
          }
        Respmod =>
          if value.body_kind != NoBody && value.body_kind != ResponseBody {
            return invalid("invalid RESPMOD request layout")
          }
      }
    }
    Response(status, reason) => {
      if status < 100 || status > 599 || !safe_value(reason) {
        return invalid("invalid response status")
      }
      if (status == 100 || status == 204 || status == 304) &&
        (
          value.request_headers is Some(_) ||
          value.response_headers is Some(_) ||
          value.body_kind != NoBody
        ) {
        return invalid("body forbidden for this response status")
      }
      if value.request_headers is Some(_) && value.response_headers is Some(_) {
        return invalid("response cannot contain both HTTP header kinds")
      }
      if value.request_headers is Some(_) && value.body_kind == ResponseBody {
        return invalid("request headers with response body")
      }
      if value.response_headers is Some(_) && value.body_kind == RequestBody {
        return invalid("response headers with request body")
      }
      if value.ieof {
        return invalid("response cannot contain preview ieof")
      }
    }
  }
  for (name, content) in value.trailers {
    if !token(name) ||
      !safe_value(content) ||
      ["encapsulated", "host", "content-length", "transfer-encoding", "preview"].contains(
        name.to_lower(),
      ) {
      return invalid("invalid trailer")
    }
  }
  Ok(())
}

///|
fn hex(n : Int32) -> String {
  if n == 0 {
    return "0"
  }
  let digits = "0123456789abcdef".to_array()
  let mut n = n
  let output : Array[Char] = []
  while n > 0 {
    output.push(digits[n % 16])
    n = n / 16
  }
  output.rev_in_place()
  String::from_array(output)
}

///|
pub fn encode_chunks(
  body : Bytes,
  chunk_size~ : Int32 = 8192,
  ieof~ : Bool = false,
  trailers~ : Array[(String, String)] = [],
) -> Result[Bytes, ProtocolError] {
  if chunk_size < 1 {
    return Err(LimitExceeded("chunk size must be positive"))
  }
  let output : Array[Byte] = []
  let mut position = 0
  while position < body.length() {
    let count = if body.length() - position < chunk_size {
      body.length() - position
    } else {
      chunk_size
    }
    append_bytes(output, raw(hex(count) + "\r\n"))
    append_bytes(output, bytes_slice(body, position, position + count))
    append_bytes(output, b"\r\n")
    position += count
  }
  append_bytes(output, if ieof { b"0; ieof\r\n" } else { b"0\r\n" })
  for (name, value) in trailers {
    if !token(name) || !safe_value(value) {
      return Err(Malformed("invalid trailer", 0))
    }
    append_bytes(output, raw(name + ": " + value + "\r\n"))
  }
  append_bytes(output, b"\r\n")
  Ok(Bytes::from_array(output))
}

///|
pub fn encode(
  value : Message,
  bounds~ : Limits = limits(),
  chunk_size~ : Int32 = 8192,
) -> Result[Bytes, ProtocolError] {
  match validate_message(value) {
    Err(e) => return Err(e)
    Ok(_) => ()
  }
  if value.body.length() > bounds.max_body {
    return Err(LimitExceeded("body length"))
  }
  let start = match value.start {
    Request(verb, uri) => method_name(verb) + " " + uri + " ICAP/1.0\r\n"
    Response(status, reason) =>
      "ICAP/1.0 " + status.to_string() + " " + reason + "\r\n"
  }
  let encapsulated : Array[String] = []
  let http : Array[Byte] = []
  if value.request_headers is Some(part) {
    encapsulated.push("req-hdr=" + http.length().to_string())
    append_bytes(http, part)
  }
  if value.response_headers is Some(part) {
    encapsulated.push("res-hdr=" + http.length().to_string())
    append_bytes(http, part)
  }
  let body_name = match value.body_kind {
    NoBody => "null-body"
    RequestBody => "req-body"
    ResponseBody => "res-body"
    OptionsBody => "opt-body"
  }
  encapsulated.push(body_name + "=" + http.length().to_string())
  let head : Array[String] = [start]
  for (name, content) in value.headers {
    if !["encapsulated", "transfer-encoding", "content-length"].contains(
        name.to_lower(),
      ) {
      head.push(name + ": " + content + "\r\n")
    }
  }
  head.push("Encapsulated: " + encapsulated.join(", ") + "\r\n\r\n")
  let prefix = raw(head.join(""))
  if prefix.length() > bounds.max_head {
    return Err(LimitExceeded("header block"))
  }
  let output : Array[Byte] = []
  append_bytes(output, prefix)
  append_bytes(output, Bytes::from_array(http))
  if value.body_kind != NoBody {
    let chunks = match
      encode_chunks(
        value.body,
        chunk_size~,
        ieof=value.ieof,
        trailers=value.trailers,
      ) {
      Ok(b) => b
      Err(e) => return Err(e)
    }
    append_bytes(output, chunks)
  }
  let encoded = Bytes::from_array(output)
  // Validate HTTP section boundaries as well as the public model before emitting.
  match decode(encoded, bounds~) {
    Ok(_) => Ok(encoded)
    Err(e) => Err(e)
  }
}