///|
/// Parse RFC 4180-style rows, accepting CRLF and LF. Quotes, quoted newlines and
/// escaped quotes are supported. Text is bounded to 16 MiB, 100,001 rows,
/// 1,000,000 cells and 65,536 characters per cell. A trailing newline is not a row.
pub fn parse_csv_rows(text : String) -> Array[Array[String]] raise CdfError {
  if text.length() > 16777216 || @utf8.encode(text).length() > 16777216 {
    raise ResourceLimit("CSV text exceeds 16 MiB")
  }
  if text.is_empty() {
    return []
  }
  let chars = text.to_array()
  let rows : Array[Array[String]] = []
  let mut row : Array[String] = []
  let field = StringBuilder()
  let mut position = 0
  let mut quoted = false
  let mut closed = false
  let mut first = true
  let mut field_length = 0
  let mut cells = 0
  let mut ended_line = false
  while position < chars.length() {
    let character = chars[position]
    position += 1
    ended_line = false
    if quoted {
      if character == '"' {
        if position < chars.length() && chars[position] == '"' {
          field.write_char('"')
          field_length += 1
          position += 1
        } else {
          quoted = false
          closed = true
        }
      } else {
        field.write_char(character)
        field_length += 1
      }
    } else if character == ',' || character == '\r' || character == '\n' {
      cells += 1
      if cells > 1000000 {
        raise ResourceLimit("CSV cell count exceeds budget")
      }
      row.push(field.to_string())
      field.reset()
      field_length = 0
      first = true
      closed = false
      if character != ',' {
        if character == '\r' {
          if position >= chars.length() || chars[position] != '\n' {
            raise Invalid(
              "unquoted CSV carriage return must be followed by newline",
            )
          }
          position += 1
        }
        rows.push(row)
        row = []
        ended_line = true
        if rows.length() > 100001 {
          raise ResourceLimit("CSV row count exceeds budget")
        }
      }
    } else if closed {
      raise Invalid("unexpected character following a quoted CSV field")
    } else if character == '"' {
      if !first {
        raise Invalid("CSV quote must start at the beginning of a field")
      }
      quoted = true
      first = false
    } else {
      field.write_char(character)
      field_length += 1
      first = false
    }
    if field_length > 65536 {
      raise ResourceLimit("CSV field exceeds 65,536 characters")
    }
  }
  if quoted {
    raise Invalid("unterminated quoted CSV field")
  }
  if !ended_line {
    if cells >= 1000000 {
      raise ResourceLimit("CSV cell count exceeds budget")
    }
    row.push(field.to_string())
    rows.push(row)
    if rows.length() > 100001 {
      raise ResourceLimit("CSV row count exceeds budget")
    }
  }
  rows
}

///|
fn csv_integer(text : String) -> Int64 raise CdfError {
  @string.parse_int64(text) catch {
    _ => raise Invalid("invalid CSV signed integer or coordinate")
  }
}

///|
fn csv_value(text : String, kind : DataType) -> Value raise CdfError {
  let value = match kind {
    Char8 => {
      let number = csv_integer(text)
      if number < 0L || number > 255L {
        raise Invalid("CSV character byte is outside 0 through 255")
      }
      Character(number.to_int().to_byte())
    }
    UInt8 | UInt16 | UInt32 | UInt64 =>
      Unsigned(
        @string.parse_uint64(text) catch {
          _ => raise Invalid("invalid CSV unsigned integer")
        },
      )
    Int8 | Int16 | Int32 | Int64 => Signed(csv_integer(text))
    Float32 | Float64 =>
      Real(
        match text {
          "NaN" => @double.not_a_number
          "Infinity" => @double.infinity
          "-Infinity" => @double.neg_infinity
          _ =>
            @string.parse_double(text) catch {
              _ => raise Invalid("invalid CSV floating value")
            }
        },
      )
  }
  checked_value(value, kind)
  value
}

///|
fn csv_scalar(value : Value) -> String {
  match value {
    Signed(number) => number.to_string()
    Unsigned(number) => number.to_string()
    Character(byte) => byte.to_int().to_string()
    Real(number) =>
      if number.is_nan() {
        "NaN"
      } else if number == @double.infinity {
        "Infinity"
      } else if number == @double.neg_infinity {
        "-Infinity"
      } else {
        number.to_string()
      }
  }
}

