///|
fn field_positions(
  table : Table,
  names : Array[String],
) -> Result[Array[Int32], String] {
  if names.is_empty() {
    return Err("Key fields cannot be empty")
  }
  let positions : Array[Int32] = []
  for name in names {
    let mut position = -1
    for i, f in table.fields {
      if f.name == name {
        position = i
      }
    }
    if position < 0 {
      return Err("Unknown key field: " + name)
    }
    if positions.contains(position) {
      return Err("Repeated field in key: " + name)
    }
    positions.push(position)
  }
  Ok(positions)
}

///|
/// Only call on a table whose TableReport is valid. Composite keys compare typed cells.
pub fn validate_primary_key(
  table : Table,
  fields : Array[String],
  on_duplicate? : (String, Int32, Int32) -> Unit,
) -> Array[Diagnostic] {
  let positions = match field_positions(table, fields) {
    Ok(p) => p
    Err(message) =>
      return [issue("primary-key-schema", table.name, 0, "", message)]
  }
  let errors : Array[Diagnostic] = []
  let seen : Map[Array[Cell], Int32] = Map([])
  for i, row in table.rows {
    if row.length() != table.fields.length() {
      errors.push(
        issue(
          "invalid-table",
          table.name,
          i + 1,
          "",
          "Cannot validate keys on a malformed logical table",
        ),
      )
      continue
    }
    let key = positions.map(p => row[p])
    if key.contains(Missing) {
      errors.push(
        issue(
          "primary-key-null",
          table.name,
          i + 1,
          "",
          "Primary key contains a missing value",
        ),
      )
    } else if seen.get(key) is Some(first) {
      if on_duplicate is Some(emit) {
        emit(table.name, i + 1, first)
      }
      errors.push(
        issue(
          "primary-key-duplicate",
          table.name,
          i + 1,
          fields.join(", "),
          "Duplicate primary key",
        ),
      )
    } else {
      seen[key] = i + 1
    }
  }
  errors
}

///|
/// A snapshot of a validated reference table, keyed by ordered, typed cells.
/// Build again after changing reference rows. Source tables can be checked in batches.
pub struct ForeignKeyIndex {
  priv kinds : Array[FieldType]
  priv keys : @hashset.HashSet[Array[Cell]]
}

///|
fn foreign_key_tuple(
  row : Array[Cell],
  positions : Array[Int32],
) -> Array[Cell] {
  positions.map(p => {
    match row[p] {
      NumberValue(n) if n == 0.0 => NumberValue(0.0)
      cell => cell
    }
  })
}

///|
fn index_reference(
  table : Table,
  positions : Array[Int32],
  kinds : Array[FieldType],
) -> Result[ForeignKeyIndex, Diagnostic] {
  let keys : @hashset.HashSet[Array[Cell]] = @hashset.HashSet([])
  for row in table.rows {
    if row.length() != table.fields.length() {
      return Err(
        issue("invalid-table", table.name, 0, "", "Malformed reference table"),
      )
    }
    let key = foreign_key_tuple(row, positions)
    if !key.contains(Missing) {
      keys.add(key)
    }
  }
  Ok({ kinds, keys, })
}

///|
pub fn ForeignKeyIndex::new(
  reference : Table,
  fields : Array[String],
) -> Result[ForeignKeyIndex, Diagnostic] {
  match field_positions(reference, fields) {
    Err(message) =>
      Err(issue("foreign-key-schema", reference.name, 0, "", message))
    Ok(to) =>
      index_reference(reference, to, to.map(p => reference.fields[p].kind))
  }
}

///|
fn source_positions(
  table : Table,
  fields : Array[String],
  width : Int32,
) -> Result[Array[Int32], Diagnostic] {
  if fields.length() != width {
    return Err(
      issue(
        "foreign-key-schema",
        table.name,
        0,
        "",
        "Foreign key arities differ",
      ),
    )
  }
  match field_positions(table, fields) {
    Err(message) => Err(issue("foreign-key-schema", table.name, 0, "", message))
    Ok(positions) => Ok(positions)
  }
}

