///|
/// One canonical column, with explicitly permitted names used by exporters.
#derive(Eq, Debug, ToJson, FromJson)
pub(all) struct Column {
  name : String
  aliases : Array[String]
  required : Bool
}

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

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

///|
pub extend Column with ToJson::{to_json}

///|
pub extend Column with @json.FromJson::{from_json}

///|
/// JSON schema version 1. Delimiters are "comma", "semicolon", and "tab".
#derive(Eq, Debug, ToJson, FromJson)
pub(all) struct Contract {
  version : Int32
  delimiter : String
  columns : Array[Column]
  allow_extra : Bool
  enforce_order : Bool
}

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

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

///|
pub extend Contract with ToJson::{to_json}

///|
pub extend Contract with @json.FromJson::{from_json}

///|
pub suberror ContractError {
  InvalidContract(String)
}

///|
pub fn Contract::separator(self : Contract) -> Delimiter raise ContractError {
  match self.delimiter {
    "comma" => Comma
    "semicolon" => Semicolon
    "tab" => Tab
    value => raise InvalidContract("unsupported delimiter: \{value}")
  }
}

///|
fn register_name(
  owners : Map[String, Int32],
  name : String,
  index : Int32,
) -> Unit raise ContractError {
  if name.trim().is_empty() {
    raise InvalidContract("column names and aliases must not be blank")
  }
  for ch in name {
    if ch == '\u{0000}' {
      raise InvalidContract("column names and aliases must not contain NUL")
    }
  }
  if owners.contains(name) {
    raise InvalidContract("name or alias is declared more than once: \{name}")
  }
  owners[name] = index
}

///|
fn Contract::index_contract(
  self : Contract,
) -> Map[String, Int32] raise ContractError {
  if self.version != 1 {
    raise InvalidContract("only contract version 1 is supported")
  }
  ignore(self.separator())
  if self.columns.is_empty() {
    raise InvalidContract("a contract must declare at least one column")
  }
  let owners : Map[String, Int32] = Map([])
  for index, column in self.columns {
    register_name(owners, column.name, index)
    for alternate in column.aliases {
      register_name(owners, alternate, index)
    }
  }
  owners
}

///|
pub fn Contract::validate(self : Contract) -> Unit raise ContractError {
  ignore(self.index_contract())
}

///|
/// Decode and validate a JSON contract before using it for an import.
pub fn parse_contract(input : String) -> Contract raise {
  let contract : Contract = @json.from_json(@json.parse(input))
  contract.validate()
  contract
}

///|
/// Build a strict baseline from a trusted sample header.
pub fn snapshot_header(
  header : Array[String],
  delimiter : Delimiter,
) -> Contract raise ContractError {
  let columns = header.map(fn(name) { { name, aliases: [], required: true, } })
  let delimiter = match delimiter {
    Comma => "comma"
    Semicolon => "semicolon"
    Tab => "tab"
  }
  let contract = {
    version: 1,
    delimiter,
    columns,
    allow_extra: false,
    enforce_order: true,
  }
  contract.validate()
  contract
}