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

///|
priv struct Migration {
  renames : Map[String, String]
  defaults : Map[String, Json]
  drops : Map[String, Bool]
  remaps : Map[String, Map[String, Json]]
  scales : Map[String, Int32]
}

///|
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([])
    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)
      }
      guard replacement is String(value) &&
        value.length() <= 128 &&
        accepts(new_field.domain, replacement) else {
        raise ContractError(
          "remap value must be a valid target choice: " + dest,
        )
      }
      copy[label] = replacement
    }
    validated[name] = copy
  }
  validated
}

///|
fn read_scales(
  raw : Json?,
  source : Contract,
  target : Contract,
  moves : Map[String, String],
  drops : Map[String, Bool],
) -> Map[String, Int32] raise ContractError {
  let spec = optional_object(raw, "scale")
  if spec.length() > 64 {
    raise ContractError("scale accepts at most 64 fields")
  }
  let scales : Map[String, Int32] = Map([])
  for name, value in spec {
    if drops.contains(name) {
      raise ContractError("cannot drop and scale 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("scale must link integer fields: " + name)
    }
    guard integer_value(value) is Some(factor) && factor > 0 else {
      raise ContractError(
        "scale factor must be an integer in 1..1000000: " + name,
      )
    }
    scales[name] = factor
  }
  scales
}

///|
fn read_migration(
  raw : Json,
  source : Contract,
  target : Contract,
) -> Migration raise ContractError {
  let spec = object(raw, "migration")
  keys(spec, ["rename", "defaults", "drop", "remap", "scale"])
  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.fields.contains(name) &&
      target.fields.contains(dest) else {
      raise ContractError(
        "rename must link distinct declared source and target fields: " + name,
      )
    }
    if destinations.contains(dest) {
      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(field.domain, defaults[name]) else {
      raise ContractError(
        "default must match its declared 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.fields.contains(name) &&
        !target.fields.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_scales(spec.get("scale"), source, target, moves, drops)
  { renames: moves, defaults: defaults.copy(), drops, remaps, scales, }
}

///|
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]
}

///|
/// 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()
  { source, target, rules, default_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)
}

///|
fn apply_batch(
  plan : Rehearsal,
  records : Array[Json],
  include_values : Bool,
) -> (Json, Bool) {
  let { source, target, rules, default_names, } = plan
  let { renames, defaults, drops, remaps, scales, } = rules
  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 changed : Map[String, Json] = Map([])
    let original_names : Array[String] = []
    for name in original.keys() {
      original_names.push(name)
    }
    original_names.sort()
    for name in original_names {
      if drops.contains(name) {
        continue
      }
      let to = renames.get(name).unwrap_or(name)
      if changed.contains(to) {
        return check_entry("rename_collision", i, Json::string(to))
      }
      let value = original[name]
      changed[to] = if scales.get(name) is Some(factor) &&
        integer_value(value) is Some(n) {
        // Each operand is bounded by 1,000,000, so the Double product is exact.
        Json::number(n.to_double() * factor.to_double())
      } else {
        match (value, remaps.get(name)) {
          (String(label), Some(choices)) => choices.get(label).unwrap_or(value)
          _ => value
        }
      }
    }
    for name in default_names {
      if !changed.contains(name) {
        changed[name] = defaults[name]
      }
    }
    let updated = 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
    check_entry("ready", i, if include_values { updated } else { Json::null() })
  })
  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,
  )
}