///|
fn optional_object(
  value : Json?,
  name : String,
) -> Map[String, Json] raise ContractError {
  match value {
    None => Map([])
    Some(raw) => object(raw, name)
  }
}

///|
priv enum NumberConversion {
  Multiply(Int32)
  Divide(Int32)
}

///|
priv struct Migration {
  renames : Map[String, String]
  merge_equal_renames : Bool
  defaults : Map[String, Json]
  null_replacements : Map[String, Json]
  drops : Map[String, Bool]
  remaps : Map[String, Map[String, Json]]
  numbers : Map[String, NumberConversion]
}

///|
fn read_remaps(
  raw : Json?,
  source : Contract,
  target : Contract,
  moves : Map[String, String],
  drops : Map[String, Bool],
) -> Map[String, Map[String, Json]] raise ContractError {
  let remaps = optional_object(raw, "remap")
  if remaps.length() > 64 {
    raise ContractError("remap accepts at most 64 fields")
  }
  let validated : Map[String, Map[String, Json]] = Map([])
  for name in remaps.keys() {
    if drops.contains(name) {
      raise ContractError("cannot drop and remap the same field: " + name)
    }
    let dest = moves.get(name).unwrap_or(name)
    guard source.fields.get(name) is Some(old_field) &&
      target.fields.get(dest) is Some(new_field) else {
      raise ContractError(
        "remap must name a retained or renamed source field: " + name,
      )
    }
    guard remaps[name] is Object(choices) &&
      choices.length() > 0 &&
      choices.length() <= 32 else {
      raise ContractError("remap field must contain 1..32 choices: " + name)
    }
    let copy : Map[String, Json] = Map([])
    let remap_to_null = new_field.nullable && new_field.domain is Text(_)
    for label, replacement in choices {
      if label.length() > 128 || !accepts(old_field.domain, Json::string(label)) {
        raise ContractError("remap key must be a valid source choice: " + name)
      }
      let valid_choice = match replacement {
        Null => remap_to_null
        String(value) =>
          value.length() <= 128 && accepts(new_field.domain, replacement)
        _ => false
      }
      guard valid_choice else {
        raise ContractError(
          "remap value must be a valid target choice: " + dest,
        )
      }
      copy[label] = replacement
    }
    validated[name] = copy
  }
  validated
}

///|
fn read_factors(
  raw : Json?,
  operation : String,
  source : Contract,
  target : Contract,
  moves : Map[String, String],
  drops : Map[String, Bool],
) -> Map[String, Int32] raise ContractError {
  let spec = optional_object(raw, operation)
  if spec.length() > 64 {
    raise ContractError(operation + " accepts at most 64 fields")
  }
  let factors : Map[String, Int32] = Map([])
  for name, value in spec {
    if drops.contains(name) {
      raise ContractError(
        "cannot drop and " + operation + " the same field: " + name,
      )
    }
    let dest = moves.get(name).unwrap_or(name)
    guard source.fields.get(name) is Some(old_field) &&
      old_field.domain is Integer(_, _) &&
      target.fields.get(dest) is Some(new_field) &&
      new_field.domain is Integer(_, _) else {
      raise ContractError(operation + " must link integer fields: " + name)
    }
    guard integer_value(value) is Some(factor) && factor > 0 else {
      raise ContractError(
        operation + " factor must be an integer in 1..1000000: " + name,
      )
    }
    factors[name] = factor
  }
  factors
}

