///|
/// Decoded metadata with lowercase field names, an optional charset and the original header text.
/// Example: `file.metadata.headers.get("content-type")`.
#derive(Eq, @debug.Debug)
pub struct MoMetadata {
  raw_header : String?
  headers : Map[String, String]
  charset : String?
  plural_forms_raw : String?
}

///|
/// Unfold continuation lines in the structured view. Keep raw_header verbatim.
fn header_fields(raw : String) -> Map[String, String] {
  let fields : Map[String, String] = Map([])
  let mut name : String? = None
  let value = StringBuilder()
  for line in raw.split("\n") {
    if line.trim().is_empty() || line.has_prefix("#-#-#-#-#") {
      continue
    }
    if line.has_prefix(" ") || line.has_prefix("\t") {
      if name is Some(_) {
        value.write_char(' ')
        value.write_view(line.trim())
      }
      continue
    }
    if name is Some(key) {
      fields[key] = value.to_string()
    }
    value.reset()
    name = None
    if line.split_once(":") is Some((key, rest)) {
      name = Some(key.trim().to_lower().to_owned())
      value.write_view(rest.trim())
    }
  }
  if name is Some(key) {
    fields[key] = value.to_string()
  }
  fields
}

///|
/// MIME parameter separators inside a quoted value belong to that value.
fn declared_charset(content_type : String) -> String? raise MoError {
  let mut start = 0
  let mut quoted = false
  let mut escaped = false
  let mut charset : String? = None
  let n = content_type.length()
  for i in 0..<=n {
    if i == n || (!quoted && content_type[i] == ';') {
      if start > 0 &&
        content_type[start:i].split_once("=") is Some((key, raw)) &&
        key.trim().to_lower() == "charset" {
        let value = raw.trim()
        let label = if value.length() >= 2 &&
          value.has_prefix("\"") &&
          value.has_suffix("\"") {
          value[1:value.length() - 1].to_owned()
        } else {
          value.to_owned()
        }
        match label.to_lower() {
          "utf-8" | "utf8" => charset = Some(label)
          _ => raise UnsupportedCharset(declared=label)
        }
      }
      if i < n {
        start = i + 1
      }
    } else if escaped {
      escaped = false
    } else if quoted && content_type[i] == '\\' {
      escaped = true
    } else if content_type[i] == '"' {
      quoted = !quoted
    }
  }
  charset
}

///|
fn read_metadata(header : BytesView?) -> MoMetadata raise MoError {
  guard header is Some(bytes) else {
    return {
      raw_header: None,
      headers: Map([]),
      charset: None,
      plural_forms_raw: None,
    }
  }
  // Inspect the MIME declaration even if another header line has legacy bytes.
  // Only a strictly decoded header can escape this function.
  let raw = @utf8.decode_lossy(bytes)
  let fields = header_fields(raw)
  let charset = match fields.get("content-type") {
    Some(content_type) => declared_charset(content_type)
    None => None
  }
  let raw_header = decode_string(bytes, "translation", 0, charset)
  {
    raw_header: Some(raw_header),
    headers: fields,
    charset,
    plural_forms_raw: fields.get("plural-forms"),
  }
}

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