///|
let sitemap_namespace = "http://www.sitemaps.org/schemas/sitemap/0.9"

///|
let sitemap_max_entries = 50000

///|
let sitemap_max_document_bytes = 52428800

///|
let sitemap_max_location_bytes = 2048

///|
pub struct SitemapDecoder {
  priv tokenizer : @xml.XmlTokenizer
  priv max_entries : Int
  priv max_text_bytes : Int
  priv stack : Array[String]
  priv mut root : String?
  priv urls : Array[@model.SitemapUrl]
  priv refs : Array[@model.SitemapRef]
  priv mut host : String?
  priv mut loc : String?
  priv mut lastmod : String?
  priv mut changefreq : String?
  priv mut priority : Double?
  priv mut seen_loc : Bool
  priv mut seen_lastmod : Bool
  priv mut seen_changefreq : Bool
  priv mut seen_priority : Bool
  priv mut text : String
  priv mut ignored_depth : Int
  priv mut consumed_bytes : Int
  priv mut finished : Bool
}

///|
fn sitemap_error(reason : String) -> @model.DiscoveryError {
  InvalidSitemap(reason~)
}

///|
fn is_core_element(raw : String) -> String? {
  if raw.contains(":") {
    None
  } else {
    match raw {
      "urlset"
      | "sitemapindex"
      | "url"
      | "sitemap"
      | "loc"
      | "lastmod"
      | "changefreq"
      | "priority" => Some(raw)
      _ => None
    }
  }
}

///|
fn is_digits(value : String) -> Bool {
  !value.is_empty() && value.all(char => char.is_ascii_digit())
}

///|
fn parse_decimal(value : String) -> Int? {
  let parsed = @string.parse_int(value) catch { _ => -1 }
  if parsed < 0 {
    None
  } else {
    Some(parsed)
  }
}

///|
fn is_between(value : String, lower : Int, upper : Int) -> Bool {
  match parse_decimal(value) {
    Some(number) => number >= lower && number <= upper
    None => false
  }
}

///|
fn valid_date(value : String) -> Bool {
  if value.length() != 10 ||
    value[4] != '-' ||
    value[7] != '-' ||
    !is_digits(value[:4].to_owned()) ||
    !is_digits(value[5:7].to_owned()) ||
    !is_digits(value[8:].to_owned()) {
    return false
  }
  let year = parse_decimal(value[:4].to_owned())
  let month = parse_decimal(value[5:7].to_owned())
  let day = parse_decimal(value[8:].to_owned())
  match (year, month, day) {
    (Some(year), Some(month), Some(day)) => {
      let days = match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31
        4 | 6 | 9 | 11 => 30
        2 =>
          if year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) {
            29
          } else {
            28
          }
        _ => 0
      }
      day >= 1 && day <= days
    }
    _ => false
  }
}

///|
fn valid_timezone(value : String) -> Bool {
  value == "Z" ||
  (
    value.length() == 6 &&
    (value[0] == '+' || value[0] == '-') &&
    value[3] == ':' &&
    is_between(value[1:3].to_owned(), 0, 23) &&
    is_between(value[4:].to_owned(), 0, 59)
  )
}

///|
fn valid_lastmod(value : String) -> Bool {
  if valid_date(value) {
    return true
  }
  if value.length() < 19 ||
    value[10] != 'T' ||
    value[13] != ':' ||
    value[16] != ':' ||
    !valid_date(value[:10].to_owned()) ||
    !is_between(value[11:13].to_owned(), 0, 23) ||
    !is_between(value[14:16].to_owned(), 0, 59) ||
    !is_between(value[17:19].to_owned(), 0, 59) {
    return false
  }
  if value.length() == 19 {
    return true
  }
  let suffix = value[19:].to_owned()
  if suffix.has_prefix("Z") || suffix.has_prefix("+") || suffix.has_prefix("-") {
    return valid_timezone(suffix)
  }
  if !suffix.has_prefix(".") {
    return false
  }
  let fractional = suffix[1:].to_owned()
  match fractional.find_by(char => char == 'Z' || char == '+' || char == '-') {
    None => is_digits(fractional)
    Some(offset) =>
      is_digits(fractional[:offset].to_owned()) &&
      valid_timezone(fractional[offset:].to_owned())
  }
}

///|
fn valid_changefreq(value : String) -> Bool {
  match value {
    "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never" =>
      true
    _ => false
  }
}

///|
fn host_end(authority : String) -> Int {
  let mut end = authority.length()
  for separator in ["/", "?", "#"] {
    match authority.find(separator) {
      Some(offset) => end = end.min(offset)
      None => ()
    }
  }
  end
}

