///|
priv enum Translation {
  Singular(String)
  Forms(Array[String], String)
}

///|
priv struct Message {
  key : Bytes
  translation : Translation
}

///|
/// Catalog header snapshot with optional declared fields and an effective plural count.
/// Example: `cat.metadata().nplurals`.
#derive(Eq, @debug.Debug)
pub struct CatalogMetadata {
  language : String?
  charset : String?
  nplurals : Int32
  plural_forms_raw : String?
  raw_header : String?
  headers : Map[String, String]
}

///|
/// Write the diagnostic representation of CatalogMetadata to a logger.
/// Example: `value.to_string()`.
pub impl Show for CatalogMetadata with fn output(self, logger) {
  logger.write_string(@debug.to_string(self))
}

///|
/// Immutable directory of validated UTF-8 messages, searched by MO key order.
/// Example: `Catalog::empty().len()`.
pub struct Catalog {
  priv messages : Array[Message]
  priv rule : @plural.PluralRule
  priv info : CatalogMetadata
}

///|
/// Create a zero-entry catalog with the default two-form rule. Queries fall back to source text.
/// Example: `Catalog::empty().gettext("Open")`.
pub fn Catalog::empty() -> Catalog {
  let rule = @plural.PluralRule::default_germanic()
  {
    messages: [],
    rule,
    info: {
      language: None,
      charset: None,
      nplurals: rule.nplurals,
      plural_forms_raw: None,
      raw_header: None,
      headers: Map([]),
    },
  }
}

///|
/// Count original-table entries, including the metadata row when stored.
/// Example: `cat.len()`.
pub fn Catalog::len(self : Catalog) -> Int32 {
  self.messages.length()
}

///|
/// Return the compiled rule, including the default when the header omitted Plural-Forms.
/// Example: `cat.plural_rule().eval_index(2)`.
pub fn Catalog::plural_rule(self : Catalog) -> @plural.PluralRule {
  self.rule
}

///|
/// Return decoded metadata with a fresh header map that the caller may edit.
/// Example: `cat.metadata().headers.get("language")`.
pub fn Catalog::metadata(self : Catalog) -> CatalogMetadata {
  { ..self.info, headers: self.info.headers.copy(), }
}

///|
/// Validate revision, layout, ordering, encoding and plural syntax at load time. Raises Mo or Plural on invalid input.
/// Example: `Catalog::from_bytes(bytes)`.
pub fn Catalog::from_bytes(bytes : Bytes) -> Catalog raise GettextError {
  let file = @mo.parse_mo(bytes) catch { e => raise Mo(e) }
  let meta = file.metadata
  let rule = match meta.plural_forms_raw {
    None => @plural.PluralRule::default_germanic()
    Some(value) =>
      @plural.PluralRule::parse(value) catch {
        e => raise Plural(e)
      }
  }
  // Ordinary lookup of any plural entry uses the same plural(1) result.
  let singular_index = rule.eval_index(1) catch { _ => 0 }
  let messages = file.entries.map(fn(entry) {
    // parse_mo validated the complete byte sequence and every NUL is a UTF-8 boundary.
    let text = @utf8.decode_lossy(entry.trans_bytes)
    let translation = match entry.plural_orig_bytes {
      None => Singular(text)
      Some(_) => {
        let forms = text.split("\u0000").map(s => s.to_owned()).to_array()
        Forms(forms, forms.get(singular_index).unwrap_or(forms[0]))
      }
    }
    { key: entry.key_bytes, translation, }
  })
  {
    messages,
    rule,
    info: {
      language: meta.headers.get("language"),
      charset: meta.charset,
      nplurals: rule.nplurals,
      plural_forms_raw: meta.plural_forms_raw,
      raw_header: meta.raw_header,
      headers: meta.headers,
    },
  }
}

///|
fn Catalog::find(self : Catalog, msgid : String) -> Translation? {
  let key = @utf8.encode(msgid)
  let mut low = 0
  let mut high = self.messages.length()
  while low < high {
    let mid = low + (high - low) / 2
    let entry = self.messages[mid]
    let order = entry.key.lexical_compare(key)
    if order == 0 {
      return Some(entry.translation)
    } else if order < 0 {
      low = mid + 1
    } else {
      high = mid
    }
  }
  None
}

///|
fn is_ascii(s : String) -> Bool {
  for i in 0..= 0x80 {
      return false
    }
  }
  true
}

