///|
/// The side of a connection.
#derive(Eq, Debug)
pub(all) enum Role {
  Client
  Server
}

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

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

///|
/// The kind of a call that has an ID: an Invocation with one result, or a
/// StreamInvocation with stream items.
#derive(Eq, Debug)
pub(all) enum CallKind {
  /// An Invocation with one result.
  Single
  /// A StreamInvocation with stream items.
  Stream
}

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

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

///|
/// How a local call waits for the peer.
#derive(Eq, Debug)
pub(all) enum CallMode {
  /// An Invocation with an ID: the peer sends a Completion.
  Blocking
  /// An Invocation with no ID: the peer sends no reply.
  NonBlocking
  /// A StreamInvocation: the peer sends stream items and a Completion. Only a
  /// client starts one.
  Streaming
}

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

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

///|
/// A call that the peer made: the hub or the client handler runs it.
#derive(Eq, Debug)
pub(all) struct Call {
  /// `None` for a non-blocking invocation, which gets no reply.
  invocation_id : InvocationId?
  kind : CallKind
  target : MethodName
  arguments : ReadOnlyArray[HubValue]
  /// The upload streams of the call. Their items arrive as `UploadItem`.
  stream_ids : ReadOnlyArray[StreamId]
  headers : Headers
}

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

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

///|
/// The IDs of a local call.
#derive(Eq, Debug)
pub(all) struct Invoked {
  /// `None` for a non-blocking invocation.
  invocation_id : InvocationId?
  /// The upload streams that the call sends, in order.
  stream_ids : ReadOnlyArray[StreamId]
}

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

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

///|
/// An output of a step of the protocol state machine (design PROTO-1).
#derive(Eq, Debug)
pub(all) enum Output {
  /// Write this framed text to the transport.
  Send(String)
  /// The handshake completed; hub messages can flow.
  HandshakeCompleted
  /// The server refused the handshake with this error text.
  HandshakeFailed(String)
  /// The peer made a call.
  Dispatch(Call)
  /// A stream item for a stream that this endpoint started.
  ItemReceived(InvocationId, HubValue)
  /// The Completion of a call that this endpoint started.
  Completed(InvocationId, Outcome)
  /// An item of an upload stream that the peer sends.
  UploadItem(StreamId, HubValue)
  /// The end of an upload stream that the peer sends, with an error text when
  /// the peer ended it with an error.
  UploadEnded(StreamId, String?)
  /// The peer asks to cancel a call that this endpoint runs.
  CancelRequested(InvocationId)
  /// The peer sent a Close message.
  CloseReceived(Close)
  /// The peer broke the protocol. A Close message that names the fault follows.
  Violation(ProtocolError)
  /// End the connection now.
  Closed
}

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

///|
pub impl Eq for ProtocolError with fn equal(self, other) {
  self.message() == other.message()
}

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

///|
/// A local operation that does not fit the state of the connection: a program
/// fault, not a fault of the peer.
#derive(Eq, Debug)
pub suberror UsageError {
  /// The connection is not open: the handshake is not complete, or the
  /// connection is closed.
  NotOpen
  /// No open call that the peer made has this ID.
  UnknownCall(invocation_id~ : InvocationId)
  /// The call is not a stream, so it gets no stream item.
  NotAStream(invocation_id~ : InvocationId)
  /// A stream ends with no result or with an error, never with a result.
  ResultForStream(invocation_id~ : InvocationId)
  /// No open call that this endpoint started has this ID.
  UnknownInvocation(invocation_id~ : InvocationId)
  /// No open upload stream that this endpoint sends has this ID.
  UnknownStream(stream_id~ : StreamId)
  /// A server cannot start a stream invocation.
  StreamFromServer
}

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

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

///|
#derive(Eq)
priv enum Phase {
  Handshake
  Open
  Closed
}

///|
priv struct ReceivedCall {
  kind : CallKind
  cancelled : Bool
}

