///|
/// One diagnostic class. A foreign key depends on two field-valid resources.
#derive(ToJson)
pub(all) struct ExternalRule {
  code : String
  resource : String
  target : String
  field : String
}

///|
struct Projection {
  columns : Array[Int32]
  group : String
  role : String
  rule : Int32
}

///|
pub struct ExternalPlan {
  resources : Array[Resource]
  rules : Array[ExternalRule]
  priv projections : Array[Array[Projection]]
  priv row_rules : Array[Array[BoundRowRule]]
}

///|
/// Compile typed projections once, sharing target events across incoming keys.
pub fn ExternalPlan::new(
  descriptor : Descriptor,
) -> Result[ExternalPlan, Array[Diagnostic]] {
  let resources = descriptor.resources
  let projections : Array[Array[Projection]] = resources.map(_ => [])
  let rules : Array[ExternalRule] = []
  let targets : Map[(String, Array[String]), String] = Map([])
  let errors = []
  let row_rules = resources.map(r => {
    bind_row_rules(r.name, r.fields, r.row_rules, errors)
  })
  let tables = resources.map(r => {
    ({ name: r.name, fields: r.fields, rows: [], } : Table)
  })
  for i, resource in resources {
    if prop(descriptor.original, "resources") is Array(items) &&
      i < items.length() &&
      tabular_format(items[i]) != "csv" {
      errors.push(
        issue(
          "unsupported",
          resource.name,
          0,
          "format",
          "External validation requires CSV resources",
        ),
      )
    }
    check_field_definitions(resource.name, resource.fields, errors)
    fn duplicate_rule(names : Array[String], code : String) -> Unit {
      match field_positions(tables[i], names) {
        Err(message) =>
          errors.push(
            issue("primary-key-schema", resource.name, 0, "", message),
          )
        Ok(columns) => {
          let rule = rules.length()
          rules.push({
            code,
            resource: resource.name,
            target: "",
            field: names.join(", "),
          })
          projections[i].push({
            columns,
            group: "d" + rule.to_string(),
            role: "2",
            rule,
          })
        }
      }
    }
    for f in resource.fields {
      if f.unique {
        duplicate_rule([f.name], "unique")
      }
    }
    if !resource.primary_key.is_empty() {
      duplicate_rule(resource.primary_key, "primary-key-duplicate")
    }
    for fk in resource.foreign_keys {
      guard resources.search_by(r => r.name == fk.resource) is Some(j) else {
        errors.push(
          issue(
            "foreign-key-schema",
            resource.name,
            0,
            "",
            "Unknown reference resource",
          ),
        )
        continue
      }
      let (from, to, _) = match
        bind_foreign_key(tables[i], fk.fields, tables[j], fk.reference_fields) {
        Ok(binding) => binding
        Err(e) => {
          errors.push(e)
          continue
        }
      }
      let identity = (fk.resource, fk.reference_fields)
      let group = match targets.get(identity) {
        Some(g) => g
        None => {
          let g = "f" + targets.length().to_string()
          targets[identity] = g
          projections[j].push({ columns: to, group: g, role: "0", rule: -1, })
          g
        }
      }
      let rule = rules.length()
      rules.push({
        code: "foreign-key",
        resource: resource.name,
        target: fk.resource,
        field: fk.fields.join(", "),
      })
      projections[i].push({ columns: from, group, role: "1", rule, })
    }
  }
  if errors.is_empty() {
    Ok({ resources, rules, projections, row_rules, })
  } else {
    Err(errors)
  }
}

///|
/// A reversible tuple encoding for equality: type tags distinguish Cell variants;
/// JSON quotes each component so arbitrary field contents cannot join two keys.
fn spill_component(cell : Cell) -> String {
  match cell {
    Missing => ""
    TextValue(s) => "s" + s
    IntegerValue(i) => "i" + i.to_string()
    BigIntegerValue(i) => "I" + i.to_string()
    NumberValue(n) => if n == 0.0 { "n0" } else { "n" + n.to_string() }
    ExactNumberValue(d) => "d" + decimal_json(d).stringify()
    SpecialNumber(s) => "N" + s
    BooleanValue(b) => if b { "b1" } else { "b0" }
    StructuredValue(s) => "j" + s
    TemporalValue(s) => "t" + s
  }
}

///|
fn cast_projection_row(
  r : Resource,
  rules : Array[BoundRowRule],
  values : Array[String],
  missing : Array[String],
  row : Int32,
  diagnose : (Diagnostic) -> Unit,
) -> Array[Cell]? {
  if values.length() != r.fields.length() {
    diagnose(
      issue("row-width", r.name, row, "", "Row width differs from schema"),
    )
    return None
  }
  let cells = []
  let errors = []
  for col, f in r.fields {
    match cast_field_text(values[col], f, missing) {
      Err(message) => {
        errors.push(issue("type", r.name, row, f.name, message))
        cells.push(Missing)
      }
      Ok(cell) => {
        check_logical_cell(r.name, f, cell, row, false, errors)
        cells.push(cell)
      }
    }
  }
  check_row_rules(r.name, row, cells, rules, errors)
  for e in errors {
    diagnose(e)
  }
  Some(cells)
}

