///|
fn escape_xml(value : String) -> String {
  value
  .replace_all(old="&", new="&")
  .replace_all(old="<", new="<")
  .replace_all(old=">", new=">")
  .replace_all(old="\"", new=""")
  .replace_all(old="'", new="'")
}

///|
fn urlset_opening() -> String {
  "\n\n"
}

///|
fn urlset_closing() -> String {
  "\n"
}

///|
fn index_opening() -> String {
  "\n\n"
}

///|
fn index_closing() -> String {
  "\n"
}

///|
fn write_optional(
  builder : StringBuilder,
  name : String,
  value : String?,
) -> Unit {
  match value {
    Some(item) =>
      builder.write_string("    <\{name}>\{escape_xml(item)}\n")
    None => ()
  }
}

///|
/// Render one validated `url` entry using the same canonical layout as
/// `serialize`. Keeping this small unit separate lets the partition planner
/// account for UTF-8 bytes without repeatedly serializing an entire prefix.
fn render_url_entry(url : @model.SitemapUrl) -> String {
  let out = StringBuilder()
  out.write_string("  \n    \{escape_xml(url.loc)}\n")
  write_optional(out, "lastmod", url.lastmod)
  write_optional(out, "changefreq", url.changefreq)
  match url.priority {
    Some(value) => out.write_string("    \{value}\n")
    None => ()
  }
  out.write_string("  \n")
  out.to_string()
}

///|
/// Render one validated `sitemap` entry using the same canonical layout as
/// `serialize`.
fn render_ref_entry(reference : @model.SitemapRef) -> String {
  let out = StringBuilder()
  out.write_string("  \n    \{escape_xml(reference.loc)}\n")
  write_optional(out, "lastmod", reference.lastmod)
  out.write_string("  \n")
  out.to_string()
}

///|
fn utf8_byte_length(value : String) -> Int {
  @utf8.encode(value).length()
}

///|
fn urlset_fixed_bytes() -> Int {
  utf8_byte_length(urlset_opening()) + utf8_byte_length(urlset_closing())
}

///|
fn index_fixed_bytes() -> Int {
  utf8_byte_length(index_opening()) + utf8_byte_length(index_closing())
}

///|
fn check_document_host(
  host : String?,
  next : String,
) -> String raise @model.DiscoveryError {
  match host {
    None => next
    Some(current) if current == next => current
    Some(_) =>
      raise sitemap_error("all Sitemap locations must use the same host")
  }
}

///|
fn check_serialized_size(value : String) -> String raise @model.DiscoveryError {
  if @utf8.encode(value).length() > sitemap_max_document_bytes {
    raise LimitExceeded(
      kind="serialized sitemap bytes",
      limit=sitemap_max_document_bytes,
    )
  }
  value
}

///|
/// Serialize a validated Sitemap document in a stable compactly-indented XML
/// representation. All text fields are escaped and output always has the
/// canonical Sitemap namespace.
pub fn serialize(
  document : @model.SitemapDocument,
) -> String raise @model.DiscoveryError {
  let out = StringBuilder()
  match document {
    UrlSet(urls) => {
      if urls.length() > sitemap_max_entries {
        raise LimitExceeded(kind="sitemap entries", limit=sitemap_max_entries)
      }
      out.write_string(urlset_opening())
      let mut host : String? = None
      for url in urls {
        host = Some(check_document_host(host, validate_url_fields(url)))
        out.write_string(render_url_entry(url))
      }
      out.write_string(urlset_closing())
    }
    Index(refs) => {
      if refs.length() > sitemap_max_entries {
        raise LimitExceeded(kind="sitemap entries", limit=sitemap_max_entries)
      }
      out.write_string(index_opening())
      let mut host : String? = None
      for reference in refs {
        host = Some(check_document_host(host, validate_ref_fields(reference)))
        out.write_string(render_ref_entry(reference))
      }
      out.write_string(index_closing())
    }
  }
  check_serialized_size(out.to_string())
}

///|
/// Split a URL set in input order. The caller can choose a smaller limit for
/// transport or CI; values above the protocol maximum are rejected.
pub fn split_urls(
  urls : ArrayView[@model.SitemapUrl],
  max_urls? : Int = sitemap_max_entries,
) -> Array[@model.SitemapDocument] raise @model.DiscoveryError {
  if max_urls <= 0 || max_urls > sitemap_max_entries {
    raise InvalidArgument(reason="max_urls must be between 1 and 50000")
  }
  let result : Array[@model.SitemapDocument] = []
  let mut current : Array[@model.SitemapUrl] = []
  let mut host : String? = None
  for url in urls {
    host = Some(check_document_host(host, validate_url_fields(url)))
    current.push(url)
    if current.length() == max_urls {
      result.push(UrlSet(current))
      current = []
    }
  }
  if !current.is_empty() {
    result.push(UrlSet(current))
  }
  result
}