///|
#derive(Eq)
pub(all) enum StateChangeKind {
  Added
  Removed
  Changed
}

///|
pub extend StateChangeKind with Eq::{equal, not_equal}

///|
pub fn StateChangeKind::code(self : StateChangeKind) -> String {
  match self {
    Added => "added"
    Removed => "removed"
    Changed => "changed"
  }
}

///|
pub(all) struct StateChange {
  series : String
  kind : StateChangeKind
  paths : Array[String]
  before : Json?
  after : Json?
}

///|
pub(all) struct StateDiff {
  before_capacity : Int32
  after_capacity : Int32
  unchanged : Int32
  changes : Array[StateChange]
}

///|
// Fresh JSON values, using the checkpoint's exact numeric representations.
fn State::series_view(self : State, series : String) -> Json? {
  match self.index.get(series) {
    None => None
    Some(IntSlot(i)) => {
      let r = self.records[i]
      Some({
        "kind": "int64",
        "origin": Json(r.origin.to_string()),
        "lastStart": Json(r.last.start.to_string()),
        "lastEnd": Json(r.last.end.to_string()),
        "delta": Json(r.last.value.to_string()),
        "total": Json(r.total.to_string()),
      })
    }
    Some(DoubleSlot(i)) => {
      let r = self.doubles[i]
      Some({
        "kind": "double",
        "origin": Json(r.origin.to_string()),
        "lastStart": Json(r.last.start.to_string()),
        "lastEnd": Json(r.last.end.to_string()),
        "delta": Json(r.last.value),
        "total": Json(r.total),
      })
    }
    Some(HistogramSlot(i)) => {
      let r = self.histograms[i]
      Some({
        "kind": "histogram",
        "delta": histogram_json(r.last_hist),
        "total": histogram_json(r.total_hist),
      })
    }
    Some(ExponentialSlot(i)) => {
      let r = self.exponentials[i]
      Some({
        "kind": "exponential",
        "delta": exp_json(r.last_exp),
        "total": exp_json(r.total_exp),
      })
    }
  }
}

///|
fn pointer_key(key : String) -> String {
  key.replace_all(old="~", new="~0").replace_all(old="/", new="~1")
}

///|
// The budget is a refusal boundary, not a silently truncated report.
fn changed_paths(
  before : Json,
  after : Json,
  path : String,
  paths : Array[String],
  budget : Ref[Int32],
) -> Unit raise StitchError {
  if before == after {
    return
  }
  match (before, after) {
    (Object(a), Object(b)) => {
      let keys = a.keys().collect()
      for key in b.keys() {
        if !a.contains(key) {
          keys.push(key)
        }
      }
      keys.sort_by((a, b) => a.lexical_compare(b))
      for key in keys {
        let next = path + "/" + pointer_key(key)
        match (a.get(key), b.get(key)) {
          (Some(x), Some(y)) => changed_paths(x, y, next, paths, budget)
          _ => add_changed_path(next, paths, budget)
        }
      }
    }
    (Array(a), Array(b)) => {
      let size = if a.length() > b.length() { a.length() } else { b.length() }
      for i in 0.. changed_paths(x, y, next, paths, budget)
          _ => add_changed_path(next, paths, budget)
        }
      }
    }
    _ => add_changed_path(path, paths, budget)
  }
}

///|
fn add_changed_path(
  path : String,
  paths : Array[String],
  budget : Ref[Int32],
) -> Unit raise StitchError {
  if budget.val == 0 {
    raise Invalid("state diff exceeds changed-path budget")
  }
  budget.val -= 1
  paths.push(path)
}

///|
/// Compare logical records, independent of checkpoint version/arrival order.
/// Sorted changes contain detached before/after values and RFC 6901 paths
/// relative to each series view. This is a difference report, not a proof of
/// lineage, valid accumulation, delivery, or a patch to apply to state.
///
/// ```mbt check
/// test {
///   let a = @metricstitch.State::new()
///   assert_eq(a.diff(a).changes.length(), 0)
/// }
/// ```
pub fn State::diff(
  self : State,
  other : State,
  max_changes~ : Int32 = 1024,
  max_paths~ : Int32 = 4096,
) -> StateDiff raise StitchError {
  if max_changes < 1 ||
    max_changes > 100000 ||
    max_paths < 1 ||
    max_paths > 100000 {
    raise Invalid("state diff budgets must be in 1..100000")
  }
  let keys = self.index.keys().collect()
  for key in other.index.keys() {
    if !self.index.contains(key) {
      keys.push(key)
    }
  }
  keys.sort_by((a, b) => a.lexical_compare(b))
  let changes : Array[StateChange] = []
  let budget = Ref(max_paths)
  let mut unchanged = 0
  for series in keys {
    let before = self.series_view(series)
    let after = other.series_view(series)
    if before == after {
      unchanged += 1
      continue
    }
    if changes.length() == max_changes {
      raise Invalid("state diff exceeds changed-series budget")
    }
    let paths : Array[String] = []
    let kind = match (before, after) {
      (None, Some(_)) => {
        add_changed_path("", paths, budget)
        Added
      }
      (Some(_), None) => {
        add_changed_path("", paths, budget)
        Removed
      }
      (Some(a), Some(b)) => {
        changed_paths(a, b, "", paths, budget)
        Changed
      }
      _ => abort("union of state identities")
    }
    changes.push({ series, kind, paths, before, after, })
  }
  {
    before_capacity: self.limit,
    after_capacity: other.limit,
    unchanged,
    changes,
  }
}

///|
/// Each call returns a detached JSON report, including detached nested arrays.
pub fn StateDiff::to_json(self : StateDiff) -> Json {
  {
    "beforeCapacity": Json(self.before_capacity),
    "afterCapacity": Json(self.after_capacity),
    "unchanged": Json(self.unchanged),
    "changes": Json::array(
      self.changes.map(c => {
        "series": Json(c.series),
        "kind": Json(c.kind.code()),
        "paths": Json::array(c.paths.map(p => Json(p))),
        "before": match c.before {
          Some(v) => detached_json(v)
          None => Json(null)
        },
        "after": match c.after {
          Some(v) => detached_json(v)
          None => Json(null)
        },
      }),
    ),
  }
}