///|
fn expect_object(
  value : Json,
  path : String,
) -> Result[Map[String, Json], String] {
  match value {
    Object(value) => Ok(value)
    _ => Err("\{path}: expected JSON object")
  }
}

///|
fn required(
  object : Map[String, Json],
  key : String,
  path : String,
) -> Result[Json, String] {
  match object.get(key) {
    Some(value) => Ok(value)
    None => Err("\{path}.\{key}: missing required field")
  }
}

///|
fn required_string(
  object : Map[String, Json],
  key : String,
  path : String,
) -> Result[String, String] {
  match required(object, key, path) {
    Err(message) => Err(message)
    Ok(value) =>
      match value {
        String(value) =>
          if value.is_empty() {
            Err("\{path}.\{key}: must not be empty")
          } else {
            Ok(value)
          }
        _ => Err("\{path}.\{key}: expected string")
      }
  }
}

///|
fn optional_array(
  object : Map[String, Json],
  key : String,
  path : String,
) -> Result[Array[Json], String] {
  match object.get(key) {
    None => Ok([])
    Some(Array(values)) => Ok(values)
    Some(_) => Err("\{path}.\{key}: expected array")
  }
}

///|
fn optional_object_map(
  object : Map[String, Json],
  key : String,
  path : String,
) -> Result[Map[String, Json], String] {
  match object.get(key) {
    None => Ok(Map([]))
    Some(value) => expect_object(value, "\{path}.\{key}")
  }
}

///|
fn clone_map(source : Map[String, Json]) -> Map[String, Json] {
  let result = Map([])
  for key, value in source {
    result.set(key, value)
  }
  result
}

///|
fn extract_extensions(
  object : Map[String, Json],
  known : Array[String],
) -> Map[String, Json] {
  let result = Map([])
  for key, value in object {
    if !known.contains(key) {
      result.set(key, value)
    }
  }
  result
}

///|
fn looks_like_uri(value : String) -> Bool {
  !value.is_empty() && value.contains(":") && !value.contains(" ")
}

///|
fn is_digit(unit : UInt16) -> Bool {
  unit >= 48 && unit <= 57
}

///|
fn two_digits(units : ArrayView[UInt16], offset : Int32) -> Int32? {
  if offset + 1 >= units.length() ||
    !is_digit(units[offset]) ||
    !is_digit(units[offset + 1]) {
    return None
  }
  Some((units[offset].to_int() - 48) * 10 + units[offset + 1].to_int() - 48)
}

///|
fn four_digits(units : ArrayView[UInt16], offset : Int32) -> Int32? {
  if offset + 3 >= units.length() {
    return None
  }
  let mut value = 0
  let mut index = offset
  while index <= offset + 3 {
    if !is_digit(units[index]) {
      return None
    }
    value = value * 10 + units[index].to_int() - 48
    index += 1
  }
  Some(value)
}

///|
fn days_in_month(year : Int32, month : Int32) -> Int32 {
  match month {
    2 =>
      if year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) {
        29
      } else {
        28
      }
    4 | 6 | 9 | 11 => 30
    _ => 31
  }
}

///|
fn looks_like_datetime(value : String) -> Bool {
  let units = value.code_units()
  if units.length() < 20 {
    return false
  }
  if units[4] != 45 || units[7] != 45 || units[13] != 58 || units[16] != 58 {
    return false
  }
  if units[10] != 84 && units[10] != 116 {
    return false
  }
  let year = four_digits(units, 0)
  let month = two_digits(units, 5)
  let day = two_digits(units, 8)
  let hour = two_digits(units, 11)
  let minute = two_digits(units, 14)
  let second = two_digits(units, 17)
  if year is None ||
    month is None ||
    day is None ||
    hour is None ||
    minute is None ||
    second is None {
    return false
  }
  let year_value = year.unwrap()
  let month_value = month.unwrap()
  let day_value = day.unwrap()
  let hour_value = hour.unwrap()
  let minute_value = minute.unwrap()
  let second_value = second.unwrap()
  if month_value < 1 ||
    month_value > 12 ||
    day_value < 1 ||
    day_value > days_in_month(year_value, month_value) ||
    hour_value > 23 ||
    minute_value > 59 ||
    second_value > 60 {
    return false
  }
  let mut index = 19
  if units[index] == 46 {
    index += 1
    let fraction_start = index
    while index < units.length() && is_digit(units[index]) {
      index += 1
    }
    if index == fraction_start {
      return false
    }
  }
  if index >= units.length() {
    return false
  }
  if units[index] == 90 || units[index] == 122 {
    return index + 1 == units.length()
  }
  if units[index] != 43 && units[index] != 45 {
    return false
  }
  let offset_hour = two_digits(units, index + 1)
  let colon = index + 3
  if offset_hour is None || colon >= units.length() || units[colon] != 58 {
    return false
  }
  let offset_minute = two_digits(units, colon + 1)
  if offset_minute is None {
    return false
  }
  offset_hour.unwrap() <= 23 &&
  offset_minute.unwrap() <= 59 &&
  colon + 3 == units.length()
}

