///|
/// Text chunks for one CSV or JSON table. Inline data is already in the descriptor.
#derive(Debug, @json.FromJson)
pub(all) struct TabularResourceInput {
  name : String
  parts : Array[String]
}

///|
pub struct TabularCsvSettings {
  dialect : CsvDialect
  escape : Char?
  double_quote : Bool
  header : Bool
  null_sequence : String?
  comment : Char?
  skip_space : Bool
  case_sensitive : Bool
}

///|
pub fn parse_tabular_csv_settings(
  value : Json,
) -> Result[TabularCsvSettings, String] {
  if unsupported_standard(value, "", "$schema") is Some(error) {
    return Err(error.message)
  }
  let fields = match value {
    Null => Map([])
    Object(fields) => fields
    _ => return Err("Expected a resolved CSV dialect object")
  }
  let options = Map([])
  let mut header = true
  let mut case_sensitive = false
  let mut null_sequence = None
  let mut comment = None
  let mut skip_space = false
  let mut double_quote = true
  let mut escape = None
  for key, setting in fields {
    match (key, setting) {
      ("nullSequence", String(s)) => null_sequence = Some(s)
      ("header", True | False) => header = setting is True
      ("caseSensitiveHeader", True | False) => case_sensitive = setting is True
      ("lineTerminator", String("\n" | "\r\n")) => ()
      ("doubleQuote", True | False) => double_quote = setting is True
      ("escapeChar", String(s)) if s.length() == 1 &&
        csv_syntax_char(s.iter().next().unwrap()) => escape = s.iter().next()
      ("skipInitialSpace", True | False) => skip_space = setting is True
      ("commentChar", String(s)) if s.length() == 1 &&
        csv_syntax_char(s.iter().next().unwrap()) => comment = s.iter().next()
      ("csvddfVersion", Number(n, ..)) if n == 1.0 || n == 1.1 || n == 1.2 => ()
      ("delimiter" | "quoteChar", _) => options[key] = setting
      _ => return Err("Unsupported CSV dialect option or value: " + key)
    }
  }
  if escape is Some(_) && fields.contains("quoteChar") {
    return Err("CSV escapeChar and explicit quoteChar are mutually exclusive")
  }
  let dialect = match parse_csv_dialect(Json::object(options)) {
    Ok(value) => value
    Err(message) => return Err(message)
  }
  if escape is Some(c) &&
    (c == dialect.delimiter || c == dialect.quote_char || comment == Some(c)) {
    return Err(
      "CSV escapeChar conflicts with the delimiter, quote, or comment character",
    )
  }
  Ok({
    dialect,
    escape,
    double_quote,
    header,
    case_sensitive,
    null_sequence,
    comment,
    skip_space,
  })
}

///|
/// Decode physical CSV records, exposing the first record as InputTable.header.
/// Package validation applies schema headers and headerless-resource policy.
pub fn TabularCsvSettings::decode(
  self : TabularCsvSettings,
  name : String,
  text : String,
) -> Result[InputTable, String] {
  csv_input(
    name,
    text,
    self.dialect,
    self.comment,
    self.skip_space,
    escape=self.escape,
    double_quote=self.double_quote,
  )
}

///|
pub fn TabularCsvSettings::matches_header(
  self : TabularCsvSettings,
  header : Array[String],
  names : Array[String],
) -> Bool {
  if self.case_sensitive {
    header == names
  } else {
    header.map(s => s.to_lower()) == names.map(s => s.to_lower())
  }
}

///|
pub fn TabularCsvSettings::missing_values(
  self : TabularCsvSettings,
  values : Array[String],
) -> Array[String] {
  match self.null_sequence {
    Some(marker) => values + [marker]
    None => values
  }
}

///|
fn tabular_format(item : Json) -> String {
  match prop(item, "format") {
    String(name) => name.to_lower()
    _ => {
      let media = json_text(prop(item, "mediatype")).unwrap_or("")
      let paths = strings(prop(item, "path")).unwrap_or([])
      if prop(item, "data") is Array(_) ||
        media == "application/json" ||
        (!paths.is_empty() && paths.all(p => p.to_lower().has_suffix(".json"))) {
        "json"
      } else {
        "csv"
      }
    }
  }
}

