///|
#derive(Debug, Eq, ToJson)
pub(all) struct RelationshipWork {
  indexes_built : Int32
  index_rows : Int64
  source_rows : Int64
  probe_rows : Int64
  checked_rules : Int32
  skipped_rules : Int32
}

///|
/// Predict target row visits and per-rule source row visits, given valid tables.
/// Counts are logical work units independent of data distribution and hardware.
pub fn ValidationPlan::estimate(
  self : ValidationPlan,
  row_counts : Map[String, Int32],
) -> Result[RelationshipWork, String] {
  let counts = []
  for t in self.tables {
    guard row_counts.get(t.name) is Some(count) && count >= 0 else {
      return Err("Missing or negative row count for " + t.name)
    }
    counts.push(count.to_int64())
  }
  if row_counts.length() != counts.length() {
    return Err("Unexpected resource in row counts")
  }
  let mut index_rows = 0L
  let mut source_rows = 0L
  let mut probe_rows = 0L
  for task in self.tasks {
    index_rows += counts[task.target]
    task.each_source((src, probes) => {
      source_rows += counts[src]
      probe_rows += counts[src] * probes.length().to_int64()
    })
  }
  Ok({
    indexes_built: self.tasks.length(),
    index_rows,
    source_rows,
    probe_rows,
    checked_rules: self.rule_count,
    skipped_rules: 0,
  })
}

///|
pub(all) struct RelationshipReport {
  errors : Array[Diagnostic]
  work : RelationshipWork
}

///|
/// Run on already field-validated logical tables, in any input order. Key
/// definitions are frozen in the plan; each call uses the current table rows.
pub fn ValidationPlan::validate(
  self : ValidationPlan,
  tables : Array[Table],
) -> RelationshipReport {
  let available : Map[String, Table] = Map([])
  let errors = []
  let names = Map([])
  for shape in self.tables {
    names[shape.name] = true
  }
  for table in tables {
    if !names.contains(table.name) || available.contains(table.name) {
      errors.push(
        issue(
          "resource-input",
          table.name,
          0,
          "",
          "Unexpected or duplicate resource input",
        ),
      )
    }
    available[table.name] = table
  }
  for shape in self.tables {
    match available.get(shape.name) {
      None =>
        errors.push(
          issue(
            "resource-input",
            shape.name,
            0,
            "",
            "Missing table for relationship plan",
          ),
        )
      Some(table) =>
        if shape.layout != table.fields.map(f => (f.name, f.kind)) {
          errors.push(
            issue(
              "foreign-key-schema",
              shape.name,
              0,
              "",
              "Field names, order or types differ from the plan",
            ),
          )
        }
    }
  }
  if !errors.is_empty() {
    return {
      errors,
      work: {
        indexes_built: 0,
        index_rows: 0L,
        source_rows: 0L,
        probe_rows: 0L,
        checked_rules: 0,
        skipped_rules: self.rule_count,
      },
    }
  }
  self.execute(available)
}

///|
/// A target's FK violations do not invalidate its typed rows. This is why a
/// cycle can be checked without recursive validation or special input ordering.
fn ValidationPlan::execute(
  self : ValidationPlan,
  available : Map[String, Table],
) -> RelationshipReport {
  let by_rule : Array[Array[Diagnostic]] = Array::makei(self.rule_count, _ => [])
  let mut checked_rules = 0
  let mut indexes_built = 0
  let mut index_rows = 0L
  let mut source_rows = 0L
  let mut probe_rows = 0L
  for task in self.tasks {
    guard available.get(self.tables[task.target].name) is Some(target) &&
      task.probes.any(p => available.contains(self.tables[p.source].name)) else {
      continue
    }
    let index = index_reference(
      target,
      task.columns,
      task.columns.map(i => target.fields[i].kind),
    )
    if index is Ok(_) {
      indexes_built += 1
      index_rows += target.rows.length().to_int64()
    }
    task.each_source((src, probes) => {
      guard available.get(self.tables[src].name) is Some(source) else { return }
      match index {
        Err(e) =>
          for p in probes {
            by_rule[p.ordinal].push(e)
          }
        Ok(keys) => {
          checked_rules += probes.length()
          source_rows += source.rows.length().to_int64()
          probe_rows += source.rows.length().to_int64() *
            probes.length().to_int64()
          for i, row in source.rows {
            for p in probes {
              if keys.check_row(source, row, i + 1, p.columns, p.label)
                is Some(e) {
                by_rule[p.ordinal].push(e)
              }
            }
          }
        }
      }
    })
  }
  let errors = []
  for bucket in by_rule {
    for e in bucket {
      errors.push(e)
    }
  }
  {
    errors,
    work: {
      indexes_built,
      index_rows,
      source_rows,
      probe_rows,
      checked_rules,
      skipped_rules: self.rule_count - checked_rules,
    },
  }
}