///|
/// The state of one end of a hub connection. It does no I/O: each input gives
/// the next state and a list of outputs (design PROTO-1). The value is
/// immutable, so a test can keep each state of a run.
pub struct ProtocolState {
  priv role : Role
  priv phase : Phase
  priv frames : FrameBuffer
  priv next_id : UInt64
  /// The calls that this endpoint started and that wait for a Completion.
  priv started : @hashmap.HashMap[InvocationId, CallKind]
  /// The calls that the peer made and that this endpoint has not completed.
  priv received : @hashmap.HashMap[InvocationId, ReceivedCall]
  /// The upload streams that the peer sends and has not ended.
  priv uploads_in : @hashmap.HashMap[StreamId, Unit]
  /// The upload streams that this endpoint sends and has not ended.
  priv uploads_out : @hashmap.HashMap[StreamId, Unit]
  /// The maximum size of a received message, or `None` for no limit.
  priv max_message_size : SizeLimit?
}

///|
fn ProtocolState::new(
  role : Role,
  max_message_size : SizeLimit?,
) -> ProtocolState {
  {
    max_message_size,
    role,
    phase: Handshake,
    frames: FrameBuffer::empty(),
    next_id: 0UL,
    started: @hashmap.HashMap::empty(),
    received: @hashmap.HashMap::empty(),
    uploads_in: @hashmap.HashMap::empty(),
    uploads_out: @hashmap.HashMap::empty(),
  }
}

///|
/// A server end that waits for the handshake request. A received message with
/// more bytes than `max_message_size` closes the connection with an error that
/// names the limit.
pub fn ProtocolState::server(
  max_message_size~ : SizeLimit = SizeLimit::default_message_size(),
) -> ProtocolState {
  ProtocolState::new(Server, Some(max_message_size))
}

///|
/// A client end, and the output that sends the handshake request for the JSON
/// protocol.
pub fn ProtocolState::client(
  max_message_size? : SizeLimit,
) -> (ProtocolState, Array[Output]) {
  (
    ProtocolState::new(Client, max_message_size),
    [Send(HandshakeRequest::json().to_frame())],
  )
}

///|
/// The role of the endpoint.
pub fn ProtocolState::role(self : ProtocolState) -> Role {
  self.role
}

///|
/// True when the handshake is complete and the connection is not closed.
pub fn ProtocolState::is_open(self : ProtocolState) -> Bool {
  self.phase == Open
}

///|
/// True when the connection is closed.
pub fn ProtocolState::is_closed(self : ProtocolState) -> Bool {
  self.phase == Closed
}

///|
/// The number of calls that the peer made and that wait for their Completion.
pub fn ProtocolState::open_calls(self : ProtocolState) -> Int32 {
  self.received.length()
}

///|
/// The number of calls that this endpoint started and that wait for their
/// Completion.
pub fn ProtocolState::pending_calls(self : ProtocolState) -> Int32 {
  self.started.length()
}

///|
/// The number of upload streams that the peer has not ended.
pub fn ProtocolState::open_upload_count(self : ProtocolState) -> Int32 {
  self.uploads_in.length()
}

///|
fn stream_id_of(id : InvocationId) -> StreamId {
  { text: id.text, }
}

///|
fn invocation_id_of(id : StreamId) -> InvocationId {
  { text: id.text, }
}

///|
/// Close because the peer broke the protocol: report the fault, send a Close
/// message that names it and permits no reconnect, and end the connection.
fn ProtocolState::violation(
  self : ProtocolState,
  error : ProtocolError,
  outputs : Array[Output],
) -> ProtocolState {
  outputs.push(Violation(error))
  outputs.push(
    Send(
      HubMessage::Close({
        error: Some(error.message()),
        allow_reconnect: false,
        headers: Headers::empty(),
      }).to_frame(),
    ),
  )
  outputs.push(Closed)
  { ..self, phase: Closed, }
}

///|
/// Take the text of one transport frame. A closed connection ignores it.
pub fn ProtocolState::receive(
  self : ProtocolState,
  text : StringView,
) -> (ProtocolState, Array[Output]) {
  let outputs = []
  guard self.phase != Closed else { return (self, outputs) }
  let (frames, messages) = self.frames.push(text)
  let mut state = { ..self, frames, }
  for message in messages {
    guard state.phase != Closed else { break }
    if state.max_message_size is Some(limit) {
      let size = utf8_length(message)
      if size > limit.to_bytes() {
        state = state.violation(
          MessageTooLarge(limit=limit.to_bytes(), size~),
          outputs,
        )
        break
      }
    }
    state = if state.phase == Handshake {
      state.receive_handshake(message, outputs)
    } else {
      state.receive_message(message, outputs)
    }
  }
  // An incomplete message that is already over the limit cannot become valid.
  if state.phase != Closed && state.max_message_size is Some(limit) {
    let size = state.frames.pending_utf8_length()
    if size > limit.to_bytes() {
      state = state.violation(
        MessageTooLarge(limit=limit.to_bytes(), size~),
        outputs,
      )
    }
  }
  (state, outputs)
}