///|
fn csv_axes(
  shape : Array[Int64],
  start : Array[Int64],
  stride : Array[Int64],
) -> Unit raise CdfError {
  if shape.length() > 16 ||
    start.length() != shape.length() ||
    stride.length() != shape.length() {
    raise Invalid("CSV coordinates must match the bounded block rank")
  }
  for axis, extent in shape {
    if start[axis] < 0L || stride[axis] < 1L {
      raise Invalid("CSV requires nonnegative origins and positive strides")
    }
    if extent > 0L &&
      extent - 1L > (9223372036854775807L - start[axis]) / stride[axis] {
      raise Invalid("CSV source coordinate overflows signed 64-bit range")
    }
  }
}

///|
fn csv_coordinates(
  index : Int32,
  shape : Array[Int64],
  start : Array[Int64],
  stride : Array[Int64],
) -> Array[Int64] {
  let coordinates = Array::make(shape.length(), 0L)
  let mut remaining = index.to_int64()
  for axis = shape.length() - 1; axis >= 0; axis = axis - 1 {
    coordinates[axis] = start[axis] + remaining % shape[axis] * stride[axis]
    remaining /= shape[axis]
  }
  coordinates
}

///|
/// Long-form raw CSV preserves integer precision and storage order. Every row
/// contains axis_0,...,axis_n,value. Character data uses decimal bytes. NaN and
/// infinities have explicit textual spellings. No missing-value scaling occurs.
pub fn block_csv(
  block : DataBlock,
  start~ : Array[Int64] = [],
  stride~ : Array[Int64] = [],
) -> String raise CdfError {
  let start = if start.is_empty() {
    Array::make(block.shape.length(), 0L)
  } else {
    start
  }
  let stride = if stride.is_empty() {
    Array::make(block.shape.length(), 1L)
  } else {
    stride
  }
  csv_axes(block.shape, start, stride)
  if shape_count(block.shape, 100000L) != block.values.length().to_int64() {
    raise Invalid(
      "CSV block shape disagrees with its values or exceeds 100,000 rows",
    )
  }
  if block.values.length() + 1 > 1000000 / (block.shape.length() + 1) {
    raise ResourceLimit("CSV header and data exceed one million cells")
  }
  let output = StringBuilder()
  for axis in 0.. 16777216 {
      raise ResourceLimit("CSV output exceeds 16 MiB")
    }
  }
  output.to_string()
}

///|
/// Read long-form raw CSV with an explicit shape and dtype. Coordinates are
/// verified against the supplied storage order; duplicate, omitted, reordered
/// or out-of-region rows fail instead of silently rearranging the data.
pub fn parse_block_csv(
  text : String,
  kind : DataType,
  shape : Array[Int64],
  start~ : Array[Int64] = [],
  stride~ : Array[Int64] = [],
) -> DataBlock raise CdfError {
  let start = if start.is_empty() {
    Array::make(shape.length(), 0L)
  } else {
    start
  }
  let stride = if stride.is_empty() {
    Array::make(shape.length(), 1L)
  } else {
    stride
  }
  csv_axes(shape, start, stride)
  let count = shape_count(shape, 100000L).to_int()
  let rows = parse_csv_rows(text)
  if rows.length() != count + 1 || rows[0].length() != shape.length() + 1 {
    raise Invalid("CSV rows or header disagree with the explicit shape")
  }
  for axis in 0.. {
    let row = rows[index + 1]
    if row.length() != shape.length() + 1 {
      raise Invalid("CSV row width disagrees with its header")
    }
    let coordinates = csv_coordinates(index, shape, start, stride)
    for axis, coordinate in coordinates {
      if csv_integer(row[axis]) != coordinate {
        raise Invalid(
          "CSV rows are missing, reordered, duplicated or outside the region",
        )
      }
    }
    csv_value(row[shape.length()], kind)
  })
  { data_type: kind, shape: shape.copy(), values, }
}