///|
fn finding_json(finding : Finding) -> Json {
  Json::object(
    Map([
      ("field", Json::string(finding.field)),
      ("reason", Json::string(finding.reason)),
      ("witness", finding.witness),
    ]),
  )
}

///|
fn compatibility(findings : Array[Finding]) -> Json {
  Json::object(
    Map([
      ("compatible", Json::boolean(findings.is_empty())),
      ("findings", Json::array(findings.map(finding_json))),
    ]),
  )
}

///|
pub fn execute(value : Json) -> (Json, Bool) raise ContractError {
  let request = object(value, "request")
  guard request.get("mode") is Some(String(mode)) else {
    raise ContractError("mode must be compare, both, or validate")
  }
  match mode {
    "compare" | "both" => {
      keys(request, ["mode", "source", "target"])
      guard request.get("source") is Some(a) && request.get("target") is Some(b) else {
        raise ContractError("compare requires source and target")
      }
      let source = parse_contract(a)
      let target = parse_contract(b)
      let forward = compare(source, target)
      if mode == "compare" {
        (compatibility(forward), forward.is_empty())
      } else {
        let reverse = compare(target, source)
        let passed = forward.is_empty() && reverse.is_empty()
        (
          Json::object(
            Map([
              ("compatible", Json::boolean(passed)),
              ("source_to_target", compatibility(forward)),
              ("target_to_source", compatibility(reverse)),
            ]),
          ),
          passed,
        )
      }
    }
    "validate" => {
      keys(request, ["mode", "contract", "record"])
      guard request.get("contract") is Some(declaration) &&
        request.get("record") is Some(record) else {
        raise ContractError("validate requires contract and record")
      }
      let faults = validate(parse_contract(declaration), record)
      let passed = faults.is_empty()
      let entries = faults.map(fault => {
        Json::object(
          Map([
            ("field", Json::string(fault.field)),
            ("reason", Json::string(fault.reason)),
          ]),
        )
      })
      (
        Json::object(
          Map([
            ("valid", Json::boolean(passed)),
            ("violations", Json::array(entries)),
          ]),
        ),
        passed,
      )
    }
    _ => raise ContractError("mode must be compare, both, or validate")
  }
}