///|
/// Strict quote framing in front of the reusable CSV parser, which otherwise accepts malformed quotes.
/// UTF-8 decoding is the host's responsibility.
pub fn input_from_csv(
  name : String,
  text : String,
  dialect~ : CsvDialect = default_csv_dialect(),
) -> Result[InputTable, String] {
  csv_input(name, text, dialect, None, false)
}

///|
#derive(Eq)
priv enum CsvFieldState {
  Start
  Unquoted
  Quoted
  Closed
}

///|
fn csv_input(
  name : String,
  source : String,
  dialect : CsvDialect,
  comment : Char?,
  skip_space : Bool,
  escape~ : Char? = None,
  double_quote~ : Bool = true,
  on_span? : (Int32, Int32) -> Unit,
) -> Result[InputTable, String] {
  if !dialect.supported() {
    return Err("Unsupported CSV delimiter or quote character")
  }
  let text = if source.has_prefix("\uFEFF") {
    source[1:].to_owned()
  } else {
    source
  }
  let quote = dialect.quote_char.to_int()
  let separator = dialect.delimiter.to_int()
  let comment = comment.map(c => c.to_int())
  let escape = escape.map(c => c.to_int())
  let mut state = Start
  let mut record_start = true
  let mut after_delimiter = false
  let mut i = 0
  // NyaCSV understands doubled quotes. Only rewrite fields containing escapes,
  // record comments, and delimiter padding; source positions always use the input.
  let mut field_start = 0
  let mut wrap_plain = false
  let mut split_crlf_at = -1
  let mut line = 1
  let mut first_line = 1
  let mut kept_from = 0
  let kept = StringBuilder()
  while i < text.length() {
    let c = text.code_unit_at(i).to_int()
    if record_start && comment == Some(c) {
      kept.write_view(text[kept_from:i])
      // A retained lone CR already terminates a record. Complete its CRLF in
      // the normalized copy so it cannot absorb a blank LF beyond the comment.
      if i > kept_from && text.code_unit_at(i - 1) == 13 {
        kept.write_char('\n')
      }
      while i < text.length() &&
            text.code_unit_at(i) != 10 &&
            text.code_unit_at(i) != 13 {
        i += 1
      }
      if i < text.length() {
        if text.code_unit_at(i) == 13 &&
          i + 1 < text.length() &&
          text.code_unit_at(i + 1) == 10 {
          i += 1
        }
        i += 1
        line += 1
        first_line = line
      }
      kept_from = i
      field_start = i
      continue
    }
    if skip_space && after_delimiter && c == 32 && escape != Some(c) {
      kept.write_view(text[kept_from:i])
      while i < text.length() && text.code_unit_at(i) == 32 {
        i += 1
      }
      kept_from = i
      field_start = i
      continue
    }
    if state != Closed && escape == Some(c) {
      if i + 1 == text.length() {
        if on_span is Some(emit) {
          emit(first_line, line)
        }
        return Err("Dangling CSV escape character")
      }
      if state != Quoted && !wrap_plain {
        kept.write_view(text[kept_from:field_start])
        kept.write_char(dialect.quote_char)
        kept_from = field_start
        wrap_plain = true
      }
      kept.write_view(text[kept_from:i])
      i += 1
      kept_from = i
      let literal = text.code_unit_at(i).to_int()
      if literal == quote {
        kept.write_char(dialect.quote_char)
      }
      // In a plain field, escaping CR in CRLF preserves CR as data. The
      // unescaped LF ends the record on that same physical line.
      if literal == 13 &&
        state != Quoted &&
        i + 1 < text.length() &&
        text.code_unit_at(i + 1) == 10 {
        split_crlf_at = i + 1
      } else if literal == 10 || literal == 13 {
        line += 1
      }
      if state == Start {
        state = Unquoted
      }
      after_delimiter = false
      record_start = false
      i += 1
      continue
    }
    if wrap_plain && (c == separator || c == 13 || c == 10) {
      kept.write_view(text[kept_from:i])
      kept.write_char(dialect.quote_char)
      kept_from = i
      wrap_plain = false
    }
    // Physical CRLF counts once, even inside a quoted logical record.
    let newline = c == 13 ||
      (
        c == 10 &&
        (i == 0 || i == split_crlf_at || text.code_unit_at(i - 1) != 13)
      )
    if newline {
      if state != Quoted {
        if on_span is Some(emit) {
          emit(first_line, line)
        }
        first_line = line + 1
      }
      line += 1
    }
    record_start = false
    after_delimiter = false
    if state == Quoted {
      if c == quote {
        if double_quote &&
          i + 1 < text.length() &&
          text.code_unit_at(i + 1).to_int() == quote {
          i += 1
        } else {
          state = Closed
        }
      }
    } else if c == separator {
      state = Start
      after_delimiter = true
      field_start = i + 1
    } else if c == 10 || c == 13 {
      state = Start
      record_start = true
      field_start = i + 1
    } else if c == quote {
      if state != Start {
        if on_span is Some(emit) {
          emit(first_line, line)
        }
        return Err("Quote inside an unquoted field")
      }
      state = Quoted
    } else {
      if state == Closed {
        if on_span is Some(emit) {
          emit(first_line, line)
        }
        return Err("Unexpected character after closing quote")
      }
      state = Unquoted
    }
    i += 1
  }
  if !record_start && on_span is Some(emit) {
    emit(first_line, line)
  }
  if state == Quoted {
    return Err("Unterminated quoted field")
  }
  let text = if kept_from == 0 {
    text
  } else {
    kept.write_view(text[kept_from:])
    if wrap_plain {
      kept.write_char(dialect.quote_char)
    }
    kept.to_string()
  }
  let parsed = @csv.CSV::parse_string(text, options={
    delimiter: dialect.delimiter,
    allow_newlines_in_quotes: true,
    quote_char: dialect.quote_char,
    skip_empty_lines: false,
    trim_spaces: false,
  })
  Ok({ name, header: parsed.header(), rows: parsed.data(), })
}