///|
fn projection_key(cells : Array[Cell], columns : Array[Int32]) -> String {
  @json.to_json(columns.map(i => spill_component(cells[i]))).stringify()
}

///|
/// The row is one-based across shards; line numbers are one-based within file.
#derive(ToJson, Eq, Debug)
pub(all) struct ExternalLocation {
  row : Int32
  file : Int32
  start_line : Int32
  end_line : Int32
}

///|
fn ExternalLocation::encode(self : ExternalLocation) -> String {
  let number = self.row.to_string()
  let padded = "0000000000".exact_view(start=number.length()).to_owned() +
    number
  padded +
  "," +
  self.file.to_string() +
  "," +
  self.start_line.to_string() +
  "," +
  self.end_line.to_string()
}

///|
fn decode_spill_location(s : String) -> ExternalLocation {
  let parts = s.split(",")
  fn number() -> Int32 {
    @string.parse_int(parts.next().unwrap().to_owned()) catch {
      _ => abort("Invalid run location")
    }
  }
  let row = number()
  let file = number()
  let start_line = number()
  let end_line = number()
  { row, file, start_line, end_line, }
}

///|
/// Feed one physical row. A host sorts emitted lines, merges its disk runs and
/// supplies them to ExternalKeyCursor. Emitters must preserve each line verbatim.
pub fn ExternalPlan::feed(
  self : ExternalPlan,
  table : Int32,
  values : Array[String],
  missing : Array[String],
  location : ExternalLocation,
  emit : (String) -> Unit,
  diagnose : (Int32, Diagnostic) -> Unit,
) -> Unit {
  let row = location.row
  guard table >= 0 &&
    table < self.resources.length() &&
    row > 0 &&
    location.file >= 0 &&
    location.start_line > 0 &&
    location.end_line >= location.start_line else {
    diagnose(
      -1,
      issue("input", "", row, "", "Invalid resource index or source location"),
    )
    return
  }
  let r = self.resources[table]
  guard cast_projection_row(r, self.row_rules[table], values, missing, row, e => {
      diagnose(-1, e)
    })
    is Some(cells) else {
    return
  }
  let position = location.encode()
  for p in self.projections[table] {
    if p.columns.any(i => cells[i] == Missing) {
      if p.rule >= 0 && self.rules[p.rule].code == "primary-key-duplicate" {
        diagnose(
          p.rule,
          issue(
            "primary-key-null",
            r.name,
            row,
            "",
            "Primary key contains a missing value",
          ),
        )
      }
      continue
    }
    let key = projection_key(cells, p.columns)
    let prefix = p.group + ":" + key + "\t" + p.role
    emit(
      if p.role == "0" {
        prefix
      } else {
        prefix + "\t" + position + "\t" + p.rule.to_string()
      },
    )
  }
}

///|
pub struct ExternalRun {
  priv lines : Array[String]
}

///|
pub fn ExternalRun::new() -> ExternalRun {
  { lines: [], }
}

///|
pub fn ExternalRun::add(self : ExternalRun, line : String) -> Unit {
  self.lines.push(line)
}

///|
pub fn ExternalRun::flush(self : ExternalRun, write : (String) -> Unit) -> Unit {
  // Spill files require lexical order. The default String order compares lengths first.
  self.lines.sort_by((a, b) => a.lexical_compare(b))
  for line in self.lines {
    write(line)
  }
  self.lines.clear()
}

///|
/// Merge a bounded number of sorted inputs; the empty string marks end of a run.
pub fn merge_external_runs(
  count : Int32,
  read : (Int32) -> String,
  write : (String) -> Unit,
) -> Unit {
  let heads = Array::makei(count, read)
  while true {
    let mut best = -1
    for i, line in heads {
      if line != "" && (best < 0 || line.lexical_compare(heads[best]) < 0) {
        best = i
      }
    }
    guard best >= 0 else { break }
    write(heads[best])
    heads[best] = read(best)
  }
}

///|
pub struct ExternalKeyCursor {
  priv mut key : String
  priv mut reference : Bool
  priv mut first : String
}

///|
pub fn ExternalKeyCursor::new() -> ExternalKeyCursor {
  { key: "", reference: false, first: "", }
}

///|
/// All references sort before probes for one key. Even a hot key needs one
/// previous location. The callback receives rule id, location and first duplicate location.
pub fn ExternalKeyCursor::feed(
  self : ExternalKeyCursor,
  line : String,
  report : (Int32, ExternalLocation, ExternalLocation?) -> Unit,
) -> Unit {
  let pieces = line.split("\t")
  let key = pieces.next().unwrap().to_owned()
  let role = pieces.next().unwrap()
  if key != self.key {
    self.key = key
    self.reference = false
    self.first = ""
  }
  if role == "0" {
    self.reference = true
    return
  }
  if role == "1" && self.reference {
    return
  }
  let location = pieces.next().unwrap().to_owned()
  if role == "2" && self.first == "" {
    self.first = location
    return
  }
  let id = @string.parse_int(pieces.next().unwrap().to_owned()) catch {
    _ => abort("Invalid run rule")
  }
  report(
    id,
    decode_spill_location(location),
    if self.first == "" {
      None
    } else {
      Some(decode_spill_location(self.first))
    },
  )
}