/// Additional protocol validation, inspection, and deterministic partitioning.
/// All operations in this file work on already-constructed model values, so
/// callers can validate generated Sitemaps without serializing and parsing
/// them again.

///|
/// The top-level document kind observed by `inspect_document`.
pub enum SitemapKind {
  UrlSetDocument
  SitemapIndexDocument
} derive(Debug, Eq)

///|
/// A stable, offline summary of a validated Sitemap document.
///
/// `host` is the normalized lower-case hostname shared by the entries (or
/// `None` for an empty document). `canonical_bytes` is the UTF-8 byte length
/// of this package's deterministic `serialize` representation, not the byte
/// length of a source document that may contain different whitespace.
pub(all) struct SitemapInspection {
  kind : SitemapKind
  entry_count : Int
  unique_locations : Int
  duplicate_locations : Int
  location_bytes : Int
  host : String?
  lastmod_entries : Int
  changefreq_entries : Int
  priority_entries : Int
  priority_total : Double
  priority_min : Double?
  priority_max : Double?
  priority_average : Double?
  canonical_bytes : Int
} derive(Debug, Eq)

///|
/// Limits for deterministic Sitemap partitioning. Both limits are inclusive:
/// a shard may contain exactly `max_entries` entries and exactly
/// `max_document_bytes` UTF-8 bytes in canonical serialized form.
///
/// Constructing this value is infallible to support configuration loading;
/// `partition_urls` and `partition_refs` reject invalid values before reading
/// their input.
pub(all) struct SitemapPartitionLimits {
  max_entries : Int
  max_document_bytes : Int
} derive(Debug, Eq)

///|
/// Construct partition limits. Values are checked by the partition operation,
/// allowing callers to collect all configuration before beginning work.
pub fn SitemapPartitionLimits::new(
  max_entries? : Int = sitemap_max_entries,
  max_document_bytes? : Int = sitemap_max_document_bytes,
) -> SitemapPartitionLimits {
  { max_entries, max_document_bytes }
}

///|
/// One deterministic output shard. `serialized_bytes` is exact for
/// `serialize(document)` and can be recorded alongside the output without a
/// second serialization pass.
pub(all) struct SitemapShard {
  document : @model.SitemapDocument
  entry_count : Int
  serialized_bytes : Int
} derive(Debug, Eq)

///|
fn validate_entry_count(count : Int) -> Unit raise @model.DiscoveryError {
  if count > sitemap_max_entries {
    raise LimitExceeded(kind="sitemap entries", limit=sitemap_max_entries)
  }
}

///|
fn checked_urlset_bytes(
  urls : Array[@model.SitemapUrl],
) -> Unit raise @model.DiscoveryError {
  let mut bytes = urlset_fixed_bytes()
  for url in urls {
    bytes += utf8_byte_length(render_url_entry(url))
    if bytes > sitemap_max_document_bytes {
      raise LimitExceeded(
        kind="serialized sitemap bytes",
        limit=sitemap_max_document_bytes,
      )
    }
  }
}

///|
fn checked_index_bytes(
  refs : Array[@model.SitemapRef],
) -> Unit raise @model.DiscoveryError {
  let mut bytes = index_fixed_bytes()
  for reference in refs {
    bytes += utf8_byte_length(render_ref_entry(reference))
    if bytes > sitemap_max_document_bytes {
      raise LimitExceeded(
        kind="serialized sitemap bytes",
        limit=sitemap_max_document_bytes,
      )
    }
  }
}

///|
fn validate_urlset(
  urls : Array[@model.SitemapUrl],
) -> Unit raise @model.DiscoveryError {
  validate_entry_count(urls.length())
  let mut host : String? = None
  for url in urls {
    host = Some(check_document_host(host, validate_url_fields(url)))
  }
  checked_urlset_bytes(urls)
}

///|
fn validate_index(
  refs : Array[@model.SitemapRef],
) -> Unit raise @model.DiscoveryError {
  validate_entry_count(refs.length())
  let mut host : String? = None
  for reference in refs {
    host = Some(check_document_host(host, validate_ref_fields(reference)))
  }
  checked_index_bytes(refs)
}

