///|
/// The direction is inferred from whether a request or response is checked.
pub(all) enum Payload {
  Request
  Response(String)
}

///|
/// Selects one request body or response status to check.
pub(all) struct OpenApiCheck {
  path : String
  http_method : String
  payload : Payload
}

///|
priv enum PreparedOpenApi {
  ParsedOpenApi(Json)
  InvalidOpenApi(String)
}

///|
fn openapi_member(value : Json, key : String) -> Json raise SchemaIssue {
  match value {
    Object(fields) => {
      if fields.contains("$ref") {
        raise Unsupported("unsupported OpenAPI reference at this location")
      }
      match fields.get(key) {
        Some(child) => child
        None => raise Unsupported("missing OpenAPI entry: \{key}")
      }
    }
    _ => raise Unsupported("expected an OpenAPI object before \{key}")
  }
}

///|
fn hex_digit(char : Char) -> Int32 raise SchemaIssue {
  let char = char.to_ascii_lowercase()
  if '0' <= char && char <= '9' {
    char.to_int() - '0'.to_int()
  } else if 'a' <= char && char <= 'f' {
    char.to_int() - 'a'.to_int() + 10
  } else {
    raise Unsupported("invalid percent escape in OpenAPI reference")
  }
}

///|
fn decode_component_fragment(reference : String) -> String raise SchemaIssue {
  if !reference.contains("%") {
    return reference
  }
  let chars = reference.to_array()
  let decoded = StringBuilder()
  let mut index = 0
  while index < chars.length() {
    let char = chars[index]
    if char == '%' {
      if index + 2 >= chars.length() {
        raise Unsupported("truncated percent escape in OpenAPI reference")
      }
      let code = hex_digit(chars[index + 1]) * 16 + hex_digit(chars[index + 2])
      // OpenAPI component names and this pointer prefix only use ASCII.
      if code > 127 {
        raise Unsupported("non-ASCII component reference")
      }
      decoded.write_char(code.unsafe_to_char())
      index += 3
    } else {
      decoded.write_char(char)
      index += 1
    }
  }
  decoded.to_string()
}

///|
fn component_name(
  reference : String,
  group : String,
) -> String raise SchemaIssue {
  let prefix = "#/components/\{group}/"
  if !reference.has_prefix("#") {
    raise Unsupported("expected a local OpenAPI reference under \{prefix}")
  }
  match decode_component_fragment(reference).strip_prefix(prefix) {
    Some(name) if !name.is_empty() &&
      name
      .iter()
      .all(ch => {
        ('A' <= ch && ch <= 'Z') ||
        ('a' <= ch && ch <= 'z') ||
        ('0' <= ch && ch <= '9') ||
        ch == '_' ||
        ch == '-' ||
        ch == '.'
      }) => name.to_owned()
    _ => raise Unsupported("expected a local OpenAPI reference under \{prefix}")
  }
}

///|
fn reference_name(
  fields : Map[String, Json],
  reference : Json,
  group : String,
) -> String raise SchemaIssue {
  if fields.length() != 1 {
    raise Unsupported(
      "OpenAPI references with sibling keywords are unsupported",
    )
  }
  match reference {
    String(reference) => component_name(reference, group)
    _ => raise Unsupported("OpenAPI $ref must be a string")
  }
}

///|
fn component_value(
  root : Json,
  group : String,
  name : String,
) -> Json raise SchemaIssue {
  let components = openapi_member(root, "components")
  openapi_member(openapi_member(components, group), name)
}

///|
fn resolve_component(
  root : Json,
  value : Json,
  group : String,
) -> Json raise SchemaIssue {
  let mut current = value
  let seen : Map[String, Unit] = Map([])
  while current is Object(fields) && fields.get("$ref") is Some(reference) {
    let name = reference_name(fields, reference, group)
    if seen.contains(name) {
      raise Unsupported("cyclic OpenAPI reference: \{group}/\{name}")
    }
    seen[name] = ()
    current = component_value(root, group, name)
  }
  current
}

///|
fn is_openapi_31(version : String) -> Bool {
  match version.strip_prefix("3.1.") {
    Some(patch) =>
      !patch.is_empty() && patch.iter().all(ch => '0' <= ch && ch <= '9')
    None => false
  }
}

///|
fn validate_openapi_check(check : OpenApiCheck) -> Unit raise SchemaIssue {
  if !check.path.has_prefix("/") {
    raise Unsupported("expected an OpenAPI path starting with /")
  }
  match check.http_method {
    "get"
    | "put"
    | "post"
    | "delete"
    | "options"
    | "head"
    | "patch"
    | "trace" => ()
    _ => raise Unsupported("expected a supported lowercase OpenAPI method")
  }
  if check.payload is Response(status) && !is_response_status(status) {
    raise Unsupported(
      "expected a response status code, status range, or default",
    )
  }
}

