///|
/// A function invocation; direction is supplied by its enclosing message.
pub struct FunctionCall {
  id : String
  surface_id : String?
  priv body : Json
}

///|
pub fn FunctionCall::expression(self : FunctionCall) -> Json {
  match self.body {
    { "callFunction": call, .. } => copy_json(call)
    _ => abort("validated function call")
  }
}

///|
fn decode_call(body : Json) -> FunctionCall raise ProtocolError {
  let fields = object(body, "/callFunction")
  {
    id: string_field(fields, "functionCallId", "/callFunction"),
    surface_id: if fields.get("surfaceId") is Some(String(id)) {
      Some(id)
    } else {
      None
    },
    body: copy_json(body),
  }
}

///|
pub struct FunctionResponse {
  id : String
  priv body : Json
}

///|
fn decode_response(body : Json) -> FunctionResponse raise ProtocolError {
  {
    id: string_field(
      object(body, "/functionResponse"),
      "functionCallId",
      "/functionResponse",
    ),
    body: copy_json(body),
  }
}

///|
pub fn FunctionResponse::success(
  id : String,
  value : Json,
) -> FunctionResponse raise ProtocolError {
  let body : Json = { "functionCallId": Json::string(id), "value": value }
  check_schema(schemas().renderer, {
    "version": "1.0",
    "rendererFunctionResponse": body,
  })
  decode_response(body)
}

///|
pub fn FunctionResponse::failure(
  id : String,
  code : String,
  message : String,
) -> FunctionResponse raise ProtocolError {
  let body : Json = {
    "functionCallId": Json::string(id),
    "error": { "code": Json::string(code), "message": Json::string(message) },
  }
  check_schema(schemas().renderer, {
    "version": "1.0",
    "rendererFunctionResponse": body,
  })
  decode_response(body)
}

///|
pub fn FunctionResponse::value(self : FunctionResponse) -> Json? {
  match self.body {
    { "value": value, .. } => Some(copy_json(value))
    _ => None
  }
}

///|
pub fn FunctionResponse::error(self : FunctionResponse) -> Json? {
  match self.body {
    { "error": error, .. } => Some(copy_json(error))
    _ => None
  }
}

///|
pub struct RendererError {
  code : String
  message : String
  priv body : Json
}

///|
pub fn RendererError::new(
  code : String,
  message : String,
  surface_id? : String,
  function_call_id? : String,
  path? : String,
) -> RendererError raise ProtocolError {
  let fields : Map[String, Json] = {
    "code": Json::string(code),
    "message": Json::string(message),
  }
  if surface_id is Some(id) {
    fields["surfaceId"] = Json::string(id)
  }
  if function_call_id is Some(id) {
    fields["functionCallId"] = Json::string(id)
  }
  if path is Some(path) {
    fields["path"] = Json::string(path)
  }
  let body = Json::object(fields)
  check_schema(schemas().renderer, { "version": "1.0", "error": body })
  { code, message, body, }
}

///|
pub(all) enum AgentMessage {
  SurfaceUpdate(Message)
  CallRenderer(FunctionCall)
  AgentFunctionResponse(FunctionResponse)
}

///|
pub(all) enum RendererMessage {
  UserAction(Action)
  CallAgent(FunctionCall)
  RendererFunctionResponse(FunctionResponse)
  Error(RendererError)
}

///|
pub fn AgentMessage::from_json(
  value : Json,
) -> AgentMessage raise ProtocolError {
  check_schema(schemas().agent, value)
  match value {
    { "callRendererFunction": body, .. } => CallRenderer(decode_call(body))
    { "agentFunctionResponse": body, .. } =>
      AgentFunctionResponse(decode_response(body))
    _ => SurfaceUpdate(decode_state_message(value))
  }
}

///|
pub fn RendererMessage::from_json(
  value : Json,
) -> RendererMessage raise ProtocolError {
  check_schema(schemas().renderer, value)
  match value {
    { "action": _, .. } => UserAction(decode_action(value))
    { "callAgentFunction": body, .. } => CallAgent(decode_call(body))
    { "rendererFunctionResponse": body, .. } =>
      RendererFunctionResponse(decode_response(body))
    { "error": body, .. } => {
      let fields = object(body, "/error")
      Error({
        code: string_field(fields, "code", "/error"),
        message: string_field(fields, "message", "/error"),
        body: copy_json(body),
      })
    }
    _ => abort("validated renderer envelope")
  }
}

///|
pub fn AgentMessage::parse(text : String) -> AgentMessage raise {
  AgentMessage::from_json(
    @json.parse(
      text,
      max_nesting_depth=64,
      reject_duplicate_keys=true,
      preserve_number_repr=true,
    ),
  )
}

///|
pub fn RendererMessage::parse(text : String) -> RendererMessage raise {
  RendererMessage::from_json(
    @json.parse(
      text,
      max_nesting_depth=64,
      reject_duplicate_keys=true,
      preserve_number_repr=true,
    ),
  )
}

///|
pub fn AgentMessage::to_json(self : AgentMessage) -> Json {
  match self {
    SurfaceUpdate(message) => message.to_json()
    CallRenderer(call) =>
      { "version": "1.0", "callRendererFunction": copy_json(call.body) }
    AgentFunctionResponse(response) =>
      { "version": "1.0", "agentFunctionResponse": copy_json(response.body) }
  }
}

///|
pub fn RendererMessage::to_json(self : RendererMessage) -> Json {
  match self {
    UserAction(action) => action.to_json()
    CallAgent(call) =>
      { "version": "1.0", "callAgentFunction": copy_json(call.body) }
    RendererFunctionResponse(response) =>
      { "version": "1.0", "rendererFunctionResponse": copy_json(response.body) }
    Error(error) => { "version": "1.0", "error": copy_json(error.body) }
  }
}

///|
pub fn AgentMessage::call_renderer(
  id : String,
  call : Json,
  surface_id? : String,
) -> AgentMessage raise ProtocolError {
  let body : Map[String, Json] = {
    "functionCallId": Json::string(id),
    "callFunction": call,
  }
  if surface_id is Some(id) {
    body["surfaceId"] = Json::string(id)
  }
  AgentMessage::from_json({
    "version": "1.0",
    "callRendererFunction": Json::object(body),
  })
}

///|
pub fn RendererMessage::call_agent(
  id : String,
  surface_id : String,
  call : Json,
) -> RendererMessage raise ProtocolError {
  RendererMessage::from_json({
    "version": "1.0",
    "callAgentFunction": {
      "functionCallId": Json::string(id),
      "surfaceId": Json::string(surface_id),
      "callFunction": call,
    },
  })
}