///|
fn incompatible_fields(
  table : Table,
  positions : Array[Int32],
  kinds : Array[FieldType],
) -> Diagnostic? {
  for i, pos in positions {
    if table.fields[pos].kind != kinds[i] {
      return Some(
        issue(
          "unsupported",
          table.name,
          0,
          "",
          "Cross-type foreign keys are outside the supported subset",
        ),
      )
    }
  }
  None
}

///|
fn ForeignKeyIndex::check_rows(
  self : ForeignKeyIndex,
  table : Table,
  from : Array[Int32],
  fields : Array[String],
) -> Array[Diagnostic] {
  let errors = []
  let label = fields.join(", ")
  for i, row in table.rows {
    if self.check_row(table, row, i + 1, from, label) is Some(e) {
      errors.push(e)
    }
  }
  errors
}

///|
fn ForeignKeyIndex::check_row(
  self : ForeignKeyIndex,
  table : Table,
  row : Array[Cell],
  number : Int32,
  columns : Array[Int32],
  label : String,
) -> Diagnostic? {
  if row.length() != table.fields.length() {
    return Some(
      issue("invalid-table", table.name, number, "", "Malformed source table"),
    )
  }
  let key = foreign_key_tuple(row, columns)
  if !key.contains(Missing) && !self.keys.contains(key) {
    Some(
      issue(
        "foreign-key",
        table.name,
        number,
        label,
        "No matching referenced row",
      ),
    )
  } else {
    None
  }
}

///|
pub fn ForeignKeyIndex::validate(
  self : ForeignKeyIndex,
  table : Table,
  fields : Array[String],
) -> Array[Diagnostic] {
  match source_positions(table, fields, self.kinds.length()) {
    Err(error) => [error]
    Ok(from) if incompatible_fields(table, from, self.kinds) is Some(error) =>
      [error]
    Ok(from) => self.check_rows(table, from, fields)
  }
}

///|
pub fn validate_foreign_key(
  table : Table,
  fields : Array[String],
  reference : Table,
  reference_fields : Array[String],
) -> Array[Diagnostic] {
  check_foreign_key(table, fields, reference, reference_fields, None)
}

///|
fn check_foreign_key(
  table : Table,
  fields : Array[String],
  reference : Table,
  reference_fields : Array[String],
  cache : Map[(String, Array[String]), ForeignKeyIndex]?,
) -> Array[Diagnostic] {
  let id = (reference.name, reference_fields)
  if cache is Some(indexes) && indexes.get(id) is Some(index) {
    return index.validate(table, fields)
  }
  let (from, to, kinds) = match
    bind_foreign_key(table, fields, reference, reference_fields) {
    Ok(binding) => binding
    Err(error) => return [error]
  }
  match index_reference(reference, to, kinds) {
    Err(error) => [error]
    Ok(index) => {
      if cache is Some(indexes) {
        indexes[id] = index
      }
      index.check_rows(table, from, fields)
    }
  }
}

///|
/// Bind both sides in declaration order, without allocating a row-data index.
fn bind_foreign_key(
  table : Table,
  fields : Array[String],
  reference : Table,
  reference_fields : Array[String],
) -> Result[(Array[Int32], Array[Int32], Array[FieldType]), Diagnostic] {
  let from = match source_positions(table, fields, reference_fields.length()) {
    Ok(p) => p
    Err(error) => return Err(error)
  }
  let to = match field_positions(reference, reference_fields) {
    Ok(p) => p
    Err(message) =>
      return Err(issue("foreign-key-schema", table.name, 0, "", message))
  }
  let kinds = to.map(p => reference.fields[p].kind)
  if incompatible_fields(table, from, kinds) is Some(error) {
    return Err(error)
  }
  Ok((from, to, kinds))
}