///|
fn is_response_status(status : String) -> Bool {
  if status == "default" {
    return true
  }
  if status.length() != 3 {
    return false
  }
  match status.to_array() {
    [first, second, third] =>
      '1' <= first &&
      first <= '5' &&
      (
        (second == 'X' && third == 'X') ||
        ('0' <= second && second <= '9' && '0' <= third && third <= '9')
      )
    _ => false
  }
}

///|
fn prepare_openapi(document : String, label : String) -> PreparedOpenApi {
  try {
    let root = parse_document(document, "document")
    match openapi_member(root, "openapi") {
      String(version) if is_openapi_31(version) => ()
      _ => raise Unsupported("expected an OpenAPI 3.1 document")
    }
    if root is Object(fields) {
      match fields.get("jsonSchemaDialect") {
        None
        | Some(String("https://spec.openapis.org/oas/3.1/dialect/base"))
        | Some(String("https://json-schema.org/draft/2020-12/schema")) => ()
        _ => raise Unsupported("unsupported OpenAPI jsonSchemaDialect")
      }
    }
    ParsedOpenApi(root)
  } catch {
    Unsupported(reason) => InvalidOpenApi("\{label}: \{reason}")
  }
}

///|
fn extract_payload(
  document : PreparedOpenApi,
  check : OpenApiCheck,
  label : String,
) -> Json raise SchemaIssue {
  let root = match document {
    ParsedOpenApi(root) => root
    InvalidOpenApi(reason) => raise Unsupported(reason)
  }
  try {
    let path_item = openapi_member(openapi_member(root, "paths"), check.path)
    let operation = openapi_member(path_item, check.http_method)
    let body = match check.payload {
      Request =>
        resolve_component(
          root,
          openapi_member(operation, "requestBody"),
          "requestBodies",
        )
      Response(code) =>
        resolve_component(
          root,
          openapi_member(openapi_member(operation, "responses"), code),
          "responses",
        )
    }
    let content = openapi_member(body, "content")
    let schema = openapi_member(
      openapi_member(content, "application/json"),
      "schema",
    )
    resolve_payload_schema(root, schema)
  } catch {
    Unsupported(reason) => raise Unsupported("\{label}: \{reason}")
  }
}

///|
fn compare_openapi_check(
  old_document : PreparedOpenApi,
  new_document : PreparedOpenApi,
  check : OpenApiCheck,
  include_diagnostic : Bool,
) -> ComparisonReport {
  try {
    validate_openapi_check(check)
    let old = extract_payload(old_document, check, "old document")
    let next = extract_payload(new_document, check, "new document")
    match check.payload {
      Request => compare_values_report(old, next, include_diagnostic)
      Response(_) => compare_values_report(next, old, include_diagnostic)
    }
  } catch {
    Unsupported(reason) => { verdict: Unknown(reason), diagnostic: None, }
  }
}

///|
/// Compare one application/json payload schema in two OpenAPI 3.1
/// documents. Request inclusion is old-to-new, and response inclusion is
/// new-to-old for the selected status code.
pub fn compare_openapi(
  old_document : String,
  new_document : String,
  path : String,
  http_method : String,
  payload : Payload,
) -> Verdict {
  compare_openapi_check(
    prepare_openapi(old_document, "old document"),
    prepare_openapi(new_document, "new document"),
    { path, http_method, payload, },
    false,
  ).verdict
}

///|
/// Compare a payload and locate a failing rule in the receiving schema.
pub fn compare_openapi_detailed(
  old_document : String,
  new_document : String,
  path : String,
  http_method : String,
  payload : Payload,
) -> ComparisonReport {
  compare_openapi_check(
    prepare_openapi(old_document, "old document"),
    prepare_openapi(new_document, "new document"),
    { path, http_method, payload, },
    true,
  )
}

///|
/// Parse the two OpenAPI documents once and return one verdict per check,
/// in input order. An invalid or unsupported payload affects only its check.
pub fn compare_openapi_batch(
  old_document : String,
  new_document : String,
  checks : Array[OpenApiCheck],
) -> Array[Verdict] {
  compare_openapi_reports(old_document, new_document, checks, false).map(report => {
    report.verdict
  })
}

///|
/// Compare a batch and include the target rejection location for each witness.
pub fn compare_openapi_batch_detailed(
  old_document : String,
  new_document : String,
  checks : Array[OpenApiCheck],
) -> Array[ComparisonReport] {
  compare_openapi_reports(old_document, new_document, checks, true)
}

///|
fn compare_openapi_reports(
  old_document : String,
  new_document : String,
  checks : Array[OpenApiCheck],
  include_diagnostic : Bool,
) -> Array[ComparisonReport] {
  if checks.is_empty() {
    return []
  }
  let old = prepare_openapi(old_document, "old document")
  let next = prepare_openapi(new_document, "new document")
  checks.map(check => {
    compare_openapi_check(old, next, check, include_diagnostic)
  })
}