///|
/// Excel-readable UTF-8 CSV and the reconciliation verdict. Raw identifiers are
/// JSON tuples inside quoted CSV cells, retaining leading zeros and component boundaries.
pub fn reconcile_issue_csv(
  master : LookupTable,
  master_columns : Array[String],
  detail : LookupTable,
  detail_columns : Array[String],
  trim_keys~ : Bool = false,
) -> Result[(String, Bool), String] {
  let out = StringBuilder()
  out.write_string(
    "\uFEFF问题分类,所在表,起始行,结束行,原始编号(JSON数组),关联台账行号,匹配方式\r\n",
  )
  let policy = if trim_keys { "忽略首尾空白" } else { "严格匹配" }
  fn emit(kind : LookupFinding, item : LookupExample) -> Unit {
    let category = match kind {
      MissingReference => "明细找不到编号"
      AmbiguousReference => "明细对应多条台账记录"
      EmptyReference => "明细漏填编号"
      DuplicateMaster => "台账重复登记"
      EmptyMaster => "台账漏填编号"
      UnusedMaster => "尚无明细引用的台账编号"
    }
    let side = if kind.is_master() { "台账" } else { "明细" }
    let (first, last) = item.lines
    let raw_key = @json.to_json(item.key)
      .stringify()
      .replace_all(old="\"", new="\"\"")
    let sources = item.master_lines.map(span => {
      let (a, b) = span
      if a == b {
        a.to_string()
      } else {
        a.to_string() + "–" + b.to_string()
      }
    })
    let locations = if sources.is_empty() {
      ""
    } else {
      "第 " + sources.join("、") + " 行"
    }
    out.write_string(
      "\{category},\{side},\{first},\{last},\"\{raw_key}\",\{locations},\{policy}\r\n",
    )
  }
  match
    run_lookup(
      master,
      master_columns,
      detail,
      detail_columns,
      0,
      trim_keys,
      Some(emit),
    ) {
    Err(e) => Err(e)
    Ok(report) => Ok((out.to_string(), report.is_clean()))
  }
}