///|
fn ProtocolState::receive_handshake(
  self : ProtocolState,
  text : String,
  outputs : Array[Output],
) -> ProtocolState {
  match self.role {
    Server => {
      let request = HandshakeRequest::parse(text) catch {
        error => {
          // A hub message or other text before the handshake: close with no
          // handshake response.
          outputs.push(
            Violation(
              if (Some(HubMessage::parse(text)) catch { _ => None }) is Some(_) {
                MessageBeforeHandshake
              } else {
                error
              },
            ),
          )
          outputs.push(Closed)
          return { ..self, phase: Closed, }
        }
      }
      let response = HandshakeResponse::for_request(request)
      outputs.push(Send(response.to_frame()))
      match response {
        Accepted => {
          outputs.push(HandshakeCompleted)
          { ..self, phase: Open, }
        }
        Refused(_) => {
          outputs.push(Closed)
          { ..self, phase: Closed, }
        }
      }
    }
    Client => {
      let response = HandshakeResponse::parse(text) catch {
        error => {
          outputs.push(Violation(error))
          outputs.push(Closed)
          return { ..self, phase: Closed, }
        }
      }
      match response {
        Accepted => {
          outputs.push(HandshakeCompleted)
          { ..self, phase: Open, }
        }
        Refused(error) => {
          outputs.push(HandshakeFailed(error))
          outputs.push(Closed)
          { ..self, phase: Closed, }
        }
      }
    }
  }
}

///|
/// Register the upload streams of a call that the peer made.
fn ProtocolState::open_uploads(
  self : ProtocolState,
  ids : ReadOnlyArray[StreamId],
) -> ProtocolState raise ProtocolError {
  let mut uploads = self.uploads_in
  for id in ids {
    guard !uploads.contains(id) else { raise StreamIdInUse(stream_id=id) }
    uploads = uploads.insert(id, ())
  }
  { ..self, uploads_in: uploads, }
}

///|
fn ProtocolState::receive_message(
  self : ProtocolState,
  text : String,
  outputs : Array[Output],
) -> ProtocolState {
  let next = self.apply(text, outputs) catch {
    error => return self.violation(error, outputs)
  }
  next
}

