///|
pub struct Configuration {
  registry : Registry
  inventory : Map[String, String]
  profiles : Map[String, Array[String]]
}

///|
/// Strict, versioned data-only rules. No config field can supply commands or scripts.
pub fn Configuration::parse(
  source : String,
  platform : &Platform,
) -> Configuration raise DoctorError {
  validate_input(source)
  let data = @json.parse(
    source,
    max_nesting_depth=32,
    reject_duplicate_keys=true,
  ) catch {
    _ => raise DoctorError("invalid doctor JSON")
  }
  let map = object(data)
  known_fields(map, ["schema_version", "rules", "inventory", "profiles"])
  if int_field(map, "schema_version", 0, 1, 1) != 1 {
    raise DoctorError("schema_version 1 is required")
  }
  let registry = Registry::new()
  let rules = array(required(map, "rules"))
  if rules.is_empty() || rules.length() > 256 {
    raise DoctorError("rules must contain 1 to 256 entries")
  }
  for value in rules {
    registry.register(decode_rule(value, platform))
  }
  registry.plan() |> ignore
  let inventory : Map[String, String] = Map([])
  if map.get("inventory") is Some(value) {
    let entries = object(value)
    if entries.length() > 256 {
      raise DoctorError("inventory exceeds limit")
    }
    for name, version in entries {
      if name.is_empty() || name.length() > 256 {
        raise DoctorError("invalid inventory package name")
      }
      let version = text(version)
      Version::parse(version) |> ignore
      inventory["dependency." + name] = version
    }
  }
  let profiles : Map[String, Array[String]] = Map([])
  if map.get("profiles") is Some(value) {
    let entries = object(value)
    if entries.length() > 32 {
      raise DoctorError("too many profiles")
    }
    for name, ids in entries {
      if !valid_id(name) {
        raise DoctorError("invalid profile name")
      }
      let ids = strings(ids, 256)
      if ids.is_empty() {
        raise DoctorError("profile selection cannot be empty")
      }
      registry.plan(selected=ids) |> ignore
      profiles[name] = ids
    }
  }
  { registry, inventory, profiles, }
}

///|
pub fn Configuration::selection(
  self : Configuration,
  profile? : String,
  category? : String,
) -> Array[String] raise DoctorError {
  let ids = match profile {
    None => self.registry.plan().map(r => r.id)
    Some(name) =>
      self.profiles
      .get(name)
      .unwrap_or_else(() => raise DoctorError("unknown profile"))
  }
  let ids = match category {
    None => ids
    Some(cat) =>
      ids.filter(id => self.registry.get(id).unwrap().category == cat)
  }
  if ids.is_empty() {
    raise DoctorError("selection has no enabled rules")
  }
  ids.copy()
}

///|
pub fn Configuration::context(
  self : Configuration,
  platform : &Platform,
  allow_network~ : Bool = false,
) -> Context {
  let facts = platform.facts()
  for key, value in self.inventory {
    facts[key] = value
  }
  context(facts~, allow_network~)
}

///|
pub fn default_configuration(
  platform : &Platform,
) -> Configuration raise DoctorError {
  let registry = Registry::new()
  registry.register(platform_rule())
  registry.register(
    platform_check(
      "toolchain.moonc",
      "toolchain",
      platform,
      Tool("moonc", ">=0.10.7"),
    ),
  )
  registry.register(
    platform_check("toolchain.moon", "toolchain", platform, Tool("moon", "*")),
  )
  registry.register(
    platform_check(
      "toolchain.git",
      "toolchain",
      platform,
      Tool("git", ">=2.0.0"),
    ),
  )
  registry.register(
    platform_check(
      "filesystem.module",
      "filesystem",
      platform,
      File("moon.mod", Read),
    ),
  )
  for
    pair in [
      ("cpu_count", 1L),
      ("memory_available_bytes", 134217728L),
      ("disk_available_bytes", 104857600L),
    ] {
    registry.register(
      platform_check(
        "resources." + pair.0,
        "resources",
        platform,
        Resource(pair.0, pair.1),
      ),
    )
  }
  let ids = registry.list().map(r => r.id)
  { registry, inventory: Map([]), profiles: { "development": ids, "ci": ids }, }
}