///|
/// Validate a constructed Sitemap document without reparsing XML. This checks
/// the protocol entry limit, canonical serialized size, one-host constraint,
/// absolute HTTP(S) locations, and every optional protocol field.
pub fn validate_document(
  document : @model.SitemapDocument,
) -> Unit raise @model.DiscoveryError {
  match document {
    UrlSet(urls) => validate_urlset(urls)
    Index(refs) => validate_index(refs)
  }
}

///|
fn make_inspection(
  kind : SitemapKind,
  entry_count : Int,
  unique_locations : Int,
  duplicate_locations : Int,
  location_bytes : Int,
  host : String?,
  lastmod_entries : Int,
  changefreq_entries : Int,
  priority_entries : Int,
  priority_total : Double,
  priority_min : Double?,
  priority_max : Double?,
  canonical_bytes : Int,
) -> SitemapInspection {
  let priority_average = if priority_entries == 0 {
    None
  } else {
    Some(priority_total / priority_entries.to_double())
  }
  {
    kind,
    entry_count,
    unique_locations,
    duplicate_locations,
    location_bytes,
    host,
    lastmod_entries,
    changefreq_entries,
    priority_entries,
    priority_total,
    priority_min,
    priority_max,
    priority_average,
    canonical_bytes,
  }
}

///|
fn inspect_urls(
  urls : Array[@model.SitemapUrl],
  canonical_bytes : Int,
) -> SitemapInspection raise @model.DiscoveryError {
  let seen : Map[String, Unit] = Map([])
  let mut duplicate_locations = 0
  let mut location_bytes = 0
  let mut host : String? = None
  let mut lastmod_entries = 0
  let mut changefreq_entries = 0
  let mut priority_entries = 0
  let mut priority_total = 0.0
  let mut priority_min : Double? = None
  let mut priority_max : Double? = None
  for url in urls {
    let next_host = checked_location_host(url.loc)
    host = Some(check_document_host(host, next_host))
    location_bytes += utf8_byte_length(url.loc)
    if seen.contains(url.loc) {
      duplicate_locations += 1
    } else {
      seen[url.loc] = ()
    }
    match url.lastmod {
      Some(_) => lastmod_entries += 1
      None => ()
    }
    match url.changefreq {
      Some(_) => changefreq_entries += 1
      None => ()
    }
    match url.priority {
      Some(priority) => {
        priority_entries += 1
        priority_total += priority
        priority_min = match priority_min {
          Some(current) => Some(current.min(priority))
          None => Some(priority)
        }
        priority_max = match priority_max {
          Some(current) => Some(current.max(priority))
          None => Some(priority)
        }
      }
      None => ()
    }
  }
  make_inspection(
    UrlSetDocument,
    urls.length(),
    seen.length(),
    duplicate_locations,
    location_bytes,
    host,
    lastmod_entries,
    changefreq_entries,
    priority_entries,
    priority_total,
    priority_min,
    priority_max,
    canonical_bytes,
  )
}

///|
fn inspect_refs(
  refs : Array[@model.SitemapRef],
  canonical_bytes : Int,
) -> SitemapInspection raise @model.DiscoveryError {
  let seen : Map[String, Unit] = Map([])
  let mut duplicate_locations = 0
  let mut location_bytes = 0
  let mut host : String? = None
  let mut lastmod_entries = 0
  for reference in refs {
    let next_host = checked_location_host(reference.loc)
    host = Some(check_document_host(host, next_host))
    location_bytes += utf8_byte_length(reference.loc)
    if seen.contains(reference.loc) {
      duplicate_locations += 1
    } else {
      seen[reference.loc] = ()
    }
    match reference.lastmod {
      Some(_) => lastmod_entries += 1
      None => ()
    }
  }
  make_inspection(
    SitemapIndexDocument,
    refs.length(),
    seen.length(),
    duplicate_locations,
    location_bytes,
    host,
    lastmod_entries,
    0,
    0,
    0.0,
    None,
    None,
    canonical_bytes,
  )
}