///|
fn ProtocolState::apply(
  self : ProtocolState,
  text : String,
  outputs : Array[Output],
) -> ProtocolState raise ProtocolError {
  match HubMessage::parse(text) {
    Invocation(message) => {
      let mut state = self
      if message.invocation_id is Some(id) {
        guard !state.received.contains(id) else {
          raise InvocationIdInUse(invocation_id=id)
        }
        state = {
          ..state,
          received: state.received.insert(id, {
            kind: Single,
            cancelled: false,
          }),
        }
      }
      state = state.open_uploads(message.stream_ids)
      outputs.push(
        Dispatch({
          invocation_id: message.invocation_id,
          kind: Single,
          target: message.target,
          arguments: message.arguments,
          stream_ids: message.stream_ids,
          headers: message.headers,
        }),
      )
      state
    }
    StreamInvocation(message) => {
      guard self.role == Server else { raise UnexpectedMessage(message_type=4) }
      let id = message.invocation_id
      guard !self.received.contains(id) else {
        raise InvocationIdInUse(invocation_id=id)
      }
      let state = {
        ..self,
        received: self.received.insert(id, { kind: Stream, cancelled: false, }),
      }.open_uploads(message.stream_ids)
      outputs.push(
        Dispatch({
          invocation_id: Some(id),
          kind: Stream,
          target: message.target,
          arguments: message.arguments,
          stream_ids: message.stream_ids,
          headers: message.headers,
        }),
      )
      state
    }
    StreamItem(message) => {
      let id = message.invocation_id
      let stream = stream_id_of(id)
      if self.uploads_in.contains(stream) {
        outputs.push(UploadItem(stream, message.item))
        return self
      }
      guard self.started.get(id) is Some(kind) else {
        raise UnknownInvocation(invocation_id=id)
      }
      guard kind == Stream else {
        raise StreamItemForInvocation(invocation_id=id)
      }
      outputs.push(ItemReceived(id, message.item))
      self
    }
    Completion(message) => {
      let id = message.invocation_id
      let stream = stream_id_of(id)
      if self.uploads_in.contains(stream) {
        let error = match message.outcome {
          Error(text) => Some(text)
          _ => None
        }
        outputs.push(UploadEnded(stream, error))
        return { ..self, uploads_in: self.uploads_in.remove(stream), }
      }
      guard self.started.get(id) is Some(kind) else {
        raise UnknownInvocation(invocation_id=id)
      }
      // A stream ends with no result or an error. A result after stream items,
      // or for a stream with no items, is a fault of the peer.
      if kind == Stream && message.outcome is Result(_) {
        raise ResultAfterStreamItems(invocation_id=id)
      }
      outputs.push(Completed(id, message.outcome))
      { ..self, started: self.started.remove(id), }
    }
    CancelInvocation(message) => {
      let id = message.invocation_id
      match self.received.get(id) {
        Some(call) if !call.cancelled => {
          outputs.push(CancelRequested(id))
          {
            ..self,
            received: self.received.insert(id, { ..call, cancelled: true, }),
          }
        }
        // An unknown or finished ID, or a second request: ignore it.
        _ => self
      }
    }
    Ping => self
    Close(message) => {
      outputs.push(CloseReceived(message))
      outputs.push(Closed)
      { ..self, phase: Closed, }
    }
  }
}

///|
fn ProtocolState::send_message(
  self : ProtocolState,
  message : HubMessage,
) -> (ProtocolState, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  (self, [Send(message.to_frame())])
}

///|
/// The ID of a new call. Both sides choose IDs from one namespace of their own, but
/// a Completion from a client can also end an upload stream, whose ID the client
/// chose. The clients use decimal counters, so a server adds a letter.
fn ProtocolState::new_call_id(
  self : ProtocolState,
  counter : UInt64,
) -> InvocationId {
  match self.role {
    Client => InvocationId::from_counter(counter)
    Server => { text: "s\{counter}", }
  }
}

///|
/// Start a call to the peer with `uploads` upload streams. The state gives the
/// invocation ID and the stream IDs from one counter, as the .NET and JavaScript
/// clients do.
pub fn ProtocolState::call(
  self : ProtocolState,
  mode : CallMode,
  target : MethodName,
  arguments : ArrayView[HubValue],
  uploads~ : Int32 = 0,
  headers~ : Headers = Headers::empty(),
) -> (ProtocolState, Invoked, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  guard mode != Streaming || self.role == Client else { raise StreamFromServer }
  let mut next = self.next_id
  let invocation_id = if mode == NonBlocking {
    None
  } else {
    let id = self.new_call_id(next)
    next += 1UL
    Some(id)
  }
  let stream_ids = []
  let mut uploads_out = self.uploads_out
  for _ in 0..
      (
        HubMessage::StreamInvocation({
          invocation_id: id,
          target,
          arguments,
          stream_ids,
          headers,
        }),
        self.started.insert(id, Stream),
      )
    (_, Some(id)) =>
      (
        HubMessage::Invocation({
          invocation_id: Some(id),
          target,
          arguments,
          stream_ids,
          headers,
        }),
        self.started.insert(id, Single),
      )
    (_, None) =>
      (
        HubMessage::Invocation({
          invocation_id: None,
          target,
          arguments,
          stream_ids,
          headers,
        }),
        self.started,
      )
  }
  let state = { ..self, next_id: next, started, uploads_out, }
  (state, { invocation_id, stream_ids, }, [Send(message.to_frame())])
}

///|
/// Ask the peer to cancel a call that this endpoint started. The call stays
/// open until its Completion arrives.
pub fn ProtocolState::cancel(
  self : ProtocolState,
  invocation_id : InvocationId,
) -> (ProtocolState, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  guard self.started.contains(invocation_id) else {
    raise UnknownInvocation(invocation_id~)
  }
  self.send_message(
    CancelInvocation({ invocation_id, headers: Headers::empty(), }),
  )
}