///|
fn read_migration(
  raw : Json,
  source : Contract,
  target : Contract,
) -> Migration raise ContractError {
  let spec = object(raw, "migration")
  keys(spec, [
    "rename", "defaults", "drop", "remap", "scale", "divide", "replace_null", "merge_equal_renames",
  ])
  let merge_equal_renames = boolean_option(
    spec.get("merge_equal_renames"),
    "merge_equal_renames",
  )
  let renames = optional_object(spec.get("rename"), "rename")
  let defaults = optional_object(spec.get("defaults"), "defaults")
  if renames.length() > 64 || defaults.length() > 64 {
    raise ContractError("migration accepts at most 64 renames and 64 defaults")
  }
  let moves : Map[String, String] = Map([])
  let destinations : Map[String, Bool] = Map([])
  for name in renames.keys() {
    guard renames[name] is String(dest) &&
      name != dest &&
      (source.open || source.fields.contains(name)) &&
      target.fields.contains(dest) else {
      raise ContractError(
        "rename must link distinct fields allowed by the source and declared by the target: " +
        name,
      )
    }
    if destinations.contains(dest) && !merge_equal_renames {
      raise ContractError("duplicate rename destination: " + dest)
    }
    moves[name] = dest
    destinations[dest] = true
  }
  for name in defaults.keys() {
    guard target.fields.get(name) is Some(field) &&
      accepts_value(field, defaults[name]) else {
      raise ContractError(
        "default must match its declared target field: " + name,
      )
    }
  }
  let null_replacements = optional_object(
    spec.get("replace_null"),
    "replace_null",
  )
  if null_replacements.length() > 64 {
    raise ContractError("replace_null accepts at most 64 fields")
  }
  for name, replacement in null_replacements {
    guard target.fields.get(name) is Some(field) &&
      accepts(field.domain, replacement) else {
      raise ContractError(
        "replace_null must give a non-null value matching its target field: " +
        name,
      )
    }
  }
  let drops : Map[String, Bool] = Map([])
  if spec.get("drop") is Some(drop) {
    guard drop is Array(names) && names.length() <= 64 else {
      raise ContractError("drop must be an array of at most 64 field names")
    }
    for raw_name in names {
      guard raw_name is String(name) &&
        (source.open || source.fields.contains(name)) &&
        (!target.fields.contains(name) || destinations.contains(name)) else {
        raise ContractError("drop must name a retired source field")
      }
      if moves.contains(name) {
        raise ContractError("cannot drop and rename the same field: " + name)
      }
      if drops.contains(name) {
        raise ContractError("duplicate drop field: " + name)
      }
      drops[name] = true
    }
  }
  let remaps = read_remaps(spec.get("remap"), source, target, moves, drops)
  let scales = read_factors(
    spec.get("scale"),
    "scale",
    source,
    target,
    moves,
    drops,
  )
  let divisors = read_factors(
    spec.get("divide"),
    "divide",
    source,
    target,
    moves,
    drops,
  )
  let numbers : Map[String, NumberConversion] = Map([])
  for name, factor in scales {
    numbers[name] = Multiply(factor)
  }
  for name, divisor in divisors {
    if numbers.contains(name) {
      raise ContractError("cannot scale and divide the same field: " + name)
    }
    numbers[name] = Divide(divisor)
  }
  {
    renames: moves,
    merge_equal_renames,
    defaults: defaults.copy(),
    null_replacements: null_replacements.copy(),
    drops,
    remaps,
    numbers,
  }
}

///|
fn check_entry(code : String, position : Int32, details : Json) -> Json {
  Json::object(
    Map([
      ("index", Json::number(position.to_double())),
      ("outcome", Json::string(code)),
      ("details", details),
    ]),
  )
}

///|
fn migration_issues(items : Array[Violation]) -> Json {
  Json::array(
    items.map(item => {
      Json::object(
        Map([
          ("field", Json::string(item.field)),
          ("reason", Json::string(item.reason)),
        ]),
      )
    }),
  )
}

///|
pub struct Rehearsal {
  priv source : Contract
  priv target : Contract
  priv rules : Migration
  priv default_names : Array[String]
  priv affected_names : Array[String]
  priv rewrite_fields : Map[String, Bool]
  priv null_replacement_names : Array[String]
  priv diagnostic_names : Array[String]
  priv complete_source_names : Array[String]?
}

