///|
fn LookupFinding::sarif_rule(self : LookupFinding) -> (String, String) {
  match self {
    MissingReference =>
      (
        "reconcile.missing_reference", "This detail key has no matching master record.",
      )
    AmbiguousReference =>
      (
        "reconcile.ambiguous_reference", "This detail key matches multiple master records.",
      )
    EmptyReference =>
      ("reconcile.empty_reference", "This detail record has an incomplete key.")
    DuplicateMaster =>
      (
        "reconcile.duplicate_master", "This master key appears in an earlier record.",
      )
    EmptyMaster =>
      ("reconcile.empty_master", "This master record has an incomplete key.")
    UnusedMaster =>
      (
        "reconcile.unused_master_keys", "No detail record refers to this master key.",
      )
  }
}

///|
fn LookupFinding::sarif_level(self : LookupFinding) -> String {
  if self == UnusedMaster {
    "note"
  } else {
    "error"
  }
}

///|
fn sarif_artifact(uri : String) -> Result[Json, String] {
  if valid_uri(uri) {
    return Ok({ "uri": uri })
  }
  let path = uri[:]
  let (first, _) = path.split_once("/").unwrap_or((path, ""[:]))
  if first.is_empty() ||
    first.contains(":") ||
    !uri_characters(path, c => uri_name_char(c) || ['/', ':', '@'].contains(c)) {
    return Err(
      "Expected an absolute URI or a percent-encoded relative artifact path",
    )
  }
  Ok({ "uri": uri, "uriBaseId": "%SRCROOT%" })
}

///|
fn sarif_physical_location(artifact : Json, lines : (Int32, Int32)) -> Json {
  let (first, last) = lines
  {
    "artifactLocation": artifact,
    "region": { "startLine": first, "endLine": last },
  }
}

///|
let sarif_schema_uri : String = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/schemas/sarif-schema-2.1.0.json"

///|
fn visit_reconcile_sarif(
  master : LookupTable,
  master_columns : Array[String],
  detail : LookupTable,
  detail_columns : Array[String],
  master_uri : String,
  detail_uri : String,
  trim_keys : Bool,
  start_run : (Map[String, Json]) -> Unit,
  write_result : (Json) -> Unit,
) -> Result[Bool, String] {
  let master_artifact = match sarif_artifact(master_uri) {
    Ok(artifact) => artifact
    Err(message) => return Err(message)
  }
  let detail_artifact = match sarif_artifact(detail_uri) {
    Ok(artifact) => artifact
    Err(message) => return Err(message)
  }
  let kinds : Array[LookupFinding] = [
    MissingReference,
    AmbiguousReference,
    EmptyReference,
    DuplicateMaster,
    EmptyMaster,
    UnusedMaster,
  ]
  let rules = kinds.map(kind => {
    let (id, title) = kind.sarif_rule()
    (
      {
        "id": id,
        "shortDescription": { "text": title },
        "defaultConfiguration": { "level": kind.sarif_level() },
      } : Json)
  })
  let run : Map[String, Json] = {
    "tool": {
      "driver": {
        "name": "MoonFriction",
        "informationUri": "https://github.com/Kleinrat/MoonFriction",
        "rules": Json::array(rules),
      },
    },
    "columnKind": "utf16CodeUnits",
  }
  if prop(master_artifact, "uriBaseId") is String(_) ||
    prop(detail_artifact, "uriBaseId") is String(_) {
    // The consumer can bind the root locally without recording the producer's filesystem path.
    run["originalUriBaseIds"] = {
      "%SRCROOT%": {
        "description": { "text": "Root directory for the input CSV files." },
      },
    }
  }
  fn emit(kind : LookupFinding, item : LookupExample) -> Unit {
    let (id, title) = kind.sarif_rule()
    let artifact = if kind.is_master() {
      master_artifact
    } else {
      detail_artifact
    }
    let links : Array[String] = []
    let related : Array[Json] = []
    for i, lines in item.master_lines {
      let witness = if i == 0 {
        "First master record"
      } else {
        "Second master record"
      }
      let target = i + 1
      links.push("[" + witness + "](" + target.to_string() + ")")
      related.push({
        "id": target,
        "message": { "text": witness },
        "physicalLocation": sarif_physical_location(master_artifact, lines),
      })
    }
    let message = if links.is_empty() {
      title
    } else {
      title + " " + links.join(", ") + "."
    }
    let fields : Map[String, Json] = {
      "ruleId": id,
      "ruleIndex": kinds.search(kind).unwrap(),
      "level": kind.sarif_level(),
      "message": { "text": message },
      "locations": [
        { "physicalLocation": sarif_physical_location(artifact, item.lines) },
      ],
    }
    if !related.is_empty() {
      fields["relatedLocations"] = Json::array(related)
    }
    write_result(Json::object(fields))
  }
  match
    run_lookup(
      master,
      master_columns,
      detail,
      detail_columns,
      0,
      trim_keys,
      Some(emit),
      on_ready=() => start_run(run),
    ) {
    Ok(report) => Ok(report.is_clean())
    Err(message) => Err(message)
  }
}

///|
/// Build a SARIF 2.1.0 log and the reconciliation verdict. Each finding retains
/// its physical line spans without including the original key values or CSV text.
/// Pass encoded artifact URIs. Relative references use the caller's source root.
pub fn reconcile_issue_sarif(
  master : LookupTable,
  master_columns : Array[String],
  detail : LookupTable,
  detail_columns : Array[String],
  master_uri~ : String,
  detail_uri~ : String,
  trim_keys~ : Bool = false,
) -> Result[(Json, Bool), String] {
  let mut run : Map[String, Json] = Map([])
  let results = []
  let clean = match
    visit_reconcile_sarif(
      master,
      master_columns,
      detail,
      detail_columns,
      master_uri,
      detail_uri,
      trim_keys,
      metadata => run = metadata,
      result => results.push(result),
    ) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  run["results"] = Json::array(results)
  let log : Json = {
    "$schema": sarif_schema_uri,
    "version": "2.1.0",
    "runs": [Json::object(run)],
  }
  Ok((log, clean))
}

///|
/// Write one complete SARIF log in order, without accumulating the result array
/// or a single report string. The synchronous sink receives no chunks for invalid input.
pub fn write_reconcile_issue_sarif(
  master : LookupTable,
  master_columns : Array[String],
  detail : LookupTable,
  detail_columns : Array[String],
  write_chunk : (String) -> Unit,
  master_uri~ : String,
  detail_uri~ : String,
  trim_keys~ : Bool = false,
) -> Result[Bool, String] {
  fn start_run(metadata : Map[String, Json]) -> Unit {
    let buf = StringBuilder()
    buf.write_string("{\"$schema\":")
    buf.write_string(Json::string(sarif_schema_uri).stringify())
    buf.write_string(",\"version\":\"2.1.0\",\"runs\":[{")
    for name, value in metadata {
      buf.write_string(Json::string(name).stringify())
      buf.write_string(":")
      buf.write_string(value.stringify())
      buf.write_string(",")
    }
    buf.write_string("\"results\":[")
    write_chunk(buf.to_string())
  }
  let mut first = true
  fn write_result(result : Json) -> Unit {
    let text = result.stringify()
    if first {
      first = false
      write_chunk(text)
    } else {
      write_chunk("," + text)
    }
  }
  match
    visit_reconcile_sarif(
      master, master_columns, detail, detail_columns, master_uri, detail_uri, trim_keys,
      start_run, write_result,
    ) {
    Ok(clean) => {
      write_chunk("]}]}")
      Ok(clean)
    }
    Err(message) => Err(message)
  }
}