///|
priv struct SplitDeclaration {
  trial : String
  group : String
  split : String
  source : String
  line : Int32
}

///|
priv struct SplitSourceCheck {
  read : (String) -> String?
  label : String
  unreadable : String
  duplicate : String
}

///|
/// Check declared provenance without opening source documents.
pub fn check_splits(text : String) -> String raise AuditError {
  check_split_declarations(text, None)
}

///|
/// Also check for byte-identical sources crossing splits. The reader supplies
/// a raw source SHA-256, or None if the source cannot be read.
pub fn check_split_sources(
  text : String,
  source_sha256 : (String) -> String?,
) -> String raise AuditError {
  check_split_declarations(
    text,
    Some({
      read: source_sha256,
      label: "SOURCE BYTES",
      unreadable: "cannot read source bytes",
      duplicate: "identical source bytes cross splits",
    }),
  )
}

///|
/// Check normalized UTF-8 sources across splits. The reader supplies a digest
/// after removing one leading BOM and replacing CRLF with LF.
pub fn check_split_source_text(
  text : String,
  normalized_sha256 : (String) -> String?,
) -> String raise AuditError {
  check_split_declarations(
    text,
    Some({
      read: normalized_sha256,
      label: "SOURCE TEXT",
      unreadable: "cannot read source as UTF-8",
      duplicate: "identical normalized source text crosses splits",
    }),
  )
}

///|
fn check_split_declarations(
  text : String,
  source_check : SplitSourceCheck?,
) -> String raise AuditError {
  let lines = text
    .strip_prefix("\u{FEFF}")
    .unwrap_or(text[:])
    .split("\n")
    .collect()
  let header = "trial_id\tsource_group_id\tsplit\tsource\treference\tcandidate"
  if lines.is_empty() || lines[0].trim(char_set="\r").to_owned() != header {
    raise InvalidInput(
      "unexpected split TSV header: source_group_id is required",
    )
  }
  let trials : Map[String, SplitDeclaration] = Map([])
  let groups : Map[String, SplitDeclaration] = Map([])
  let rows : Array[SplitDeclaration] = []
  for i in 1.. "SPLITS OK \{counts}"
    Some(check) => {
      let unique = check_split_source_digests(rows, check)
      "SPLITS \{check.label} OK \{counts} unique_sources=\{unique}"
    }
  }
}

///|
fn SplitDeclaration::location(self : SplitDeclaration) -> String {
  let trial = Json::string(self.trial).stringify()
  let group = Json::string(self.group).stringify()
  "line \{self.line} trial=\{trial} group=\{group} split=\{self.split}"
}

///|
fn check_split_source_digests(
  rows : Array[SplitDeclaration],
  check : SplitSourceCheck,
) -> Int32 raise AuditError {
  let known_paths : Map[String, String] = Map([])
  let known_digests : Map[String, SplitDeclaration] = Map([])
  for row in rows {
    let digest = match known_paths.get(row.source) {
      Some(digest) => digest
      None => {
        guard (check.read)(row.source) is Some(digest) else {
          raise InvalidInput("split TSV \{row.location()}: \{check.unreadable}")
        }
        known_paths[row.source] = digest
        digest
      }
    }
    match known_digests.get(digest) {
      Some(previous) =>
        if row.split != previous.split {
          raise InvalidInput(
            "\{check.duplicate}: \{previous.location()}; \{row.location()}",
          )
        }
      None => known_digests[digest] = row
    }
  }
  known_digests.length()
}