///|
fn valid_host_char(char : Char) -> Bool {
  char.is_ascii_alphabetic() ||
  char.is_ascii_digit() ||
  char == '-' ||
  char == '.'
}

///|
fn valid_ipv6_char(char : Char) -> Bool {
  char.is_ascii_hexdigit() || char == ':' || char == '.'
}

///|
fn valid_port(value : String) -> Bool {
  is_digits(value) && is_between(value, 0, 65535)
}

///|
fn location_host(value : String) -> String? {
  match value.find("://") {
    None => None
    Some(scheme_end) => {
      let scheme = value[:scheme_end].to_owned().to_lower()
      if scheme != "http" && scheme != "https" {
        return None
      }
      let remainder = value[scheme_end + 3:].to_owned()
      let authority_end = host_end(remainder)
      let authority = remainder[:authority_end].to_owned()
      if authority.is_empty() ||
        authority.contains("@") ||
        authority.contains("\\") {
        return None
      }
      if authority.has_prefix("[") {
        match authority.find("]") {
          Some(close) => {
            let literal = authority[1:close].to_owned()
            let tail = authority[close + 1:].to_owned()
            if literal.is_empty() ||
              !literal.all(valid_ipv6_char) ||
              (
                !tail.is_empty() &&
                (!tail.has_prefix(":") || !valid_port(tail[1:].to_owned()))
              ) {
              None
            } else {
              Some("[" + literal.to_lower() + "]")
            }
          }
          None => None
        }
      } else {
        match authority.rev_find(":") {
          Some(port_separator) => {
            if authority.find(":") != Some(port_separator) {
              return None
            }
            let host = authority[:port_separator].to_owned()
            let port = authority[port_separator + 1:].to_owned()
            if host.is_empty() ||
              !host.all(valid_host_char) ||
              !valid_port(port) {
              None
            } else {
              Some(host.to_lower())
            }
          }
          None =>
            if authority.is_empty() ||
              !authority.all(valid_host_char) ||
              authority.has_prefix(".") ||
              authority.has_suffix(".") {
              None
            } else {
              Some(authority.to_lower())
            }
        }
      }
    }
  }
}

///|
fn checked_location_host(value : String) -> String raise @model.DiscoveryError {
  if @utf8.encode(value).length() > sitemap_max_location_bytes {
    raise LimitExceeded(
      kind="sitemap location bytes",
      limit=sitemap_max_location_bytes,
    )
  }
  match location_host(value) {
    Some(host) => host
    None =>
      raise sitemap_error("loc must be an absolute http(s) URL with a host")
  }
}

///|
fn validate_url_fields(
  url : @model.SitemapUrl,
) -> String raise @model.DiscoveryError {
  let host = checked_location_host(url.loc)
  match url.lastmod {
    Some(value) if !valid_lastmod(value) =>
      raise sitemap_error("lastmod must be an ISO-8601 date or date-time")
    _ => ()
  }
  match url.changefreq {
    Some(value) if !valid_changefreq(value) =>
      raise sitemap_error("changefreq is not a Sitemap protocol value")
    _ => ()
  }
  match url.priority {
    Some(value) if value != value || value < 0.0 || value > 1.0 =>
      raise sitemap_error("priority must be between 0.0 and 1.0")
    _ => ()
  }
  host
}

///|
fn validate_ref_fields(
  reference : @model.SitemapRef,
) -> String raise @model.DiscoveryError {
  let host = checked_location_host(reference.loc)
  match reference.lastmod {
    Some(value) if !valid_lastmod(value) =>
      raise sitemap_error("lastmod must be an ISO-8601 date or date-time")
    _ => ()
  }
  host
}

///|
fn SitemapDecoder::check_limits(
  self : SitemapDecoder,
) -> Unit raise @model.DiscoveryError {
  if self.max_entries <= 0 || self.max_entries > sitemap_max_entries {
    raise InvalidArgument(reason="max_entries must be between 1 and 50000")
  }
  if self.max_text_bytes <= 0 ||
    self.max_text_bytes > sitemap_max_document_bytes {
    raise InvalidArgument(
      reason="max_text_bytes must be between 1 and 52428800",
    )
  }
}

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

///|
fn SitemapDecoder::entry_parent(self : SitemapDecoder) -> String? {
  match self.stack.last() {
    Some("url") => Some("url")
    Some("sitemap") => Some("sitemap")
    _ => None
  }
}

