///|
/// A JSON Schema paired with the parser that produces a `T` from a value
/// satisfying it, so the advertised schema and the validation cannot drift.
pub(all) struct Schema[T] {
  json : () -> Json
  decode : (Json, Array[String]) -> T raise SchemaError
}

///|
/// The JSON Schema (draft 2020-12) of the values the schema accepts.
pub fn[T] Schema::to_json_schema(self : Schema[T]) -> Json {
  (self.json)()
}

///|
/// Parses `input`, raising `SchemaError` with the path of the offending value.
pub fn[T] Schema::parse(self : Schema[T], input : Json) -> T raise SchemaError {
  (self.decode)(input, [])
}

///|
/// Adds a `description` to the emitted schema.
pub fn[T] Schema::describe(self : Schema[T], text : String) -> Schema[T] {
  {
    json: () => compose((self.json)(), "description", Json(text)),
    decode: self.decode,
  }
}

///|
/// Converts the parsed value; the emitted schema is unchanged.
pub fn[A, B] Schema::map(self : Schema[A], f : (A) -> B) -> Schema[B] {
  { json: self.json, decode: (input, path) => f((self.decode)(input, path)), }
}

///|
/// Rejects values for which `check` is false with `message`. `keywords` are
/// added to the emitted schema so the advertised schema states the same
/// constraint, e.g. a `pattern` that MoonBit cannot evaluate itself.
/// A keyword the schema already carries with another value is kept beside the
/// new one under `allOf`, since `check` is enforced on top of the earlier
/// constraint rather than instead of it.
pub fn[T] Schema::refine(
  self : Schema[T],
  check : (T) -> Bool,
  message : String,
  keywords~ : Array[(String, Json)] = [],
) -> Schema[T] {
  {
    json: () => {
      keywords.fold(init=(self.json)(), (json, entry) => {
        compose(json, entry.0, entry.1)
      })
    },
    decode: (input, path) => {
      let value = (self.decode)(input, path)
      if !check(value) {
        fail(path, message)
      }
      value
    },
  }
}

///|
/// An integer, optionally bounded (inclusive).
pub fn integer(min? : Int32, max? : Int32) -> Schema[Int32] {
  {
    json: () => {
      bounded(
        "integer",
        ("minimum", min.map(m => Json(m))),
        ("maximum", max.map(m => Json(m))),
      )
    },
    decode: (input, path) => {
      guard input is Number(d, ..) &&
        d == d.floor() &&
        d >= -2147483648.0 &&
        d <= 2147483647.0 else {
        fail(path, "expected an integer")
      }
      let n = d.to_int()
      if min is Some(m) && n < m {
        fail(path, "must be at least \{m}")
      }
      if max is Some(m) && n > m {
        fail(path, "must be at most \{m}")
      }
      n
    },
  }
}

///|
/// An integer beyond the range of `integer`, such as a byte count, optionally
/// bounded (inclusive).
pub fn integer64(min? : Int64, max? : Int64) -> Schema[Int64] {
  {
    // `Json(m)` would emit the bound as a string, since core encodes `Int64` that way.
    json: () => {
      bounded(
        "integer",
        ("minimum", min.map(m => Json::number(m.to_double()))),
        ("maximum", max.map(m => Json::number(m.to_double()))),
      )
    },
    decode: (input, path) => {
      // 2^63 itself is excluded, since it is one past the largest `Int64`.
      guard input is Number(d, ..) &&
        d == d.floor() &&
        d >= -9223372036854775808.0 &&
        d < 9223372036854775808.0 else {
        fail(path, "expected an integer")
      }
      let n = d.to_int64()
      if min is Some(m) && n < m {
        fail(path, "must be at least \{m}")
      }
      if max is Some(m) && n > m {
        fail(path, "must be at most \{m}")
      }
      n
    },
  }
}

///|
/// A number, optionally bounded (inclusive).
pub fn number(min? : Double, max? : Double) -> Schema[Double] {
  {
    json: () => {
      bounded(
        "number",
        ("minimum", min.map(m => Json(m))),
        ("maximum", max.map(m => Json(m))),
      )
    },
    decode: (input, path) => {
      guard input is Number(d, ..) else { fail(path, "expected a number") }
      if min is Some(m) && d < m {
        fail(path, "must be at least \{m}")
      }
      if max is Some(m) && d > m {
        fail(path, "must be at most \{m}")
      }
      d
    },
  }
}

///|
/// A string, optionally bounded in length (in characters).
pub fn string(min_length? : Int32, max_length? : Int32) -> Schema[String] {
  {
    json: () => {
      bounded(
        "string",
        ("minLength", min_length.map(m => Json(m))),
        ("maxLength", max_length.map(m => Json(m))),
      )
    },
    decode: (input, path) => {
      guard input is String(s) else { fail(path, "expected a string") }
      let length = s.iter().count()
      if min_length is Some(m) && length < m {
        fail(path, "must be at least \{m} characters")
      }
      if max_length is Some(m) && length > m {
        fail(path, "must be at most \{m} characters")
      }
      s
    },
  }
}

///|
/// A string containing at least one non-whitespace character, optionally
/// bounded in length (in characters) like `string`.
pub fn not_blank(min_length? : Int32, max_length? : Int32) -> Schema[String] {
  string(min_length?, max_length?).refine(
    s => s.iter().any(c => !c.is_whitespace()),
    "must not be blank",
    keywords=[("pattern", "\\S")],
  )
}

///|
/// A boolean.
pub fn boolean() -> Schema[Bool] {
  {
    json: () => { "type": "boolean" },
    decode: (input, path) => {
      match input {
        True => true
        False => false
        _ => fail(path, "expected a boolean")
      }
    },
  }
}

///|
/// Exactly the string `value`.
pub fn literal(value : String) -> Schema[String] {
  {
    json: () => { "type": "string", "const": Json(value) },
    decode: (input, path) => {
      guard input is String(s) && s == value else {
        fail(path, "must be `\{value}`")
      }
      s
    },
  }
}

///|
/// One of the listed names, parsed to the value paired with it.
pub fn[T] choice(options : Array[(String, T)]) -> Schema[T] {
  let names = options.map(o => o.0)
  {
    json: () => {
      "type": "string",
      "enum": Json::array(names.map(n => Json(n))),
    },
    decode: (input, path) => {
      guard input is String(s) else { fail(path, "expected a string") }
      for option in options {
        if option.0 == s {
          return option.1
        }
      }
      fail(path, "must be one of \{listing(names)}")
    },
  }
}

///|
/// An array whose items all satisfy `item`.
pub fn[T] array(item : Schema[T], min_items? : Int32) -> Schema[Array[T]] {
  {
    json: () => {
      let entries : Array[(String, Json)] = [
        ("type", "array"),
        ("items", (item.json)()),
      ]
      if min_items is Some(m) {
        entries.push(("minItems", Json(m)))
      }
      Json::object(Map::from_array(entries))
    },
    decode: (input, path) => {
      guard input is Array(items) else { fail(path, "expected an array") }
      if min_items is Some(m) && items.length() < m {
        fail(path, "must have at least \{m} items")
      }
      items.mapi((i, v) => (item.decode)(v, [..path, i.to_string()]))
    },
  }
}