///|
#derive(Debug)
pub(all) struct InputTable {
  name : String
  header : Array[String]
  rows : Array[Array[String]]
}

///|
#derive(Debug)
pub(all) struct PackageReport {
  tables : Array[Table]
  errors : Array[Diagnostic]
}

///|
pub fn PackageReport::valid(self : PackageReport) -> Bool {
  self.errors.is_empty()
}

///|
/// No I/O: a host may load local files or supply rows from any trusted source.
pub fn validate_package(
  descriptor : Descriptor,
  inputs : Array[InputTable],
) -> PackageReport {
  validate_inputs(descriptor, inputs, t => t.name, (resource, input) => {
    validate_table(
      resource.name,
      resource.fields,
      input.header,
      input.rows,
      missing_values=resource.missing_values,
      row_rules=resource.row_rules,
    )
  })
}

///|
/// Validate named, in-memory JSON tables using the descriptor's schemas and keys.
pub fn validate_json_package(
  descriptor : Descriptor,
  inputs : Array[JsonInputTable],
) -> PackageReport {
  validate_inputs(descriptor, inputs, t => t.name, (resource, input) => {
    validate_json_table(
      resource.name,
      resource.fields,
      input,
      missing_values=resource.missing_values,
      row_rules=resource.row_rules,
    )
  })
}

///|
fn[T] validate_inputs(
  descriptor : Descriptor,
  inputs : Array[T],
  name_of : (T) -> String,
  check_table : (Resource, T) -> TableReport,
  on_duplicate? : (String, Int32, Int32) -> Unit,
  on_relationships? : (ValidationPlan, RelationshipWork) -> Unit,
) -> PackageReport {
  let tables : Array[Table] = []
  let errors : Array[Diagnostic] = []
  if descriptor.resources.is_empty() {
    errors.push(issue("descriptor", "", 0, "", "resources cannot be empty"))
  }
  let resource_counts : Map[String, Int32] = Map([])
  for r in descriptor.resources {
    resource_counts[r.name] = resource_counts.get(r.name).unwrap_or(0) + 1
  }
  let input_counts : Map[String, Int32] = Map([])
  let inputs_by_name : Map[String, T] = Map([])
  for input in inputs {
    let name = name_of(input)
    input_counts[name] = input_counts.get(name).unwrap_or(0) + 1
    inputs_by_name[name] = input
  }
  for resource in descriptor.resources {
    if !valid_resource_name(resource.name) ||
      resource_counts[resource.name] != 1 {
      errors.push(
        issue(
          "descriptor",
          resource.name,
          0,
          "",
          "Resource names must be valid and unique",
        ),
      )
    }
    for key in resource.foreign_keys {
      if !resource_counts.contains(key.resource) {
        errors.push(
          issue(
            "foreign-key-schema",
            resource.name,
            0,
            "",
            "Unknown reference resource",
          ),
        )
      }
    }
  }
  for input in inputs {
    if !resource_counts.contains(name_of(input)) ||
      input_counts[name_of(input)] != 1 {
      errors.push(
        issue(
          "resource-input",
          name_of(input),
          0,
          "",
          "Unexpected or duplicate resource input",
        ),
      )
    }
  }
  for resource in descriptor.resources {
    if input_counts.get(resource.name) != Some(1) {
      errors.push(
        issue(
          "resource-input",
          resource.name,
          0,
          "",
          "Exactly one input table is required",
        ),
      )
      continue
    }
    let report = check_table(resource, inputs_by_name[resource.name])
    for e in report.errors {
      errors.push(e)
    }
    if report.valid() {
      if !resource.primary_key.is_empty() {
        for
          e in validate_primary_key(
            report.table,
            resource.primary_key,
            on_duplicate?,
          ) {
          errors.push(e)
        }
      }
      tables.push(report.table)
    }
  }
  if ValidationPlan::new(descriptor) is Ok(plan) {
    let available = Map([])
    for table in tables {
      available[table.name] = table
    }
    let result = plan.execute(available)
    for e in result.errors {
      errors.push(e)
    }
    if on_relationships is Some(emit) {
      emit(plan, result.work)
    }
    return { tables, errors, }
  }
  // Direct library callers can construct an invalid Descriptor. Retain the
  // existing per-edge diagnostics and still check its other usable relationships.
  let reference_indexes = Map([])
  // Validate each relationship only when its source and target table are usable.
  for resource in descriptor.resources {
    let sources = tables.filter(t => t.name == resource.name)
    if sources.length() != 1 {
      continue
    }
    for key in resource.foreign_keys {
      let targets = tables.filter(t => t.name == key.resource)
      if targets.length() != 1 {
        continue
      }
      for
        e in check_foreign_key(
          sources[0],
          key.fields,
          targets[0],
          key.reference_fields,
          Some(reference_indexes),
        ) {
        errors.push(e)
      }
    }
  }
  { tables, errors, }
}