///|
#derive(Eq, Debug)
pub(all) enum Delimiter {
  Comma
  Semicolon
  Tab
}

///|
pub extend Delimiter with Eq::{equal, not_equal}

///|
pub extend Delimiter with @debug.Debug::{to_repr}

///|
pub fn Delimiter::character(self : Delimiter) -> Char {
  match self {
    Comma => ','
    Semicolon => ';'
    Tab => '\t'
  }
}

///|
pub suberror HeaderError {
  EmptyHeader
  UnexpectedQuote(Int32)
  TextAfterQuote(Int32)
  UnclosedQuote
  IncompleteHeader
  NulInHeader(Int32)
}

///|
pub fn HeaderError::description(self : HeaderError) -> String {
  match self {
    EmptyHeader => "the CSV header is empty"
    UnexpectedQuote(position) => "unexpected quote at position \{position}"
    TextAfterQuote(position) =>
      "unexpected text after a closing quote at position \{position}"
    UnclosedQuote => "the CSV header has an unclosed quote"
    IncompleteHeader => "the available prefix ends before the CSV header"
    NulInHeader(position) => "NUL in the CSV header at position \{position}"
  }
}

///|
priv enum FieldState {
  Start
  Unquoted
  Quoted
  AfterQuote
}

///|
priv struct HeaderRecord {
  fields : Array[String]
  length : Int32
}

///|
fn scan_header(
  input : String,
  delimiter : Delimiter,
  eof : Bool,
) -> HeaderRecord raise HeaderError {
  let fields : Array[String] = []
  let mut field = StringBuilder()
  let mut state = Start
  let mut length = 0
  let mut has_content = false
  let separator = delimiter.character()
  for ch in input {
    if length == 0 && ch == '\u{feff}' {
      length += 1
      continue
    }
    if ch == '\u{0000}' {
      raise NulInHeader(length + 1)
    }
    if ch == '\r' || ch == '\n' {
      if state is Quoted {
        field.write_char(ch)
        length += 1
        continue
      }
      guard has_content else { raise EmptyHeader }
      fields.push(field.to_string())
      return { fields, length, }
    }
    has_content = true
    length += 1
    if ch == separator && !(state is Quoted) {
      fields.push(field.to_string())
      field = StringBuilder()
      state = Start
      continue
    }
    state = match state {
      Start if ch == '"' => Quoted
      Start | Unquoted => {
        if ch == '"' {
          raise UnexpectedQuote(length)
        }
        field.write_char(ch)
        Unquoted
      }
      Quoted if ch == '"' => AfterQuote
      Quoted => {
        field.write_char(ch)
        Quoted
      }
      AfterQuote if ch == '"' => {
        field.write_char(ch)
        Quoted
      }
      AfterQuote => raise TextAfterQuote(length)
    }
  }
  guard eof else { raise IncompleteHeader }
  guard has_content else { raise EmptyHeader }
  if state is Quoted {
    raise UnclosedQuote
  }
  fields.push(field.to_string())
  { fields, length, }
}

///|
/// Parse only the first logical record, including CSV quoting and an optional BOM.
/// Column names retain their original case and whitespace.
pub fn parse_header(
  input : String,
  delimiter : Delimiter,
) -> Array[String] raise HeaderError {
  scan_header(input, delimiter, true).fields
}

///|
/// Return the header's length in Unicode scalars, excluding the record terminator.
/// Set eof=false for a bounded prefix that may have been cut off mid-record.
pub fn header_length(
  input : String,
  delimiter : Delimiter,
  eof~ : Bool,
) -> Int32 raise HeaderError {
  scan_header(input, delimiter, eof).length
}