///|
/// Validate and retain the rules for repeated batches.
pub fn prepare_rehearsal(
  source : Contract,
  target : Contract,
  migration : Json,
) -> Rehearsal raise ContractError {
  let rules = read_migration(migration, source, target)
  let default_names : Array[String] = []
  for name in rules.defaults.keys() {
    default_names.push(name)
  }
  default_names.sort()
  let rewrite_fields : Map[String, Bool] = Map([])
  for
    keys in [
      rules.renames.keys(),
      rules.drops.keys(),
      rules.remaps.keys(),
      rules.numbers.keys(),
    ] {
    for name in keys {
      rewrite_fields[name] = true
    }
  }
  let affected_names = rewrite_fields.keys().to_array()
  let null_replacement_names = rules.null_replacements.keys().to_array()
  // Rename destinations and null replacements must be processed during a rewrite,
  // but presence alone triggers migration only for rename, drop, remap, and conversion inputs.
  for names in [rules.renames.values(), null_replacement_names.iter()] {
    for name in names {
      if !rewrite_fields.contains(name) {
        rewrite_fields[name] = false
      }
    }
  }
  let complete_source_names = if source.open {
    None
  } else {
    Some(source.ordered.map(entry => entry.0))
  }
  let diagnostic_names = if !target.open {
    []
  } else if complete_source_names is Some(names) {
    // A validated closed source record can only contain these declarations.
    names.filter(name => {
      target.fields.contains(name) || rules.renames.contains(name)
    })
  } else {
    let names : Map[String, Bool] = Map([])
    for name in target.fields.keys() {
      names[name] = true
    }
    for name in rules.renames.keys() {
      names[name] = true
    }
    let ordered = names.keys().to_array()
    ordered.sort()
    ordered
  }
  {
    source,
    target,
    rules,
    default_names,
    diagnostic_names,
    complete_source_names,
    affected_names,
    rewrite_fields,
    null_replacement_names,
  }
}

///|
fn valid_batch_size(records : Array[Json]) -> Bool {
  records.length() > 0 && records.length() <= 256
}

///|
/// Apply the prepared rules and return the report and readiness verdict.
pub fn Rehearsal::run(
  self : Rehearsal,
  records : Array[Json],
  diagnostics~ : Bool = false,
) -> (Json, Bool) raise ContractError {
  if !valid_batch_size(records) {
    raise ContractError("rehearsal requires 1..256 records")
  }
  apply_batch(self, records, !diagnostics)
}

///|
fn rehearse(request : Map[String, Json]) -> (Json, Bool) raise ContractError {
  keys(request, ["mode", "source", "target", "migration", "records", "report"])
  let include_values = match request.get("report") {
    None | Some(String("full")) => true
    Some(String("diagnostics")) => false
    _ => raise ContractError("report must be full or diagnostics")
  }
  guard request.get("source") is Some(old_schema) &&
    request.get("target") is Some(new_schema) &&
    request.get("migration") is Some(migration) &&
    request.get("records") is Some(Array(records)) &&
    valid_batch_size(records) else {
    raise ContractError(
      "rehearse requires source, target, migration and 1..256 records",
    )
  }
  let plan = prepare_rehearsal(
    parse_contract(old_schema),
    parse_contract(new_schema),
    migration,
  )
  apply_batch(plan, records, include_values)
}

///|
priv enum PreviewContainer {
  PreviewObject(Map[String, Json], Map[String, Json])
  PreviewArray(Array[Json])
}

///|
/// Detach nested arrays and objects from the input before returning a preview.
fn detach_preview_fields(fields : Map[String, Json]) -> Unit {
  let pending : Array[PreviewContainer] = []
  let copy_node = fn(value : Json) -> Json {
    match value {
      Object(source) => {
        let target : Map[String, Json] = Map([], capacity=source.length())
        pending.push(PreviewObject(source, target))
        Json::object(target)
      }
      Array(source) => {
        let target = source.copy()
        pending.push(PreviewArray(target))
        Json::array(target)
      }
      _ => value
    }
  }
  // The record map is already owned by this preview. Replace only child containers.
  for name, value in fields {
    match value {
      Object(_) | Array(_) => fields[name] = copy_node(value)
      _ => ()
    }
  }
  while pending.pop() is Some(container) {
    match container {
      PreviewObject(source, target) =>
        for name, child in source {
          target[name] = copy_node(child)
        }
      PreviewArray(target) =>
        // The array copy already owns its slots. Detach only container elements.
        for i, child in target {
          match child {
            Object(_) | Array(_) => target[i] = copy_node(child)
            _ => ()
          }
        }
    }
  }
}