///|
test "reused CSV parser preserves quoted commas newlines and Unicode" {
  let input = input_from_csv(
    "t", "id,title\r\n1,\"你好,🙂\"\r\n2,\"line1\nline2\"\r\n",
  ).unwrap()
  assert_eq(input.header, ["id", "title"])
  assert_eq(input.rows, [["1", "你好,🙂"], ["2", "line1\nline2"]])
}

///|
test "malformed CSV is rejected before lenient dependency parsing" {
  for text in ["id\n\"unterminated", "id\na\"b", "id\n\"value\"oops"] {
    assert_true(input_from_csv("t", text) is Err(_))
  }
}

///|
test "empty CSV records cannot erase required data errors" {
  let input = input_from_csv("t", "id\n\n1\n").unwrap()
  assert_eq(input.rows, [[""], ["1"]])
  let report = validate_table(
    "t",
    [{ ..field("id", Integer), required: true, }],
    input.header,
    input.rows,
  )
  assert_false(report.valid())
  assert_eq(report.errors[0].code, "required")
}

///|
test "BOM is handled consistently in the embedded API" {
  assert_eq(input_from_csv("t", "\uFEFFid\n1\n").unwrap().header, ["id"])
}

///|
test "alternate delimiters and quotes preserve the same logical records" {
  let expected = input_from_csv(
    "t", "id,title\r\n1,\"it's;茶\r\n新\"\r\n2,\r\n",
  ).unwrap()
  for sep in [';', '\t'] {
    let dialect : CsvDialect = { delimiter: sep, quote_char: '\'', }
    let text = "\uFEFFid\{sep}title\r\n1\{sep}'it''s;茶\r\n新'\r\n2\{sep}\r\n"
    let actual = input_from_csv("t", text, dialect~).unwrap()
    assert_eq(actual.header, expected.header)
    assert_eq(actual.rows, expected.rows)
    for bad in ["'oops", "a'b", "'closed'x"] {
      assert_true(input_from_csv("t", bad, dialect~) is Err(_))
    }
  }
}

///|
test "annotated CSV skips only record comments and spaces following delimiters" {
  let dialect : CsvDialect = { delimiter: '|', quote_char: '~', }
  for newline in ["\n", "\r", "\r\n"] {
    let text = [
      "\uFEFF# ~unclosed", "ID| LABEL", "1|  ~中|文", "# literal ~~quote~~ ~",
      " # keep|\tx ", "", "# trailing comment",
    ].join(newline)
    let result = csv_input("t", text, dialect, Some('#'), true).unwrap()
    assert_eq(result.header, ["ID", "LABEL"])
    assert_eq(result.rows, [
      ["1", "中|文" + newline + "# literal ~quote~ "],
      [" # keep", "\tx "],
      [""],
    ])
  }
  assert_true(csv_input("t", "a| ~ok~x", dialect, Some('#'), true) is Err(_))
  assert_true(csv_input("t", "a| ~ok~", dialect, None, false) is Err(_))
}

///|
test "tabular CSV parts match headers by dialect and keep headerless data" {
  let names = ["id", "label"]
  let defaults = parse_tabular_csv_settings(Json::null()).unwrap()
  let parts = ["ID,Label\n1,a", "id,LABEL\n2,b"]
  assert_eq(csv_table_from_parts("t", parts, names, defaults).unwrap().rows, [
    ["1", "a"],
    ["2", "b"],
  ])
  assert_true(
    csv_table_from_parts("t", parts, names, {
      ..defaults,
      case_sensitive: true,
    })
    is Err(_),
  )
  assert_true(
    csv_table_from_parts("t", ["label,id"], names, defaults) is Err(_),
  )
  let headerless = parse_tabular_csv_settings(
    @json.parse("{\"header\":false,\"commentChar\":\"#\"}"),
  ).unwrap()
  assert_eq(
    csv_table_from_parts("t", ["# only", "", "1,a\n# tail"], names, headerless).unwrap().rows,
    [["1", "a"]],
  )
}

///|
test "CSV syntax characters cannot be ambiguous or unsupported" {
  for
    json in [
      "{\"quoteChar\":\",\"}", "{\"commentChar\":\"\"}", "{\"commentChar\":\"##\"}",
      "{\"commentChar\":\"\\r\"}", "{\"skipInitialSpace\":1}", "{\"delimiter\":\"🙂\"}",
    ] {
    assert_true(parse_tabular_csv_settings(@json.parse(json)) is Err(_))
  }
  let result = input_from_csv("t", "甲。乙\n1。「茶。水「", dialect={
    delimiter: '。',
    quote_char: '「',
  }).unwrap()
  assert_eq(result.rows, [["1", "茶。水"]])
}

///|
test "CSV nullSequence and schema missingValues both apply before constraints" {
  let descriptor = parse_mixed_descriptor(
    (
      #|{"resources":[{"name":"t","path":"x.csv","dialect":{"nullSequence":"NULL"},"schema":{"missingValues":["NA"],"fields":[{"name":"n","type":"integer","constraints":{"required":true}}]}}]}
    ),
  ).unwrap()
  let result = validate_mixed_package(descriptor, [
    { name: "t", parts: ["N\nNULL\nNA\n1\nNULLx"], },
  ])
  assert_eq(result.errors.map(e => (e.row, e.code)), [
    (1, "required"),
    (2, "required"),
    (4, "type"),
  ])
  assert_eq(descriptor.resources[0].missing_values, ["NA"])
}