///|
/// In-memory CSV with positions of data records. Header access returns a copy.
pub struct LookupTable {
  priv table : InputTable
  priv spans : Array[(Int32, Int32)]
}

///|
pub fn LookupTable::columns(self : LookupTable) -> Array[String] {
  self.table.header.copy()
}

///|
pub fn LookupTable::from_csv(
  name : String,
  csv : String,
) -> Result[LookupTable, String] {
  let spans = []
  let table = match
    csv_input(name, csv, default_csv_dialect(), None, false, on_span=(
      start,
      end,
    ) => spans.push((start, end))) {
    Err(message) => return Err(name + ": " + message)
    Ok(value) => value
  }
  let names : @hashset.HashSet[String] = @hashset.HashSet([])
  if table.header.is_empty() || spans.is_empty() {
    return Err(name + ": missing CSV header")
  }
  for column in table.header {
    if column.trim().is_empty() || !names.add_and_check(column) {
      return Err(name + ": empty or repeated column name")
    }
  }
  if spans.length() != table.rows.length() + 1 {
    return Err(name + ": record and line counts disagree")
  }
  for index, row in table.rows {
    if row.length() != table.header.length() {
      let (line, _) = spans[index + 1]
      return Err(
        name +
        ": CSV line " +
        line.to_string() +
        " has an unexpected number of columns",
      )
    }
  }
  Ok({ table, spans, })
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct LookupExample {
  key : Array[String]
  lines : (Int32, Int32)
  master_lines : Array[(Int32, Int32)]
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct LookupGroup {
  mut count : Int32
  examples : Array[LookupExample]
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct LookupReport {
  master_rows : Int32
  detail_rows : Int32
  matched : Int32
  missing_reference : LookupGroup
  ambiguous_reference : LookupGroup
  empty_reference : LookupGroup
  duplicate_master : LookupGroup
  empty_master : LookupGroup
  unused_master_keys : LookupGroup
}

///|
priv struct LookupEntry {
  key : Array[String]
  first : (Int32, Int32)
  mut second : (Int32, Int32)?
  mut used : Bool
}

///|
fn LookupGroup::new() -> LookupGroup {
  { count: 0, examples: [], }
}

///|
fn LookupTable::positions(
  self : LookupTable,
  columns : Array[String],
) -> Result[Array[Int32], String] {
  let result = []
  for column in columns {
    match self.table.header.search(column) {
      Some(i) if !result.contains(i) => result.push(i)
      _ =>
        return Err(
          self.table.name + ": unknown or repeated key column: " + column,
        )
    }
  }
  Ok(result)
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct LookupPreview {
  examples : Array[Array[String]]
  whitespace_rows : Int32
}

///|
/// All White_Space code points fit in UTF-16's BMP, including no-break and ideographic spaces.
fn trim_identifier(value : String) -> StringView {
  value.trim(
    chars="\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000",
  )
}

///|
/// Inspect original identifiers before choosing how to compare them.
pub fn LookupTable::preview_keys(
  self : LookupTable,
  columns : Array[String],
) -> Result[LookupPreview, String] {
  if columns.is_empty() {
    return Err("Select at least one key column")
  }
  let positions = match self.positions(columns) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let examples = []
  let mut whitespace_rows = 0
  for row in self.table.rows {
    if examples.length() < 3 {
      examples.push(positions.map(i => row[i]))
    }
    if positions.any(i => trim_identifier(row[i]).length() != row[i].length()) {
      whitespace_rows += 1
    }
  }
  Ok({ examples, whitespace_rows, })
}

///|
pub fn LookupReport::is_clean(self : LookupReport) -> Bool {
  self.matched == self.detail_rows &&
  self.duplicate_master.count == 0 &&
  self.empty_master.count == 0
}

///|
/// Reconcile textual identifiers, including tuple keys. Empty components never match;
/// leading zeros and case are significant. trim_keys opts into boundary whitespace removal. Examples are capped per category.
pub fn reconcile_tables(
  master : LookupTable,
  master_columns : Array[String],
  detail : LookupTable,
  detail_columns : Array[String],
  max_examples~ : Int32 = 5,
  trim_keys~ : Bool = false,
) -> Result[LookupReport, String] {
  run_lookup(
    master,
    master_columns,
    detail,
    detail_columns,
    max_examples,
    trim_keys,
    None,
  )
}

///|
#derive(Eq)
priv enum LookupFinding {
  MissingReference
  AmbiguousReference
  EmptyReference
  DuplicateMaster
  EmptyMaster
  UnusedMaster
}

///|
fn LookupFinding::is_master(self : LookupFinding) -> Bool {
  match self {
    DuplicateMaster | EmptyMaster | UnusedMaster => true
    MissingReference | AmbiguousReference | EmptyReference => false
  }
}

///|
fn run_lookup(
  master : LookupTable,
  master_columns : Array[String],
  detail : LookupTable,
  detail_columns : Array[String],
  max_examples : Int32,
  trim_keys : Bool,
  visit : ((LookupFinding, LookupExample) -> Unit)?,
  on_ready? : () -> Unit,
) -> Result[LookupReport, String] {
  fn record(
    group : LookupGroup,
    kind : LookupFinding,
    key : Array[String],
    lines : (Int32, Int32),
    master_lines : Array[(Int32, Int32)],
  ) -> Unit {
    group.count += 1
    if group.count <= max_examples || visit is Some(_) {
      let item = { key, lines, master_lines, }
      if group.count <= max_examples {
        group.examples.push(item)
      }
      if visit is Some(emit) {
        emit(kind, item)
      }
    }
  }
  if max_examples < 0 ||
    master_columns.is_empty() ||
    master_columns.length() != detail_columns.length() {
    return Err(
      "Expected equally many nonempty key columns and a nonnegative sample limit",
    )
  }
  let m = match master.positions(master_columns) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let d = match detail.positions(detail_columns) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  if on_ready is Some(start) {
    start()
  }
  let index : Map[Array[String], LookupEntry] = Map([])
  let order = []
  let duplicate_master = LookupGroup::new()
  let empty_master = LookupGroup::new()
  for i, row in master.table.rows {
    let raw = m.map(pos => row[pos])
    let key = if trim_keys {
      raw.map(v => trim_identifier(v).to_owned())
    } else {
      raw
    }
    let lines = master.spans[i + 1]
    if key.contains("") {
      record(empty_master, EmptyMaster, raw, lines, [])
    } else if index.get(key) is Some(entry) {
      if entry.second is None {
        entry.second = Some(lines)
      }
      record(duplicate_master, DuplicateMaster, raw, lines, [entry.first])
    } else {
      let entry = { key: raw, first: lines, second: None, used: false, }
      index[key] = entry
      order.push(entry)
    }
  }
  let missing_reference = LookupGroup::new()
  let ambiguous_reference = LookupGroup::new()
  let empty_reference = LookupGroup::new()
  let mut matched = 0
  for i, row in detail.table.rows {
    let raw = d.map(pos => row[pos])
    let key = if trim_keys {
      raw.map(v => trim_identifier(v).to_owned())
    } else {
      raw
    }
    let lines = detail.spans[i + 1]
    if key.contains("") {
      record(empty_reference, EmptyReference, raw, lines, [])
    } else if index.get(key) is Some(entry) {
      entry.used = true
      if entry.second is Some(other) {
        record(ambiguous_reference, AmbiguousReference, raw, lines, [
          entry.first,
          other,
        ])
      } else {
        matched += 1
      }
    } else {
      record(missing_reference, MissingReference, raw, lines, [])
    }
  }
  let unused_master_keys = LookupGroup::new()
  for entry in order {
    if !entry.used {
      record(unused_master_keys, UnusedMaster, entry.key, entry.first, [])
    }
  }
  Ok({
    master_rows: master.table.rows.length(),
    detail_rows: detail.table.rows.length(),
    matched,
    missing_reference,
    ambiguous_reference,
    empty_reference,
    duplicate_master,
    empty_master,
    unused_master_keys,
  })
}