///|
/// Produce protocol statistics for a constructed document. The operation first
/// applies `validate_document`; therefore every reported value has passed the
/// same semantic checks as a parser or serializer. Duplicate locations are
/// reported rather than rejected because duplicate detection is operational
/// evidence, not a Sitemap XML validity failure.
pub fn inspect_document(
  document : @model.SitemapDocument,
) -> SitemapInspection raise @model.DiscoveryError {
  validate_document(document)
  let canonical_bytes = utf8_byte_length(serialize(document))
  match document {
    UrlSet(urls) => inspect_urls(urls, canonical_bytes)
    Index(refs) => inspect_refs(refs, canonical_bytes)
  }
}

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

///|
fn ensure_entry_fits_shard(
  fixed_bytes : Int,
  entry_bytes : Int,
  limits : SitemapPartitionLimits,
) -> Unit raise @model.DiscoveryError {
  if fixed_bytes + entry_bytes > limits.max_document_bytes {
    raise LimitExceeded(
      kind="sitemap shard bytes",
      limit=limits.max_document_bytes,
    )
  }
}

///|
fn make_url_shard(
  urls : Array[@model.SitemapUrl],
  serialized_bytes : Int,
) -> SitemapShard {
  { document: UrlSet(urls), entry_count: urls.length(), serialized_bytes }
}

///|
fn make_index_shard(
  refs : Array[@model.SitemapRef],
  serialized_bytes : Int,
) -> SitemapShard {
  { document: Index(refs), entry_count: refs.length(), serialized_bytes }
}

///|
/// Greedily partition URL entries in input order using both an entry-count and
/// canonical UTF-8 byte ceiling. No entry is reordered, dropped, or duplicated.
/// A single valid entry that cannot fit the configured byte ceiling raises
/// `LimitExceeded` instead of producing a non-conformant shard.
pub fn partition_urls(
  urls : ArrayView[@model.SitemapUrl],
  limits? : SitemapPartitionLimits = SitemapPartitionLimits::new(),
) -> Array[SitemapShard] raise @model.DiscoveryError {
  validate_partition_limits(limits)
  let result : Array[SitemapShard] = []
  let mut current : Array[@model.SitemapUrl] = []
  let mut current_bytes = urlset_fixed_bytes()
  let mut host : String? = None
  for url in urls {
    host = Some(check_document_host(host, validate_url_fields(url)))
    let entry_bytes = utf8_byte_length(render_url_entry(url))
    ensure_entry_fits_shard(urlset_fixed_bytes(), entry_bytes, limits)
    if current.length() == limits.max_entries ||
      current_bytes + entry_bytes > limits.max_document_bytes {
      result.push(make_url_shard(current, current_bytes))
      current = []
      current_bytes = urlset_fixed_bytes()
    }
    current.push(url)
    current_bytes += entry_bytes
  }
  if !current.is_empty() {
    result.push(make_url_shard(current, current_bytes))
  }
  result
}

///|
/// Greedily partition Sitemap-index references in input order. The planner has
/// the same deterministic count and byte guarantees as `partition_urls`, while
/// retaining the index document kind in every emitted shard.
pub fn partition_refs(
  refs : ArrayView[@model.SitemapRef],
  limits? : SitemapPartitionLimits = SitemapPartitionLimits::new(),
) -> Array[SitemapShard] raise @model.DiscoveryError {
  validate_partition_limits(limits)
  let result : Array[SitemapShard] = []
  let mut current : Array[@model.SitemapRef] = []
  let mut current_bytes = index_fixed_bytes()
  let mut host : String? = None
  for reference in refs {
    host = Some(check_document_host(host, validate_ref_fields(reference)))
    let entry_bytes = utf8_byte_length(render_ref_entry(reference))
    ensure_entry_fits_shard(index_fixed_bytes(), entry_bytes, limits)
    if current.length() == limits.max_entries ||
      current_bytes + entry_bytes > limits.max_document_bytes {
      result.push(make_index_shard(current, current_bytes))
      current = []
      current_bytes = index_fixed_bytes()
    }
    current.push(reference)
    current_bytes += entry_bytes
  }
  if !current.is_empty() {
    result.push(make_index_shard(current, current_bytes))
  }
  result
}