///|
fn apply_batch(
  plan : Rehearsal,
  records : Array[Json],
  include_values : Bool,
) -> (Json, Bool) {
  let {
    source,
    target,
    rules,
    default_names,
    affected_names,
    rewrite_fields,
    null_replacement_names,
    diagnostic_names,
    complete_source_names,
  } = plan
  let {
    renames,
    merge_equal_renames,
    defaults,
    null_replacements,
    drops,
    remaps,
    numbers,
  } = rules
  let has_renames = !renames.is_empty()
  let mut passed = 0
  let entries = records.mapi((i, record) => {
    let source_issues = validate(source, record)
    if !source_issues.is_empty() {
      return check_entry("source_rejected", i, migration_issues(source_issues))
    }
    guard record is Object(original) else {
      abort("validated record must be an object")
    }
    let has_affected_field = if original.length() < affected_names.length() / 2 {
      original.keys().any(name => rewrite_fields.get(name) is Some(true))
    } else {
      affected_names.any(name => original.contains(name))
    }
    let needs_migration = has_affected_field ||
      default_names.any(name => !original.contains(name)) ||
      null_replacement_names.any(name => original.get(name) is Some(Null))
    let updated = if !include_values && !needs_migration {
      record
    } else {
      // A validated closed record with this count has every declared field.
      let complete_order = complete_source_names.filter(names => {
        names.length() == original.length()
      })
      // An open target accepts unrelated fields, and diagnostics omit preview values.
      let original_names = if !include_values &&
        target.open &&
        diagnostic_names.length() < original.length() {
        if complete_order is Some(_) {
          diagnostic_names
        } else {
          diagnostic_names.filter(name => original.contains(name))
        }
      } else if complete_order is Some(names) {
        names
      } else {
        let names = original.keys().to_array()
        names.sort()
        names
      }
      // Use a conservative hint when active rules can drop fields.
      let capacity = (original_names.length() - drops.length()).max(0)
      let changed : Map[String, Json] = Map([], capacity~)
      if needs_migration {
        let skip_unrelated = rewrite_fields.length() <
          original_names.length() / 2
        for name in original_names {
          if skip_unrelated && !rewrite_fields.contains(name) {
            changed[name] = original[name]
            continue
          }
          if drops.contains(name) {
            continue
          }
          let to = if has_renames {
            renames.get(name).unwrap_or(name)
          } else {
            name
          }
          // Only renames can send two original keys to the same destination.
          let previous = if has_renames { changed.get(to) } else { None }
          if previous is Some(_) && !merge_equal_renames {
            return check_entry("rename_collision", i, Json::string(to))
          }
          let value = original[name]
          let migrated = match value {
            Null => null_replacements.get(to).unwrap_or(value)
            Number(raw, ..) =>
              match numbers.get(name) {
                // Conversion rules only reference validated integer fields.
                // Bounded operands make the product exact as a Double.
                Some(Multiply(factor)) =>
                  Json::number(raw.to_int().to_double() * factor.to_double())
                Some(Divide(divisor)) => {
                  let n = raw.to_int()
                  if n % divisor != 0 {
                    return check_entry("inexact_division", i, Json::string(to))
                  }
                  Json::number((n / divisor).to_double())
                }
                None => value
              }
            String(label) =>
              match remaps.get(name) {
                Some(choices) => choices.get(label).unwrap_or(value)
                None => value
              }
            _ => value
          }
          if previous is Some(existing) {
            let field = target.fields[to]
            if !accepts_value(field, existing) ||
              !accepts_value(field, migrated) ||
              existing != migrated {
              return check_entry("rename_collision", i, Json::string(to))
            }
          } else {
            changed[to] = migrated
          }
        }
        for name in default_names {
          if !changed.contains(name) {
            changed[name] = defaults[name]
          }
        }
      } else {
        for name in original_names {
          changed[name] = original[name]
        }
      }
      Json::object(changed)
    }
    let target_issues = validate(target, updated)
    if !target_issues.is_empty() {
      return check_entry("target_rejected", i, migration_issues(target_issues))
    }
    passed += 1
    let details = if include_values {
      // Closed sources and validated migration rules only contribute scalar values.
      if source.open && target.open && updated is Object(fields) {
        detach_preview_fields(fields)
      }
      updated
    } else {
      Json::null()
    }
    check_entry("ready", i, details)
  })
  let all_ready = passed == records.length()
  (
    Json::object(
      Map([
        ("ready", Json::boolean(all_ready)),
        ("passed", Json::number(passed.to_double())),
        ("total", Json::number(records.length().to_double())),
        ("records", Json::array(entries)),
      ]),
    ),
    all_ready,
  )
}