///|
pub(all) enum FieldType {
  Text
  Number
  Boolean
  Object
  Array
}

///|
pub(all) struct Field {
  path : Array[String]
  kind : FieldType
  required : Bool
  allowed : Array[String]
  minimum : Double?
  maximum : Double?
  requires : Array[Array[String]]
}

///|
pub fn field(
  path : Array[String],
  kind : FieldType,
  required~ : Bool = true,
  allowed~ : Array[String] = [],
  minimum? : Double,
  maximum? : Double,
  requires~ : Array[Array[String]] = [],
) -> Field {
  { path, kind, required, allowed, minimum, maximum, requires, }
}

///|
fn json_at(value : Json, path : Array[String]) -> Json? {
  let mut current = value
  for key in path {
    match current {
      Object(map) =>
        match map.get(key) {
          Some(next) => current = next
          None => return None
        }
      _ => return None
    }
  }
  Some(current)
}

///|
pub fn validate_configuration(text : String, fields : Array[Field]) -> Finding {
  validate_input(text) catch {
    _ =>
      return finding(
        Error,
        "config_limit",
        "Configuration exceeds input limits",
      )
  }
  if fields.length() > 256 {
    return finding(Error, "config_limit", "Too many field constraints")
  }
  let value = @json.parse(
    text,
    max_nesting_depth=32,
    reject_duplicate_keys=true,
  ) catch {
    err =>
      return finding(
        Failed,
        "config_parse",
        "Configuration is not valid JSON",
        evidence=json_error_position(err),
        remediation="Correct JSON syntax without including secrets in logs",
      )
  }
  validate_configuration_value(value, fields)
}

///|
/// Apply the field schema to an already decoded value.
pub fn validate_configuration_value(
  value : Json,
  fields : Array[Field],
) -> Finding {
  if fields.length() > 256 {
    return finding(Error, "config_limit", "Too many field constraints")
  }
  if !(value is Object(_)) {
    return finding(
      Failed,
      "config_root",
      "Configuration root must be an object",
    )
  }
  for field in fields {
    if field.path.is_empty() || field.path.length() > 16 {
      return finding(Error, "config_schema", "Invalid field path")
    }
    let location = field.path
      .map(segment => {
        segment.replace_all(old="~", new="~0").replace_all(old="/", new="~1")
      })
      .join("/")
    let evidence = [
      { key: "json_pointer", value: "/" + location, sensitive: false, },
    ]
    if (field.minimum is Some(_) || field.maximum is Some(_)) &&
      !(field.kind is Number) {
      return finding(
        Error,
        "config_schema",
        "Bounds require a number field",
        evidence~,
      )
    }
    if field.minimum is Some(lo) && field.maximum is Some(hi) && lo > hi {
      return finding(
        Error,
        "config_schema",
        "Minimum exceeds maximum",
        evidence~,
      )
    }
    if field.requires.length() > 64 ||
      field.requires.iter().any(p => p.is_empty() || p.length() > 16) {
      return finding(
        Error,
        "config_schema",
        "Invalid required field paths",
        evidence~,
      )
    }
    match json_at(value, field.path) {
      None =>
        if field.required {
          return finding(
            Failed,
            "config_required",
            "A required configuration field is missing",
            evidence~,
            remediation="Consult the project's configuration schema",
          )
        }
      Some(item) => {
        let valid = match (field.kind, item) {
          (Text, String(_))
          | (Number, Number(_, ..))
          | (Boolean, True | False)
          | (Object, Object(_))
          | (Array, Array(_)) => true
          _ => false
        }
        if !valid {
          return finding(
            Failed,
            "config_type",
            "A configuration field has the wrong type",
            evidence~,
          )
        }
        if item is Number(n, ..) {
          if (field.minimum is Some(lo) && n < lo) ||
            (field.maximum is Some(hi) && n > hi) {
            return finding(
              Failed,
              "config_range",
              "Number is outside the allowed range",
              evidence~,
              remediation="Check the field bounds in the project schema",
            )
          }
        }
        for dependency in field.requires {
          if json_at(value, dependency) is None {
            return finding(
              Failed,
              "config_dependency",
              "A field requires another configuration field",
              evidence~,
              remediation="Provide the related field required by the project schema",
            )
          }
        }
        if !field.allowed.is_empty() {
          match item {
            String(s) =>
              if !field.allowed.contains(s) {
                return finding(
                  Failed,
                  "config_value",
                  "A configuration field has a disallowed value",
                  evidence~,
                )
              }
            _ =>
              return finding(
                Error,
                "config_schema",
                "Allowed values require a text field",
              )
          }
        }
      }
    }
  }
  finding(Passed, "config_valid", "JSON syntax and declared fields are valid")
}

///|
pub fn configuration_rule(
  id : String,
  platform : &Platform,
  path : String,
  fields : Array[Field],
) -> Rule raise DoctorError {
  if !safe_relative(path) {
    raise DoctorError("unsafe configuration path")
  }
  let schema = fields.map(f => {
    ..f,
    path: f.path.copy(),
    allowed: f.allowed.copy(),
    requires: f.requires.map(p => p.copy()),
  })
  rule(id, "configuration", _ => {
    let text = platform.read_text(path, 65536) catch {
      err => {
        if @async.is_being_cancelled() {
          raise err
        }
        return finding(
          Error,
          "config_access",
          "Cannot safely read configuration",
          remediation="Check path, size, symlinks, and read permissions",
        )
      }
    }
    validate_configuration(text, schema)
  })
}