///|
fn SitemapDecoder::reset_entry(self : SitemapDecoder) -> Unit {
  self.loc = None
  self.lastmod = None
  self.changefreq = None
  self.priority = None
  self.seen_loc = false
  self.seen_lastmod = false
  self.seen_changefreq = false
  self.seen_priority = false
  self.text = ""
}

///|
pub fn SitemapDecoder::new(
  max_entries? : Int = sitemap_max_entries,
  max_text_bytes? : Int = sitemap_max_document_bytes,
) -> SitemapDecoder {
  {
    tokenizer: @xml.XmlTokenizer::new(max_token_bytes=65536),
    max_entries,
    max_text_bytes,
    stack: [],
    root: None,
    urls: [],
    refs: [],
    host: None,
    loc: None,
    lastmod: None,
    changefreq: None,
    priority: None,
    seen_loc: false,
    seen_lastmod: false,
    seen_changefreq: false,
    seen_priority: false,
    text: "",
    ignored_depth: 0,
    consumed_bytes: 0,
    finished: false,
  }
}

///|
fn SitemapDecoder::begin_element(
  self : SitemapDecoder,
  raw : String,
  default_namespace : String?,
) -> Unit raise @model.DiscoveryError {
  let core = is_core_element(raw)
  if self.ignored_depth > 0 {
    self.ignored_depth += 1
    self.stack.push(raw)
    return
  }
  match self.root {
    None =>
      match core {
        Some("urlset" | "sitemapindex" as root) => {
          if default_namespace != Some(sitemap_namespace) {
            raise sitemap_error("root must use the Sitemap default namespace")
          }
          self.root = Some(root)
        }
        _ =>
          raise sitemap_error(
            "root must be an unprefixed urlset or sitemapindex",
          )
      }
    Some(root) => {
      if self.stack.is_empty() {
        raise sitemap_error("multiple root elements are not allowed")
      }
      match (core, default_namespace) {
        (Some(_), Some(declared_namespace)) if declared_namespace !=
          sitemap_namespace =>
          raise sitemap_error("core Sitemap elements must not change namespace")
        _ => ()
      }
      match core {
        Some("url") => {
          if root != "urlset" || self.stack.length() != 1 {
            raise sitemap_error("url entry belongs directly to urlset")
          }
          self.reset_entry()
        }
        Some("sitemap") => {
          if root != "sitemapindex" || self.stack.length() != 1 {
            raise sitemap_error(
              "sitemap entry belongs directly to sitemapindex",
            )
          }
          self.reset_entry()
        }
        Some("loc" | "lastmod" | "changefreq" | "priority" as field) => {
          match self.entry_parent() {
            Some("url") =>
              if field == "changefreq" ||
                field == "priority" ||
                field == "loc" ||
                field == "lastmod" {
                ()
              }
            Some("sitemap") =>
              if field == "changefreq" || field == "priority" {
                raise sitemap_error(
                  "changefreq and priority are only valid for url",
                )
              }
            _ =>
              raise sitemap_error(
                "Sitemap fields must be direct entry children",
              )
          }
          self.text = ""
        }
        Some("urlset" | "sitemapindex") =>
          raise sitemap_error("Sitemap root may not be nested")
        Some(_) => self.ignored_depth = 1
        None => self.ignored_depth = 1
      }
    }
  }
  self.stack.push(raw)
}

///|
fn SitemapDecoder::complete_field(
  self : SitemapDecoder,
  name : String,
) -> Unit raise @model.DiscoveryError {
  let value = self.text.trim().to_owned()
  match self.entry_parent() {
    None => ()
    Some(entry) =>
      match name {
        "loc" => {
          if self.seen_loc {
            raise sitemap_error("entry contains duplicate loc")
          }
          if value.is_empty() {
            raise sitemap_error("loc must not be empty")
          }
          self.record_host(checked_location_host(value))
          self.loc = Some(value)
          self.seen_loc = true
        }
        "lastmod" => {
          if self.seen_lastmod {
            raise sitemap_error("entry contains duplicate lastmod")
          }
          if !valid_lastmod(value) {
            raise sitemap_error("lastmod must be an ISO-8601 date or date-time")
          }
          self.lastmod = Some(value)
          self.seen_lastmod = true
        }
        "changefreq" => {
          if entry != "url" || self.seen_changefreq || !valid_changefreq(value) {
            raise sitemap_error(
              "changefreq must be a unique Sitemap protocol value",
            )
          }
          self.changefreq = Some(value)
          self.seen_changefreq = true
        }
        "priority" => {
          if entry != "url" || self.seen_priority {
            raise sitemap_error(
              "priority must be unique and valid only for url",
            )
          }
          let parsed = @string.parse_double(value) catch {
            _ => raise sitemap_error("priority must be a decimal number")
          }
          if parsed != parsed || parsed < 0.0 || parsed > 1.0 {
            raise sitemap_error("priority must be between 0.0 and 1.0")
          }
          self.priority = Some(parsed)
          self.seen_priority = true
        }
        _ => ()
      }
  }
}