///|
fn looks_like_uuid(value : String) -> Bool {
  if value.length() != 36 {
    return false
  }
  let units = value.code_units()
  let mut index = 0
  while index < 36 {
    let unit = units[index]
    let is_hyphen = index == 8 || index == 13 || index == 18 || index == 23
    if is_hyphen {
      if unit != 45 {
        return false
      }
    } else if !((unit >= 48 && unit <= 57) ||
      (unit >= 65 && unit <= 70) ||
      (unit >= 97 && unit <= 102)) {
      return false
    }
    index += 1
  }
  true
}

///|
fn validate_uri(
  object : Map[String, Json],
  key : String,
  path : String,
) -> Result[String, String] {
  match required_string(object, key, path) {
    Ok(value) =>
      if looks_like_uri(value) {
        Ok(value)
      } else {
        Err("\{path}.\{key}: expected URI")
      }
    Err(message) => Err(message)
  }
}

///|
fn validate_facets(
  facets : Map[String, Json],
  path : String,
) -> Result[Unit, String] {
  for key, value in facets {
    let facet_path = "\{path}.\{key}"
    let facet = match expect_object(value, facet_path) {
      Ok(value) => value
      Err(message) => return Err(message)
    }
    match validate_uri(facet, "_producer", facet_path) {
      Ok(_) => ()
      Err(message) => return Err(message)
    }
    match validate_uri(facet, "_schemaURL", facet_path) {
      Ok(_) => ()
      Err(message) => return Err(message)
    }
  }
  Ok(())
}

///|
fn decode_schema_fields(
  schema_facet : Map[String, Json],
  path : String,
) -> Result[Array[SchemaField], String] {
  let fields_json = match optional_array(schema_facet, "fields", path) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let fields = []
  let mut index = 0
  while index < fields_json.length() {
    let field_path = "\{path}.fields[\{index}]"
    let field = match expect_object(fields_json[index], field_path) {
      Ok(value) => value
      Err(message) => return Err(message)
    }
    let field_name = match required_string(field, "name", field_path) {
      Ok(value) => value
      Err(message) => return Err(message)
    }
    let data_type = match field.get("type") {
      None => ""
      Some(String(value)) => value
      Some(_) => return Err("\{field_path}.type: expected string")
    }
    let nullable = match field.get("nullable") {
      None => None
      Some(True) => Some(true)
      Some(False) => Some(false)
      Some(_) => return Err("\{field_path}.nullable: expected boolean")
    }
    fields.push(SchemaField::from_openlineage(field_name, data_type, nullable))
    index += 1
  }
  Ok(fields)
}

