///|
#derive(ToJson, Eq, Debug)
pub(all) struct ReferenceChange {
  key : Array[String]
  reason : String
  old_reference : Array[String]?
  new_reference : Array[String]?
  old_child_lines : (Int32, Int32)?
  new_child_lines : (Int32, Int32)?
  old_parent_lines : Array[(Int32, Int32)]
  new_parent_lines : Array[(Int32, Int32)]
  old_status : String
  new_status : String
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct ReferenceImpact {
  findings : Array[ReferenceChange]
  child_conflicts : Array[CsvKeyConflict]
  parent_conflicts : Array[CsvKeyConflict]
}

///|
/// Empty foreign keys carry no reference. Ambiguous or missing current references
/// and ambiguous/incomplete source identities require review.
pub fn ReferenceImpact::is_clean(self : ReferenceImpact) -> Bool {
  self.child_conflicts.is_empty() &&
  self.parent_conflicts.is_empty() &&
  !self.findings.any(f => {
    f.new_status == "missing" || f.new_status == "ambiguous"
  })
}

///|
priv enum ReferenceMatch {
  NoChild
  BlankReference
  NotFound
  SeveralTargets
  OneTarget((Int32, Int32))
}

///|
fn ReferenceMatch::label(self : ReferenceMatch) -> String {
  match self {
    NoChild => "absent"
    BlankReference => "empty"
    NotFound => "missing"
    SeveralTargets => "ambiguous"
    OneTarget(_) => "matched"
  }
}

///|
/// Locations for duplicate targets live once in parent_conflicts. Copying every
/// target span into every affected child would grow quadratically with duplicates.
fn ReferenceMatch::lines(self : ReferenceMatch) -> Array[(Int32, Int32)] {
  match self {
    OneTarget(lines) => [lines]
    _ => []
  }
}

///|
fn CsvSnapshotIndex::resolve_reference(
  self : CsvSnapshotIndex,
  reference : Array[String]?,
) -> ReferenceMatch {
  match reference {
    None => NoChild
    Some(key) if key.contains("") => BlankReference
    Some(key) =>
      match self.by_key.get(key) {
        None => NotFound
        Some([i]) => OneTarget(self.span(i))
        Some(_) => SeveralTargets
      }
  }
}

///|
fn reference_change_reason(
  before : ReferenceMatch,
  after : ReferenceMatch,
  same_reference : Bool,
  old_match_for_current_ref : ReferenceMatch,
) -> String? {
  match after {
    OneTarget(_) =>
      match before {
        NotFound | SeveralTargets | BlankReference => Some("restored")
        _ => None
      }
    NoChild =>
      match before {
        NotFound | SeveralTargets | BlankReference => Some("source_removed")
        _ => None
      }
    SeveralTargets => Some("ambiguous_target")
    BlankReference => Some("empty_reference")
    NotFound =>
      match before {
        NotFound if same_reference => Some("already_missing")
        SeveralTargets => Some("ambiguous_target")
        _ if old_match_for_current_ref is SeveralTargets =>
          Some("ambiguous_target")
        NoChild => Some("source_added")
        OneTarget(_) if same_reference => Some("target_removed")
        _ => Some("reference_changed")
      }
  }
}

///|
/// Compare one foreign-key relationship across two snapshots. Each child record
/// needs a stable unique identity separate from the foreign key. Attribute a new
/// failure to a target deletion only when the same child kept the same reference
/// and a previously unique target disappeared.
pub fn compare_reference_impact(
  old_parent : LookupTable,
  new_parent : LookupTable,
  old_child : LookupTable,
  new_child : LookupTable,
  parent_key : Array[String],
  child_key : Array[String],
  references : Array[String],
) -> Result[ReferenceImpact, String] {
  if references.is_empty() || references.length() != parent_key.length() {
    return Err(
      "Select equally many nonempty parent key and foreign key columns",
    )
  }
  let before_parent = match CsvSnapshotIndex::new(old_parent, parent_key) {
    Ok(index) => index
    Err(e) => return Err(e)
  }
  let after_parent = match CsvSnapshotIndex::new(new_parent, parent_key) {
    Ok(index) => index
    Err(e) => return Err(e)
  }
  let before_child = match CsvSnapshotIndex::new(old_child, child_key) {
    Ok(index) => index
    Err(e) => return Err(e)
  }
  let after_child = match CsvSnapshotIndex::new(new_child, child_key) {
    Ok(index) => index
    Err(e) => return Err(e)
  }
  let before_fk = match old_child.positions(references) {
    Ok(cols) => cols
    Err(e) => return Err(e)
  }
  let after_fk = match new_child.positions(references) {
    Ok(cols) => cols
    Err(e) => return Err(e)
  }
  let findings = []
  let parent_conflicts = visit_csv_keys(before_parent, after_parent, (_, _, _) => {
    ()
  })
  let child_conflicts = visit_csv_keys(before_child, after_child, (key, i, j) => {
    let old_reference = i.map(row => {
      before_fk.map(col => old_child.table.rows[row][col])
    })
    let new_reference = j.map(row => {
      after_fk.map(col => new_child.table.rows[row][col])
    })
    let before = before_parent.resolve_reference(old_reference)
    let after = after_parent.resolve_reference(new_reference)
    if reference_change_reason(
        before,
        after,
        old_reference == new_reference,
        before_parent.resolve_reference(new_reference),
      )
      is Some(reason) {
      findings.push({
        key,
        reason,
        old_reference,
        new_reference,
        old_child_lines: i.map(row => before_child.span(row)),
        new_child_lines: j.map(row => after_child.span(row)),
        old_parent_lines: before.lines(),
        new_parent_lines: after.lines(),
        old_status: before.label(),
        new_status: after.label(),
      })
    }
  })
  Ok({ findings, child_conflicts, parent_conflicts, })
}