///|
fn validation_result(valid : Bool, message : String) -> Json {
  if valid {
    { "valid": true }
  } else {
    { "valid": false, "message": Json::string(message) }
  }
}

///|
fn numeric_value(value : Json) -> Double? {
  match value {
    Number(number, ..) => Some(number)
    Null | False => Some(0.0)
    True => Some(1.0)
    String(text) => {
      let text = text.trim().to_owned()
      if text.is_empty() {
        Some(0.0)
      } else {
        Some(@string.parse_double(text)) catch {
          _ => None
        }
      }
    }
    Array(items) if items.is_empty() => Some(0.0)
    Array(items) if items.length() == 1 => numeric_value(items[0])
    _ => None
  }
}

///|
fn email_valid(value : Json) -> Bool {
  guard value is String(text) else { return false }
  let parts = text.split("@").map(s => s.to_owned()).collect()
  guard parts.length() == 2 && !parts[0].is_empty() else { return false }
  if !parts[0]
    .iter()
    .all(c => {
      c.is_ascii_alphabetic() ||
      c.is_ascii_digit() ||
      "._%+-".contains(c.to_string())
    }) {
    return false
  }
  let domain = parts[1]
  let labels = domain.split(".").map(s => s.to_owned()).collect()
  guard labels.length() >= 2 else { return false }
  let suffix = labels[labels.length() - 1]
  suffix.length() >= 2 &&
  suffix.iter().all(c => c.is_ascii_alphabetic()) &&
  domain.length() > suffix.length() + 1 &&
  domain
  .iter()
  .all(c => {
    c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '.' || c == '-'
  })
}

///|
fn Runtime::basic_function(
  self : Runtime,
  name : String,
  args : Json,
  context : EvaluationContext,
  depth : Int32,
) -> Json raise ProtocolError {
  let fields = object(args, "/args")
  let value = fields.get("value").unwrap_or(Json::null())
  match name {
    "required" => {
      let valid = match value {
        Null => false
        String(s) => !s.is_empty()
        Array(a) => !a.is_empty()
        _ => true
      }
      validation_result(valid, "This field is required.")
    }
    "length" | "numeric" => {
      let number = if name == "length" {
        Some(
          match value {
            String(s) => s.length().to_double()
            Array(items) => items.length().to_double()
            _ => 0.0
          },
        )
      } else {
        numeric_value(value)
      }
      guard number is Some(number) && !number.is_nan() else {
        return validation_result(false, "Value must be a valid number.")
      }
      if fields.get("min") is Some(Number(min, ..)) && number < min {
        return validation_result(
          false,
          "Minimum " +
          (if name == "length" { "length" } else { "value" }) +
          " is " +
          Json::number(min).stringify() +
          ".",
        )
      }
      if fields.get("max") is Some(Number(max, ..)) && number > max {
        return validation_result(
          false,
          "Maximum " +
          (if name == "length" { "length" } else { "value" }) +
          " is " +
          Json::number(max).stringify() +
          ".",
        )
      }
      { "valid": true }
    }
    "email" =>
      if email_valid(value) {
        { "valid": true }
      } else {
        {
          "valid": false,
          "code": "INVALID_EMAIL",
          "severity": "error",
          "message": "Please enter a valid email address (e.g. user@example.com).",
        }
      }
    "regex" => {
      let pattern = string_field(fields, "pattern", "/args")
      let text = value_string(value)
      let valid = @safe_regex.matches(pattern, text) catch {
        error =>
          raise RuntimeError(
            code="EXPRESSION_ERROR",
            reason="Invalid or unsafe regex: \{Repr(error)}",
          )
      }
      validation_result(
        valid,
        if text.iter().count() > 4096 {
          "Value exceeds the maximum length for pattern matching."
        } else {
          "Value does not match required pattern."
        },
      )
    }
    "and" | "or" => {
      guard fields.get("values") is Some(Array(values)) && values.length() >= 2 else {
        raise RuntimeError(
          code="EXPRESSION_ERROR",
          reason=name + " requires at least 2 values",
        )
      }
      Json::boolean(
        if name == "and" {
          values.iter().all(coerce_boolean)
        } else {
          values.iter().any(coerce_boolean)
        },
      )
    }
    "not" => Json::boolean(!coerce_boolean(value))
    "formatString" =>
      Json::string(self.interpolate(value_string(value), context, depth + 1))
    "formatNumber" | "formatCurrency" | "formatDate" | "pluralize" =>
      @formatting.evaluate(name, args) catch {
        error =>
          raise RuntimeError(
            code="EXPRESSION_ERROR",
            reason="Formatting failed: \{Repr(error)}",
          )
      }
    "openUrl" =>
      raise RuntimeError(
        code="NOT_IMPLEMENTED",
        reason="host must register an openUrl handler",
      )
    _ =>
      raise RuntimeError(
        code="NOT_IMPLEMENTED",
        reason="unknown basic function: " + name,
      )
  }
}