///|
priv struct BoundProbe {
  ordinal : Int32
  source : Int32
  columns : Array[Int32]
  fields : Array[String]
  label : String
  referenced_fields : Array[String]
}

///|
priv struct IndexTask {
  target : Int32
  columns : Array[Int32]
  probes : Array[BoundProbe]
}

///|
/// Compilation appends a source's rules contiguously. Visit a slice without copying it.
fn IndexTask::each_source(
  self : IndexTask,
  visit : (Int32, ArrayView[BoundProbe]) -> Unit,
) -> Unit {
  let mut first = 0
  while first < self.probes.length() {
    let src = self.probes[first].source
    let mut end = first + 1
    while end < self.probes.length() && self.probes[end].source == src {
      end += 1
    }
    visit(src, self.probes[first:end])
    first = end
  }
}

///|
priv struct PlanTable {
  name : String
  layout : Array[(String, FieldType)]
}

///|
/// A schema-only relationship schedule. It can be reused for new batches.
/// All target indexes are scoped to one execution.
pub struct ValidationPlan {
  priv tables : Array[PlanTable]
  priv stages : Array[Array[Int32]]
  priv cyclic : Array[Bool]
  priv tasks : Array[IndexTask]
  priv rule_count : Int32
}

///|
pub fn ValidationPlan::new(
  d : Descriptor,
) -> Result[ValidationPlan, Array[Diagnostic]] {
  let resources = d.resources
  let n = resources.length()
  let by_name : Map[String, Int32] = Map([])
  let errors = []
  if n == 0 {
    errors.push(issue("descriptor", "", 0, "", "resources cannot be empty"))
  }
  let schemas = resources.map(r => {
    ({ name: r.name, fields: r.fields, rows: [], } : Table)
  })
  for i, r in resources {
    if !valid_resource_name(r.name) || by_name.contains(r.name) {
      errors.push(
        issue(
          "descriptor",
          r.name,
          0,
          "",
          "Resource names must be valid and unique",
        ),
      )
    }
    by_name[r.name] = i
  }
  let grouped : Array[Array[IndexTask]] = Array::makei(n, _ => [])
  let groups : Map[(Int32, Array[Int32]), IndexTask] = Map([])
  let dependencies : Array[Array[Int32]] = Array::makei(n, _ => [])
  let dependents : Array[Array[Int32]] = Array::makei(n, _ => [])
  let self_edge = Array::make(n, false)
  let mut ordinal = 0
  for source, r in resources {
    for fk in r.foreign_keys {
      guard by_name.get(fk.resource) is Some(target) else {
        errors.push(
          issue(
            "foreign-key-schema",
            r.name,
            0,
            "",
            "Unknown reference resource: " + fk.resource,
          ),
        )
        continue
      }
      let (from, to, _) = match
        bind_foreign_key(
          schemas[source],
          fk.fields,
          schemas[target],
          fk.reference_fields,
        ) {
        Ok(binding) => binding
        Err(e) => {
          errors.push(e)
          continue
        }
      }
      // Reorder *both* sides by target column position. (x,y)->(b,a)
      // becomes (y,x)->(a,b); its diagnostic still names x,y in declared order.
      let order = Array::makei(to.length(), i => i)
      order.sort_by_key(i => to[i])
      let columns = order.map(i => to[i])
      let identity = (target, columns)
      let task = match groups.get(identity) {
        Some(task) => task
        None => {
          let task : IndexTask = { target, columns, probes: [], }
          groups[identity] = task
          grouped[target].push(task)
          task
        }
      }
      task.probes.push({
        ordinal,
        source,
        columns: order.map(i => from[i]),
        fields: fk.fields.copy(),
        label: fk.fields.join(", "),
        referenced_fields: fk.reference_fields.copy(),
      })
      ordinal += 1
      dependencies[source].push(target)
      dependents[target].push(source)
      if source == target {
        self_edge[target] = true
      }
    }
  }
  if !errors.is_empty() {
    return Err(errors)
  }
  let stages = relationship_components(dependents, dependencies)
  let tasks = []
  for members in stages {
    for target in members {
      for task in grouped[target] {
        tasks.push(task)
      }
    }
  }
  Ok({
    tables: resources.map(r => {
      name: r.name,
      layout: r.fields.map(f => (f.name, f.kind)),
    }),
    stages,
    cyclic: stages.map(s => s.length() > 1 || self_edge[s[0]]),
    tasks,
    rule_count: ordinal,
  })
}

///|
/// Dependency-first components and the declared pairings served by each index.
pub fn ValidationPlan::explain(self : ValidationPlan) -> Json {
  {
    "relationshipCount": self.rule_count,
    "indexCount": self.tasks.length(),
    "stages": Json::array(
      Array::makei(self.stages.length(), i => {
        (
          {
            "resources": @json.to_json(
              self.stages[i].map(v => self.tables[v].name),
            ),
            "cyclic": self.cyclic[i],
          } : Json)
      }),
    ),
    "indexes": Json::array(
      self.tasks.map(task => {
        (
          {
            "target": self.tables[task.target].name,
            "fields": @json.to_json(
              task.columns.map(i => self.tables[task.target].layout[i].0),
            ),
            "rules": Json::array(
              task.probes.map(p => {
                (
                  {
                    "source": self.tables[p.source].name,
                    "fields": @json.to_json(p.fields),
                    "referenceFields": @json.to_json(p.referenced_fields),
                  } : Json)
              }),
            ),
          } : Json)
      }),
    ),
  }
}