///|
/// A validation failure with an optional one-based CSV record start line.
#derive(Eq, Debug, ToJson)
pub(all) struct Issue {
  code : String
  source : String
  line : Int32?
  message : String
}

///|
fn issue(
  code : String,
  source : String,
  message : String,
  line? : Int32,
) -> Issue {
  { code, source, line, message, }
}

///|
priv struct Snapshot {
  table : @wayfarer.CsvTable
  columns : Map[String, Int32]
  key_indices : Array[Int32]
}

///|
fn csv_issue(error : @wayfarer.CsvError, source : String) -> Issue {
  match error {
    EmptyDocument => issue("empty-csv", source, "A CSV header is required.")
    EmptyHeader(line~, column~) =>
      issue(
        "empty-header",
        source,
        "Column \{column} has an empty header.",
        line~,
      )
    DuplicateHeader(name~, column~) =>
      issue(
        "duplicate-header",
        source,
        "Column \{column} repeats header \{Json::string(name).stringify()}.",
        line=1,
      )
    UnexpectedQuote(line~, column~) =>
      issue(
        "invalid-csv",
        source,
        "Unexpected quote at column \{column}.",
        line~,
      )
    CharactersAfterQuote(line~, column~) =>
      issue(
        "invalid-csv",
        source,
        "Unexpected characters at column \{column} after a closing quote.",
        line~,
      )
    UnterminatedQuote(line~, column~) =>
      issue(
        "invalid-csv",
        source,
        "Quoted field opened at column \{column} was not closed.",
        line~,
      )
    RowWidthMismatch(line~, expected~, actual~) =>
      issue(
        "row-width",
        source,
        "Expected \{expected} fields, received \{actual}.",
        line~,
      )
    InvalidLineEnding(line~, column~) =>
      issue(
        "invalid-csv",
        source,
        "Expected LF after CR at column \{column}.",
        line~,
      )
  }
}

///|
fn validate_keys(keys : Array[String]) -> Result[Unit, Issue] {
  if keys.is_empty() {
    return Err(
      issue("missing-key", "configuration", "Specify at least one key column."),
    )
  }
  let seen : Map[String, Unit] = Map([])
  for key in keys {
    if key.trim().is_empty() {
      return Err(
        issue(
          "empty-key-column", "configuration", "Key column names cannot be blank.",
        ),
      )
    }
    if seen.contains(key) {
      return Err(
        issue(
          "duplicate-key-column",
          "configuration",
          "Key column \{Json::string(key).stringify()} was specified more than once.",
        ),
      )
    }
    seen[key] = ()
  }
  Ok(())
}

///|
fn prepare_snapshot(
  input : String,
  keys : Array[String],
  source : String,
) -> Result[Snapshot, Issue] {
  let table = match @wayfarer.parse_csv(input) {
    Ok(table) => table
    Err(error) => return Err(csv_issue(error, source))
  }
  let columns : Map[String, Int32] = Map([])
  for index, name in table.headers {
    columns[name] = index
  }
  let key_indices = []
  for name in keys {
    match columns.get(name) {
      Some(index) => key_indices.push(index)
      None => {
        let shown = table.headers.length().min(8)
        let names = Json::array(table.headers[:shown].map(Json::string)).stringify()
        let remaining = table.headers.length() - shown
        let more = if remaining > 0 { " (+\{remaining} more)" } else { "" }
        return Err(
          issue(
            "missing-key-column",
            source,
            "Header does not contain key column \{Json::string(name).stringify()}. Available columns: \{names}\{more}.",
            line=1,
          ),
        )
      }
    }
  }
  Ok({ table, columns, key_indices, })
}