///|
pub fn decode_dataset(
  value : Json,
  path : String,
) -> Result[DatasetRef, String] {
  let object = match expect_object(value, path) {
    Ok(object) => object
    Err(message) => return Err(message)
  }
  let namespace_id = match required_string(object, "namespace", path) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let name = match required_string(object, "name", path) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let facets = match optional_object_map(object, "facets", path) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let input_facets = match optional_object_map(object, "inputFacets", path) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let output_facets = match optional_object_map(object, "outputFacets", path) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  for
    check in [
      ("facets", facets),
      ("inputFacets", input_facets),
      ("outputFacets", output_facets),
    ] {
    match validate_facets(check.1, "\{path}.\{check.0}") {
      Ok(_) => ()
      Err(message) => return Err(message)
    }
  }
  let schema = match facets.get("schema") {
    None => []
    Some(schema_json) => {
      let schema_path = "\{path}.facets.schema"
      let schema_facet = match expect_object(schema_json, schema_path) {
        Ok(value) => value
        Err(message) => return Err(message)
      }
      let schema_facet_url = match
        required_string(schema_facet, "_schemaURL", schema_path) {
        Ok(value) => value
        Err(message) => return Err(message)
      }
      if schema_facet_url != SCHEMA_DATASET_FACET_SCHEMA_URL {
        return Err(
          "\{schema_path}._schemaURL: unsupported SchemaDatasetFacet version",
        )
      }
      match decode_schema_fields(schema_facet, schema_path) {
        Ok(value) => value
        Err(message) => return Err(message)
      }
    }
  }
  let result = DatasetRef::with_facets(
    DatasetId::new(namespace_id, name),
    schema,
    facets,
    input_facets,
    output_facets,
  )
  result.has_facets = object.contains("facets")
  result.has_input_facets = object.contains("inputFacets")
  result.has_output_facets = object.contains("outputFacets")
  let extensions = extract_extensions(object, [
    "namespace", "name", "facets", "inputFacets", "outputFacets",
  ])
  for key, extension in extensions {
    result.extensions.set(key, extension)
  }
  Ok(result)
}

///|
fn decode_datasets(
  values : Array[Json],
  path : String,
) -> Result[Array[DatasetRef], String] {
  let datasets = []
  let mut index = 0
  while index < values.length() {
    match decode_dataset(values[index], "\{path}[\{index}]") {
      Ok(value) => datasets.push(value)
      Err(message) => return Err(message)
    }
    index += 1
  }
  Ok(datasets)
}