///|
fn compare_key_ascii(entry_key : Bytes, query : String) -> Int {
  let entry_length = entry_key.length()
  let query_length = query.length()
  // An ASCII code unit has the same unsigned value as its single UTF-8 byte.
  for i in 0.. Translation? {
  let mut low = 0
  let mut high = self.messages.length()
  while low < high {
    let mid = low + (high - low) / 2
    let entry = self.messages[mid]
    let order = compare_key_ascii(entry.key, msgid)
    if order == 0 {
      return Some(entry.translation)
    } else if order < 0 {
      low = mid + 1
    } else {
      high = mid
    }
  }
  None
}

///|
/// Return None for a miss and Some("") for an empty hit. Ordinary plural hits select plural(1), with slot zero as fallback.
/// Example: `cat.try_gettext("Ready")`.
pub fn Catalog::try_gettext(self : Catalog, msgid : String) -> String? {
  let translation = if is_ascii(msgid) {
    self.find_ascii(msgid)
  } else {
    self.find(msgid)
  }
  match translation {
    None => None
    Some(Singular(text)) => Some(text)
    Some(Forms(_, ordinary)) => Some(ordinary)
  }
}

///|
/// Return a translation, including an explicit empty string, or the original ID on a miss.
/// Example: `cat.gettext("Ready")`.
pub fn Catalog::gettext(self : Catalog, msgid : String) -> String {
  self.try_gettext(msgid).unwrap_or(msgid)
}

///|
fn context_key(ctx : String, msgid : String) -> String {
  ctx + "\u0004" + msgid
}

///|
/// Look up the exact context and ID. Returns None on a miss and preserves empty hits.
/// Example: `cat.try_pgettext("menu", "Open")`.
pub fn Catalog::try_pgettext(
  self : Catalog,
  msgctxt : String,
  msgid : String,
) -> String? {
  self.try_gettext(context_key(msgctxt, msgid))
}

///|
/// Return the contextual translation or the original ID on a miss.
/// Example: `cat.pgettext("menu", "Open")`.
pub fn Catalog::pgettext(
  self : Catalog,
  msgctxt : String,
  msgid : String,
) -> String {
  self.try_pgettext(msgctxt, msgid).unwrap_or(msgid)
}

///|
fn Catalog::plural_lookup(
  self : Catalog,
  key : String,
  msgid : String,
  n : UInt64,
) -> String? raise GettextError {
  guard self.find(key) is Some(Forms(forms, _)) else { return None }
  let index = self.rule.eval_index(n) catch { e => raise Plural(e) }
  guard forms.get(index) is Some(form) else {
    raise PluralFormOutOfRange(
      msgid~,
      index~,
      available_forms=forms.length(),
      nplurals=self.rule.nplurals,
    )
  }
  Some(form)
}

///|
/// Return the selected plural slot, or None for absent or singular entries. Raises Plural for rule errors and PluralFormOutOfRange for missing slots.
/// Example: `cat.try_ngettext_checked("lamp", 2)`.
pub fn Catalog::try_ngettext_checked(
  self : Catalog,
  msgid : String,
  n : UInt64,
) -> String? raise GettextError {
  self.plural_lookup(msgid, msgid, n)
}

///|
/// Look up a plural in one context. Absent or singular entries yield None. Rule errors raise Plural and missing slots raise PluralFormOutOfRange.
/// Example: `cat.try_npgettext_checked("inventory", "lamp", 2)`.
pub fn Catalog::try_npgettext_checked(
  self : Catalog,
  msgctxt : String,
  msgid : String,
  n : UInt64,
) -> String? raise GettextError {
  self.plural_lookup(context_key(msgctxt, msgid), msgid, n)
}

///|
fn source_form(msgid : String, msgid_plural : String, n : UInt64) -> String {
  if n == 1 {
    msgid
  } else {
    msgid_plural
  }
}

///|
/// Select a translated slot. On a miss or plural error, return the singular source for n=1 and the plural source otherwise.
/// Example: `cat.ngettext("lamp", "lamps", 2)`.
pub fn Catalog::ngettext(
  self : Catalog,
  msgid : String,
  msgid_plural : String,
  n : UInt64,
) -> String {
  let value = self.try_ngettext_checked(msgid, n) catch { _ => None }
  value.unwrap_or(source_form(msgid, msgid_plural, n))
}

///|
/// Select a translated slot within a context. Misses and plural errors fall back to the supplied source forms using n=1.
/// Example: `cat.npgettext("inventory", "lamp", "lamps", 2)`.
pub fn Catalog::npgettext(
  self : Catalog,
  msgctxt : String,
  msgid : String,
  msgid_plural : String,
  n : UInt64,
) -> String {
  let value = self.try_npgettext_checked(msgctxt, msgid, n) catch { _ => None }
  value.unwrap_or(source_form(msgid, msgid_plural, n))
}