///|
/// A reusable contract for one ordered reference key and its incoming foreign keys.
/// Hosts persist the opaque keys. The storage format must version their encoding.
pub struct SnapshotPlan {
  resources : Array[Resource]
  target : Int32
  sources : Array[Int32]
  priv target_columns : Array[Int32]
  priv row_rules : Array[Array[BoundRowRule]]
  priv probes : Array[Array[(String, Array[Int32])]]
}

///|
pub fn SnapshotPlan::new(
  descriptor : Descriptor,
  target : String,
  fields : Array[String],
) -> Result[SnapshotPlan, Array[Diagnostic]] {
  let resources = descriptor.resources
  guard resources.search_by(r => r.name == target) is Some(index) else {
    return Err([
      issue("foreign-key-schema", target, 0, "", "Unknown target resource"),
    ])
  }
  let tables = resources.map(r => {
    ({ name: r.name, fields: r.fields, rows: [], } : Table)
  })
  let columns = match field_positions(tables[index], fields) {
    Err(message) =>
      return Err([issue("foreign-key-schema", target, 0, "", message)])
    Ok(columns) => columns
  }
  let kinds = columns.map(i => tables[index].fields[i].kind)
  let probes : Array[Array[(String, Array[Int32])]] = resources.map(_ => [])
  let sources = []
  let errors = []
  let row_rules = resources.map(r => {
    bind_row_rules(r.name, r.fields, r.row_rules, errors)
  })
  for i, r in resources {
    for fk in r.foreign_keys {
      if fk.resource != target || fk.reference_fields != fields {
        continue
      }
      match source_positions(tables[i], fk.fields, columns.length()) {
        Err(e) => errors.push(e)
        Ok(pos) =>
          if incompatible_fields(tables[i], pos, kinds) is Some(e) {
            errors.push(e)
          } else {
            probes[i].push((fk.fields.join(", "), pos))
          }
      }
    }
    if !probes[i].is_empty() {
      sources.push(i)
    }
    if i == index || !probes[i].is_empty() {
      check_field_definitions(r.name, r.fields, errors)
      if prop(descriptor.original, "resources") is Array(items) &&
        tabular_format(items[i]) != "csv" {
        errors.push(
          issue(
            "unsupported",
            r.name,
            0,
            "format",
            "Snapshot indexes require CSV resources",
          ),
        )
      }
    }
  }
  if errors.is_empty() {
    Ok({
      resources,
      target: index,
      sources,
      target_columns: columns,
      probes,
      row_rules,
    })
  } else {
    Err(errors)
  }
}

///|
/// Emit an opaque typed key for a target row or each applicable incoming rule.
/// Missing components do not participate. The storage host receives no raw cells.
pub fn SnapshotPlan::project(
  self : SnapshotPlan,
  table : Int32,
  reference : Bool,
  values : Array[String],
  missing : Array[String],
  row : Int32,
  emit : (String, String) -> Unit,
  diagnose : (Diagnostic) -> Unit,
) -> Unit {
  guard table >= 0 &&
    table < self.resources.length() &&
    row > 0 &&
    (if reference {
      table == self.target
    } else {
      !self.probes[table].is_empty()
    }) else {
    diagnose(
      issue(
        "input", "", row, "", "Resource does not match the snapshot projection",
      ),
    )
    return
  }
  let mut invalid = false
  guard cast_projection_row(
      self.resources[table],
      self.row_rules[table],
      values,
      missing,
      row,
      e => {
        invalid = true
        diagnose(e)
      },
    )
    is Some(cells) else {
    return
  }
  if invalid {
    return
  }
  fn project(field : String, positions : Array[Int32]) -> Unit {
    if !positions.any(i => cells[i] == Missing) {
      emit(field, projection_key(cells, positions))
    }
  }
  if reference {
    project("", self.target_columns)
  } else {
    for probe in self.probes[table] {
      project(probe.0, probe.1)
    }
  }
}