///|
pub fn decode_run_event(value : Json) -> Result[LineageEvent, String] {
  let object = match expect_object(value, "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let event_type = match required_string(object, "eventType", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let state = match RunState::parse(event_type) {
    Some(value) => value
    None =>
      return Err(
        "$.eventType: expected START, RUNNING, COMPLETE, ABORT, FAIL or OTHER",
      )
  }
  let event_time = match required_string(object, "eventTime", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  if !looks_like_datetime(event_time) {
    return Err("$.eventTime: expected RFC 3339 date-time")
  }
  let producer = match validate_uri(object, "producer", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let schema_url = match validate_uri(object, "schemaURL", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  if schema_url != RUN_EVENT_SCHEMA_URL {
    return Err("$.schemaURL: unsupported OpenLineage RunEvent version")
  }
  let run_object = match required(object, "run", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let run_object = match expect_object(run_object, "$.run") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let run_id = match required_string(run_object, "runId", "$.run") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  if !looks_like_uuid(run_id) {
    return Err("$.run.runId: expected UUID")
  }
  let run_facets = match optional_object_map(run_object, "facets", "$.run") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  match validate_facets(run_facets, "$.run.facets") {
    Ok(_) => ()
    Err(message) => return Err(message)
  }
  let job_object = match required(object, "job", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let job_object = match expect_object(job_object, "$.job") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let job_namespace = match required_string(job_object, "namespace", "$.job") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let job_name = match required_string(job_object, "name", "$.job") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let job_facets = match optional_object_map(job_object, "facets", "$.job") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  match validate_facets(job_facets, "$.job.facets") {
    Ok(_) => ()
    Err(message) => return Err(message)
  }
  let inputs_json = match optional_array(object, "inputs", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let outputs_json = match optional_array(object, "outputs", "$") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let inputs = match decode_datasets(inputs_json, "$.inputs") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let outputs = match decode_datasets(outputs_json, "$.outputs") {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  let event = LineageEvent::with_facets(
    event_time,
    producer,
    schema_url,
    state,
    run_id,
    JobId::new(job_namespace, job_name),
    run_facets,
    job_facets,
    inputs,
    outputs,
  )
  event.has_run_facets = run_object.contains("facets")
  event.has_job_facets = job_object.contains("facets")
  event.has_inputs = object.contains("inputs")
  event.has_outputs = object.contains("outputs")
  let extensions = extract_extensions(object, [
    "eventType", "eventTime", "producer", "schemaURL", "run", "job", "inputs", "outputs",
  ])
  for key, extension in extensions {
    event.extensions.set(key, extension)
  }
  let run_extensions = extract_extensions(run_object, ["runId", "facets"])
  for key, extension in run_extensions {
    event.run_extensions.set(key, extension)
  }
  let job_extensions = extract_extensions(job_object, [
    "namespace", "name", "facets",
  ])
  for key, extension in job_extensions {
    event.job_extensions.set(key, extension)
  }
  Ok(event)
}

///|
pub fn decode_run_event_text(
  input : StringView,
) -> Result[LineageEvent, String] {
  let value = @json.parse(input, reject_duplicate_keys=true) catch {
    error => return Err("invalid JSON: \{error.to_string()}")
  }
  decode_run_event(value)
}

///|
fn encoded_schema_field(
  field : SchemaField,
  existing : Map[String, Json],
) -> Json {
  let object = clone_map(existing)
  object.set("name", Json::string(field.name))
  if field.data_type.is_empty() {
    object.remove("type")
  } else {
    object.set("type", Json::string(field.data_type))
  }
  match field.nullable {
    Some(value) => object.set("nullable", Json::boolean(value))
    None => object.remove("nullable")
  }
  Json::object(object)
}

///|
fn encode_schema_facet(dataset : DatasetRef, producer : String) -> Json {
  let existing_facet = match dataset.facets.get("schema") {
    Some(Object(value)) => value
    _ => Map([])
  }
  let existing_fields = match existing_facet.get("fields") {
    Some(Array(value)) => value
    _ => []
  }
  let fields : Array[Json] = []
  for field in dataset.schema {
    let mut existing = Map([])
    for candidate in existing_fields {
      if candidate is Object(candidate) {
        if candidate.get("name") is Some(String(name)) && name == field.name {
          existing = candidate
        }
      }
    }
    fields.push(encoded_schema_field(field, existing))
  }
  let facet = clone_map(existing_facet)
  if !facet.contains("_producer") {
    facet.set("_producer", Json::string(producer))
  }
  if !facet.contains("_schemaURL") {
    facet.set("_schemaURL", Json::string(SCHEMA_DATASET_FACET_SCHEMA_URL))
  }
  facet.set("fields", Json::array(fields))
  Json::object(facet)
}

///|
pub fn encode_dataset(dataset : DatasetRef, producer : String) -> Json {
  let object = clone_map(dataset.extensions)
  object.set("namespace", Json::string(dataset.id.namespace_id))
  object.set("name", Json::string(dataset.id.name))
  let facets = clone_map(dataset.facets)
  if !dataset.schema.is_empty() {
    facets.set("schema", encode_schema_facet(dataset, producer))
  }
  if dataset.has_facets || !facets.is_empty() {
    object.set("facets", Json::object(facets))
  }
  if dataset.has_input_facets || !dataset.input_facets.is_empty() {
    object.set("inputFacets", Json::object(dataset.input_facets))
  }
  if dataset.has_output_facets || !dataset.output_facets.is_empty() {
    object.set("outputFacets", Json::object(dataset.output_facets))
  }
  Json::object(object)
}

///|
pub fn encode_run_event(event : LineageEvent) -> Json {
  let inputs = []
  for input in event.inputs {
    inputs.push(encode_dataset(input, event.producer))
  }
  let outputs = []
  for output in event.outputs {
    outputs.push(encode_dataset(output, event.producer))
  }
  let run = clone_map(event.run_extensions)
  run.set("runId", Json::string(event.run_id))
  if event.has_run_facets || !event.run_facets.is_empty() {
    run.set("facets", Json::object(event.run_facets))
  }
  let job = clone_map(event.job_extensions)
  job.set("namespace", Json::string(event.job.namespace_id))
  job.set("name", Json::string(event.job.name))
  if event.has_job_facets || !event.job_facets.is_empty() {
    job.set("facets", Json::object(event.job_facets))
  }
  let object = clone_map(event.extensions)
  object.set("eventType", Json::string(event.state.event_type()))
  object.set("eventTime", Json::string(event.event_time))
  object.set("producer", Json::string(event.producer))
  object.set("schemaURL", Json::string(event.schema_url))
  object.set("run", Json::object(run))
  object.set("job", Json::object(job))
  if event.has_inputs {
    object.set("inputs", Json::array(inputs))
  }
  if event.has_outputs {
    object.set("outputs", Json::array(outputs))
  }
  Json::object(object)
}

///|
pub fn encode_run_event_text(event : LineageEvent) -> String {
  encode_run_event(event).stringify()
}