///|
fn SitemapDecoder::complete_entry(
  self : SitemapDecoder,
  name : String,
  output : Array[@model.SitemapEvent],
) -> Unit raise @model.DiscoveryError {
  match (name, self.loc) {
    ("url", Some(loc)) => {
      if self.urls.length() >= self.max_entries {
        raise LimitExceeded(kind="sitemap entries", limit=self.max_entries)
      }
      let url : @model.SitemapUrl = {
        loc,
        lastmod: self.lastmod,
        changefreq: self.changefreq,
        priority: self.priority,
      }
      ignore(validate_url_fields(url))
      self.urls.push(url)
      output.push(Url(url))
    }
    ("sitemap", Some(loc)) => {
      if self.refs.length() >= self.max_entries {
        raise LimitExceeded(kind="sitemap entries", limit=self.max_entries)
      }
      let reference : @model.SitemapRef = { loc, lastmod: self.lastmod }
      ignore(validate_ref_fields(reference))
      self.refs.push(reference)
      output.push(Reference(reference))
    }
    ("url" | "sitemap", None) =>
      raise sitemap_error("each entry requires exactly one loc")
    _ => ()
  }
}

///|
fn SitemapDecoder::end_element(
  self : SitemapDecoder,
  raw : String,
  output : Array[@model.SitemapEvent],
) -> Unit raise @model.DiscoveryError {
  let was_ignored = self.ignored_depth > 0
  match self.stack.pop() {
    Some(opened) if opened == raw => ()
    Some(_) => raise sitemap_error("mismatched closing element: \{raw}")
    None => raise sitemap_error("closing element without an opening element")
  }
  if was_ignored {
    self.ignored_depth -= 1
    return
  }
  match is_core_element(raw) {
    Some(name) => {
      self.complete_field(name)
      self.complete_entry(name, output)
      self.text = ""
    }
    None => ()
  }
}

///|
fn SitemapDecoder::consume(
  self : SitemapDecoder,
  tokens : Array[@xml.XmlToken],
) -> Array[@model.SitemapEvent] raise @model.DiscoveryError {
  let output : Array[@model.SitemapEvent] = []
  for token in tokens {
    match token {
      Start(start) => self.begin_element(start.name, start.default_namespace)
      End(name) => self.end_element(name, output)
      Text(value) =>
        if self.ignored_depth > 0 {
          ()
        } else if !self.stack.is_empty() {
          self.text = self.text + value
          if @utf8.encode(self.text).length() > self.max_text_bytes {
            raise LimitExceeded(kind="sitemap text", limit=self.max_text_bytes)
          }
        } else if !value.trim().is_empty() {
          raise sitemap_error("text is not allowed outside the root element")
        }
    }
  }
  output
}

///|
pub fn SitemapDecoder::push(
  self : SitemapDecoder,
  chunk : String,
) -> Array[@model.SitemapEvent] raise @model.DiscoveryError {
  if self.finished {
    raise sitemap_error("decoder is already finished")
  }
  self.check_limits()
  self.consumed_bytes += @utf8.encode(chunk).length()
  if self.consumed_bytes > self.max_text_bytes {
    raise LimitExceeded(
      kind="sitemap document bytes",
      limit=self.max_text_bytes,
    )
  }
  self.consume(self.tokenizer.push(chunk))
}

///|
pub fn SitemapDecoder::finish(
  self : SitemapDecoder,
) -> @model.SitemapDocument raise @model.DiscoveryError {
  if self.finished {
    raise sitemap_error("decoder is already finished")
  }
  self.check_limits()
  ignore(self.consume(self.tokenizer.finish()))
  if !self.stack.is_empty() {
    raise sitemap_error("unclosed XML element")
  }
  self.finished = true
  match self.root {
    Some("urlset") => UrlSet(self.urls)
    Some("sitemapindex") => Index(self.refs)
    _ => raise sitemap_error("missing Sitemap root element")
  }
}

///|
/// Parse a complete document by using the same incremental state machine.
pub fn parse(
  text : String,
) -> @model.SitemapDocument raise @model.DiscoveryError {
  let decoder = SitemapDecoder::new()
  ignore(decoder.push(text))
  decoder.finish()
}