///|
/// Send one item of a stream call that the peer made. After the peer cancelled
/// the call, the item is dropped and no output is given.
pub fn ProtocolState::send_item(
  self : ProtocolState,
  invocation_id : InvocationId,
  item : HubValue,
) -> (ProtocolState, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  guard self.received.get(invocation_id) is Some(call) else {
    raise UnknownCall(invocation_id~)
  }
  guard call.kind == Stream else { raise NotAStream(invocation_id~) }
  guard !call.cancelled else { return (self, []) }
  self.send_message(
    StreamItem({ invocation_id, item, headers: Headers::empty(), }),
  )
}

///|
/// Send the Completion of a call that the peer made. A stream call ends with
/// no result or with an error. A cancelled call also gets its Completion.
pub fn ProtocolState::complete(
  self : ProtocolState,
  invocation_id : InvocationId,
  outcome : Outcome,
) -> (ProtocolState, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  guard self.received.get(invocation_id) is Some(call) else {
    raise UnknownCall(invocation_id~)
  }
  guard !(call.kind == Stream && outcome is Result(_)) else {
    raise ResultForStream(invocation_id~)
  }
  let state = { ..self, received: self.received.remove(invocation_id), }
  state.send_message(
    Completion({ invocation_id, outcome, headers: Headers::empty(), }),
  )
}

///|
/// Send one item of an upload stream that this endpoint started.
pub fn ProtocolState::upload_item(
  self : ProtocolState,
  stream_id : StreamId,
  item : HubValue,
) -> (ProtocolState, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  guard self.uploads_out.contains(stream_id) else {
    raise UnknownStream(stream_id~)
  }
  self.send_message(
    StreamItem({
      invocation_id: invocation_id_of(stream_id),
      item,
      headers: Headers::empty(),
    }),
  )
}

///|
/// End an upload stream that this endpoint started, with an error text when
/// it ends because of an error.
pub fn ProtocolState::end_upload(
  self : ProtocolState,
  stream_id : StreamId,
  error? : String,
) -> (ProtocolState, Array[Output]) raise UsageError {
  guard self.phase == Open else { raise NotOpen }
  guard self.uploads_out.contains(stream_id) else {
    raise UnknownStream(stream_id~)
  }
  let outcome : Outcome = match error {
    Some(text) => Error(text)
    None => NoResult
  }
  let state = { ..self, uploads_out: self.uploads_out.remove(stream_id), }
  state.send_message(
    Completion({
      invocation_id: invocation_id_of(stream_id),
      outcome,
      headers: Headers::empty(),
    }),
  )
}

///|
/// Send a Ping message.
pub fn ProtocolState::ping(
  self : ProtocolState,
) -> (ProtocolState, Array[Output]) raise UsageError {
  self.send_message(Ping)
}

///|
/// Send a Close message and end the connection. `error` is set only when the
/// connection ends because of an error. A closed connection gives no output.
pub fn ProtocolState::close(
  self : ProtocolState,
  error? : String,
  allow_reconnect~ : Bool = false,
) -> (ProtocolState, Array[Output]) {
  guard self.phase != Closed else { return (self, []) }
  let outputs : Array[Output] = []
  if self.phase == Open {
    outputs.push(
      Send(
        HubMessage::Close({ error, allow_reconnect, headers: Headers::empty(), }).to_frame(),
      ),
    )
  }
  outputs.push(Closed)
  ({ ..self, phase: Closed, }, outputs)
}

///|
/// The server that a client talks to. It decides whether the client sends a
/// CancelInvocation for a call with one result: .NET 10 servers do not accept
/// one, .NET 11 servers and Moon-Lander servers do (design WIRE-2).
#derive(Eq, Debug)
pub(all) enum PeerProfile {
  MoonLander
  DotNet10
  DotNet11
}

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

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

///|
/// True when the peer accepts a CancelInvocation for a call of `kind`. Every
/// peer accepts one for a stream.
pub fn PeerProfile::accepts_cancel(self : PeerProfile, kind : CallKind) -> Bool {
  match (kind, self) {
    (Stream, _) => true
    (Single, DotNet10) => false
    (Single, _) => true
  }
}