///|
fn object(value : Json) -> Map[String, Json] raise DoctorError {
  match value {
    Object(map) => map
    _ => raise DoctorError("expected a JSON object")
  }
}

///|
fn array(value : Json) -> Array[Json] raise DoctorError {
  match value {
    Array(items) => items
    _ => raise DoctorError("expected a JSON array")
  }
}

///|
fn text(value : Json) -> String raise DoctorError {
  match value {
    String(s) =>
      if s.length() <= 4096 {
        s
      } else {
        raise DoctorError("string exceeds limit")
      }
    _ => raise DoctorError("expected a JSON string")
  }
}

///|
fn required(map : Map[String, Json], key : String) -> Json raise DoctorError {
  map
  .get(key)
  .unwrap_or_else(() => {
    raise DoctorError("missing required configuration field: \{key}")
  })
}

///|
fn text_field(
  map : Map[String, Json],
  key : String,
) -> String raise DoctorError {
  text(required(map, key))
}

///|
fn optional_text(
  map : Map[String, Json],
  key : String,
  fallback : String,
) -> String raise DoctorError {
  match map.get(key) {
    None => fallback
    Some(value) => text(value)
  }
}

///|
fn bool_field(
  map : Map[String, Json],
  key : String,
  fallback : Bool,
) -> Bool raise DoctorError {
  match map.get(key) {
    None => fallback
    Some(True) => true
    Some(False) => false
    _ => raise DoctorError("expected a boolean configuration field")
  }
}

///|
fn int_field(
  map : Map[String, Json],
  key : String,
  fallback : Int32,
  min : Int32,
  max : Int32,
) -> Int32 raise DoctorError {
  match map.get(key) {
    None => fallback
    Some(Number(n, ..)) =>
      if n >= min.to_double() &&
        n <= max.to_double() &&
        n.to_int().to_double() == n {
        n.to_int()
      } else {
        raise DoctorError("integer field out of range")
      }
    _ => raise DoctorError("expected an integer configuration field")
  }
}

///|
fn strings(value : Json, limit : Int32) -> Array[String] raise DoctorError {
  let values = array(value)
  if values.length() > limit {
    raise DoctorError("array exceeds configured limit")
  }
  values.map(text)
}

///|
fn known_fields(
  map : Map[String, Json],
  keys : Array[String],
) -> Unit raise DoctorError {
  for key in map.keys() {
    if !keys.contains(key) {
      raise DoctorError("unknown configuration field")
    }
  }
}

///|
fn decode_condition(value : Json, depth : Int32) -> Condition raise DoctorError {
  if depth > 16 {
    raise DoctorError("condition nesting exceeds limit")
  }
  let map = object(value)
  if map.length() != 1 {
    raise DoctorError("condition must contain exactly one operator")
  }
  for key, value in map {
    return match key {
      "present" => Present(text(value))
      "equals" => {
        let pair = object(value)
        known_fields(pair, ["key", "value"])
        Equals(text_field(pair, "key"), text_field(pair, "value"))
      }
      "not" => Not(decode_condition(value, depth + 1))
      "all" | "any" => {
        let items = array(value)
        if items.length() > 64 {
          raise DoctorError("too many condition children")
        }
        let nodes = items.map(v => decode_condition(v, depth + 1))
        if key == "all" {
          All(nodes)
        } else {
          Any(nodes)
        }
      }
      _ => raise DoctorError("unknown condition operator")
    }
  }
  raise DoctorError("empty condition")
}

///|
fn decode_fields(value : Json) -> Array[Field] raise DoctorError {
  let items = array(value)
  if items.length() > 256 {
    raise DoctorError("too many field constraints")
  }
  items.map(item => {
    let map = object(item)
    known_fields(map, [
      "path", "type", "required", "allowed", "minimum", "maximum", "requires",
    ])
    let path = strings(required(map, "path"), 16)
    if path.is_empty() {
      raise DoctorError("field path cannot be empty")
    }
    let kind = match text_field(map, "type") {
      "text" => Text
      "number" => Number
      "boolean" => Boolean
      "object" => Object
      "array" => Array
      _ => raise DoctorError("unknown field type")
    }
    let allowed = match map.get("allowed") {
      None => []
      Some(v) => strings(v, 128)
    }
    fn number(key : String) -> Double? raise DoctorError {
      match map.get(key) {
        None => None
        Some(Number(n, ..)) if !n.is_inf() && !n.is_nan() => Some(n)
        _ => raise DoctorError("expected finite field bound")
      }
    }
    let requires = match map.get("requires") {
      None => []
      Some(items) => {
        let paths = array(items)
        if paths.length() > 64 {
          raise DoctorError("too many field prerequisites")
        }
        paths.map(p => strings(p, 16))
      }
    }
    field(
      path,
      kind,
      required=bool_field(map, "required", true),
      allowed~,
      minimum?=number("minimum"),
      maximum?=number("maximum"),
      requires~,
    )
  })
}