///|
fn csv_table_from_parts(
  name : String,
  parts : Array[String],
  names : Array[String],
  settings : TabularCsvSettings,
  locate? : (Int32, Int32, Int32, Int32) -> Unit,
) -> Result[InputTable, Diagnostic] {
  let rows = []
  let dialect = settings.dialect
  if parts.is_empty() {
    return Err(issue("csv", name, 0, "", "At least one CSV part is required"))
  }
  for index, text in parts {
    if locate is Some(emit) {
      emit(0, index, 1, 1)
    }
    let mut local_row = if settings.header { 0 } else { 1 }
    let offset = rows.length()
    let mut logical = 0
    fn on_span(first : Int32, last : Int32) -> Unit {
      logical = if local_row == 0 { 0 } else { offset + local_row }
      if locate is Some(emit) {
        emit(logical, index, first, last)
      }
      local_row += 1
    }
    let part = match
      csv_input(
        name,
        text,
        dialect,
        settings.comment,
        settings.skip_space,
        escape=settings.escape,
        double_quote=settings.double_quote,
        on_span~,
      ) {
      Ok(table) => table
      Err(message) =>
        return Err(
          issue(
            "csv",
            name,
            logical,
            "",
            "CSV part " + (index + 1).to_string() + ": " + message,
          ),
        )
    }
    if settings.header && !settings.matches_header(part.header, names) {
      return Err(
        issue(
          "header",
          name,
          0,
          "",
          "CSV part " +
          (index + 1).to_string() +
          ": header must match schema fields in order",
        ),
      )
    }
    if !settings.header && !part.header.is_empty() {
      rows.push(part.header)
    }
    for row in part.rows {
      rows.push(row)
    }
  }
  Ok({ name, header: names, rows, })
}

///|
fn inline_json_table(
  name : String,
  value : Json,
  names : Array[String],
) -> Result[JsonInputTable, String] {
  match json_input_value(name, value) {
    Ok(table) if table.mode is ArrayRows && !table.rows.is_empty() => {
      guard table.rows[0] == @json.to_json(names) else {
        return Err("First inline JSON array must be the schema header")
      }
      Ok({ ..table, rows: table.rows[1:].to_owned(), })
    }
    result => result
  }
}

///|
fn json_table_from_parts(
  name : String,
  parts : Array[String],
) -> Result[JsonInputTable, String] {
  let rows = []
  for index, text in parts {
    let content = if text.has_prefix("\uFEFF") {
      text[1:].to_owned()
    } else {
      text
    }
    let value = @json.parse(content, preserve_number_repr=true) catch {
      _ =>
        return Err(
          "JSON part " + (index + 1).to_string() + ": Invalid JSON row data",
        )
    }
    guard value is Array(part) else {
      return Err(
        "JSON part " + (index + 1).to_string() + ": Expected an array of rows",
      )
    }
    for row in part {
      rows.push(row)
    }
  }
  json_input_value(name, Json::array(rows))
}

///|
/// Validate CSV and JSON resources together, ensuring every constraint and
/// foreign key sees the complete logical table across all parts.
pub fn validate_mixed_package(
  descriptor : Descriptor,
  inputs : Array[TabularResourceInput],
  on_source? : (String, Int32, String, Int32, Int32) -> Unit,
  on_duplicate? : (String, Int32, Int32) -> Unit,
  on_relationships? : (ValidationPlan, RelationshipWork) -> Unit,
) -> PackageReport {
  let metadata = Map([])
  if prop(descriptor.original, "resources") is Array(resources) {
    for resource in resources {
      if prop(resource, "name") is String(name) {
        metadata[name] = resource
      }
    }
  }
  validate_inputs(
    descriptor,
    inputs,
    input => input.name,
    (resource, input) => {
      let item = metadata.get(resource.name).unwrap_or(Json::null())
      let table : Table = {
        name: resource.name,
        fields: resource.fields,
        rows: [],
      }
      fn failure(code : String, message : String) -> TableReport {
        {
          table,
          errors: [
            { code, resource: resource.name, row: 0, field: "", message, },
          ],
        }
      }
      let inline = prop(item, "data")
      let names = resource.fields.map(field => field.name)
      if tabular_format(item) == "json" {
        let result = if inline is Null {
          json_table_from_parts(input.name, input.parts)
        } else if inline is String(text) {
          let value = @json.parse(text, preserve_number_repr=true) catch {
            _ => return failure("input", "Invalid inline JSON row data")
          }
          inline_json_table(input.name, value, names)
        } else {
          inline_json_table(input.name, inline, names)
        }
        match result {
          Ok(t) =>
            validate_json_table(
              resource.name,
              resource.fields,
              t,
              missing_values=resource.missing_values,
              row_rules=resource.row_rules,
            )
          Err(message) => failure("input", message)
        }
      } else {
        let parts = match inline {
          String(text) => [text]
          Null => input.parts
          _ => return failure("csv", "Inline CSV must be a string")
        }
        let settings = match parse_tabular_csv_settings(prop(item, "dialect")) {
          Ok(settings) => settings
          Err(message) => return failure("csv", message)
        }
        let paths = strings(prop(item, "path")).unwrap_or([])
        let locate = on_source.map(emit => {
          fn(row : Int32, part : Int32, start : Int32, end : Int32) {
            let file = paths.get(part).unwrap_or(resource.name)
            emit(resource.name, row, file, start, end)
          }
        })
        match
          csv_table_from_parts(resource.name, parts, names, settings, locate?) {
          Ok(t) =>
            validate_table(
              resource.name,
              resource.fields,
              t.header,
              t.rows,
              missing_values=settings.missing_values(resource.missing_values),
              row_rules=resource.row_rules,
            )
          Err(error) => { table, errors: [error], }
        }
      }
    },
    on_duplicate?,
    on_relationships?,
  )
}