///|
fn decode_rule(value : Json, platform : &Platform) -> Rule raise DoctorError {
  let map = object(value)
  let id = text_field(map, "id")
  let kind = text_field(map, "type")
  let common = [
    "id", "type", "name", "severity", "priority", "dependencies", "enabled", "timeout_ms",
    "when",
  ]
  let extra = match kind {
    "environment" => ["key", "expected"]
    "path" => ["directory"]
    "tool" => ["tool", "constraint"]
    "dependency" => ["package", "constraint", "snapshot", "source"]
    "filesystem" => ["path", "access", "kind"]
    "configuration" => ["path", "fields"]
    "dns" => ["host"]
    "tcp" => ["host", "port"]
    "resource" => ["metric", "minimum", "path"]
    "platform" => []
    _ => raise DoctorError("unknown diagnostic rule type")
  }
  known_fields(map, common + extra)
  let base = match kind {
    "environment" =>
      environment_rule(
        id,
        text_field(map, "key"),
        expected?=map.get("expected").map(text),
      )
    "path" =>
      path_rule(
        id,
        text_field(map, "directory"),
        windows=platform.facts().get("doctor.os") == Some("windows"),
      )
    "platform" => { ..platform_rule(), id, }
    "dependency" => decode_dependency(id, map, platform)
    "tool" => {
      let constraint = optional_text(map, "constraint", "*")
      Requirement::parse(constraint) |> ignore
      platform_check(
        id,
        "toolchain",
        platform,
        Tool(text_field(map, "tool"), constraint),
      )
    }
    "filesystem" => {
      let path = text_field(map, "path")
      if !safe_relative(path) {
        raise DoctorError("unsafe filesystem path")
      }
      let access = match optional_text(map, "access", "exists") {
        "exists" => Exists
        "read" => Read
        "write" => Write
        "execute" => Execute
        _ => raise DoctorError("unknown file access mode")
      }
      let probe = match optional_text(map, "kind", "any") {
        "any" => File(path, access)
        "file" => TypedFile(path, access, RegularFile)
        "directory" => TypedFile(path, access, Directory)
        _ => raise DoctorError("unknown path kind")
      }
      platform_check(id, "filesystem", platform, probe)
    }
    "configuration" =>
      configuration_rule(
        id,
        platform,
        text_field(map, "path"),
        decode_fields(required(map, "fields")),
      )
    "dns" =>
      platform_check(id, "network", platform, Dns(text_field(map, "host")))
    "tcp" =>
      platform_check(
        id,
        "network",
        platform,
        Tcp(text_field(map, "host"), int_field(map, "port", 0, 1, 65535)),
      )
    "resource" => {
      let minimum = match required(map, "minimum") {
        Number(n, ..) =>
          if n >= 0.0 &&
            n <= 9007199254740991.0 &&
            n.to_int64().to_double() == n {
            n.to_int64()
          } else {
            raise DoctorError("invalid resource minimum")
          }
        _ => raise DoctorError("resource minimum must be an integer")
      }
      let metric = text_field(map, "metric")
      let probe = match map.get("path") {
        None => Resource(metric, minimum)
        Some(value) => {
          let path = text(value)
          if metric != "disk_available_bytes" || !safe_relative(path) {
            raise DoctorError(
              "resource path requires disk_available_bytes and a safe relative directory",
            )
          }
          DiskAt(path, minimum)
        }
      }
      platform_check(id, "resources", platform, probe)
    }
    _ => raise DoctorError("unknown rule type")
  }
  let severity = match optional_text(map, "severity", "medium") {
    "info" => Info
    "low" => Low
    "medium" => Medium
    "high" => High
    "critical" => Critical
    _ => raise DoctorError("unknown severity")
  }
  let dependencies = match map.get("dependencies") {
    None => []
    Some(v) => strings(v, 256)
  }
  let base = {
    ..base,
    name: optional_text(map, "name", base.name),
    severity,
    priority: int_field(map, "priority", 100, -10000, 10000),
    dependencies,
    enabled: bool_field(map, "enabled", true),
    timeout_ms: int_field(map, "timeout_ms", 3000, 1, 60000),
  }
  match map.get("when") {
    None => base
    Some(v) => {
      let condition = decode_condition(v, 1)
      condition.evaluate(Map([])) |> ignore
      conditional(base, condition)
    }
  }
}