///|
fn report_finding(
  findings : Array[@model.AuditFinding],
  max_findings : Int,
  code : String,
  severity : @model.FindingSeverity,
  subject : String,
  message : String,
) -> Unit raise @model.DiscoveryError {
  if findings.length() >= max_findings {
    raise LimitExceeded(kind="audit findings", limit=max_findings)
  }
  push_finding(findings, code, severity, subject, message)
}

///|
fn split_uri(location : String) -> (String, String)? {
  match location.find("://") {
    None => None
    Some(scheme_end) => {
      let scheme = location[:scheme_end].to_owned().to_lower()
      if scheme != "http" && scheme != "https" {
        return None
      }
      let after = location[scheme_end + 3:].to_owned()
      let mut authority_end = after.length()
      for offset, character in after {
        if character == '/' || character == '?' || character == '#' {
          authority_end = offset
          break
        }
      }
      let authority = after[:authority_end].to_owned()
      if authority.is_empty() ||
        authority.contains("@") ||
        authority.contains("\\") {
        None
      } else {
        Some(
          (
            "\{scheme}://\{authority.to_lower()}",
            after[authority_end:].to_owned(),
          ),
        )
      }
    }
  }
}

///|
fn canonical_location(location : String) -> String? {
  match split_uri(location) {
    None => None
    Some((raw_origin, path)) => {
      let origin = origin_of(raw_origin)
      match origin {
        None => None
        Some(canonical_origin) => {
          let without_fragment = match path.find("#") {
            None => path
            Some(offset) => path[:offset].to_owned()
          }
          let normalized_path = if without_fragment.is_empty() {
            "/"
          } else if without_fragment.has_prefix("/") {
            without_fragment
          } else {
            "/" + without_fragment
          }
          Some(canonical_origin + normalized_path)
        }
      }
    }
  }
}

///|
fn location_has_fragment(location : String) -> Bool {
  match location.find("#") {
    None => false
    Some(_) => true
  }
}

///|
fn enhanced_location_findings(
  findings : Array[@model.AuditFinding],
  canonical_seen : Map[String, String],
  location : String,
  max_findings : Int,
) -> Unit raise @model.DiscoveryError {
  if location_has_fragment(location) {
    report_finding(
      findings,
      max_findings,
      "fragment-location",
      Information,
      location,
      "Sitemap locations with fragments identify the same fetched resource without the fragment",
    )
  }
  match canonical_location(location) {
    None => ()
    Some(key) =>
      match canonical_seen.get(key) {
        None => canonical_seen[key] = location
        Some(first) if first == location => ()
        Some(first) =>
          report_finding(
            findings,
            max_findings,
            "canonical-duplicate-location",
            Warning,
            location,
            "location canonicalizes to the same fetch target as \{first}",
          )
      }
  }
}

///|
fn checked_findings(
  findings : Array[@model.AuditFinding],
  max_findings : Int,
) -> Array[@model.AuditFinding] raise @model.DiscoveryError {
  if max_findings <= 0 || max_findings > 1000000 {
    raise InvalidArgument(reason="max_findings must be between 1 and 1000000")
  }
  if findings.length() > max_findings {
    raise LimitExceeded(kind="audit findings", limit=max_findings)
  }
  findings
}

///|
fn append_enhanced_findings(
  base : Array[@model.AuditFinding],
  sitemap : @model.SitemapDocument,
  max_findings : Int,
) -> Array[@model.AuditFinding] raise @model.DiscoveryError {
  let findings = checked_findings(base, max_findings)
  let canonical_seen : Map[String, String] = Map([])
  match sitemap {
    UrlSet(urls) => {
      if urls.is_empty() {
        report_finding(
          findings,
          max_findings,
          "empty-urlset",
          Information,
          "urlset",
          "Sitemap URL set contains no locations",
        )
      }
      for url in urls {
        enhanced_location_findings(
          findings,
          canonical_seen,
          url.loc,
          max_findings,
        )
      }
    }
    Index(refs) => {
      if refs.is_empty() {
        report_finding(
          findings,
          max_findings,
          "empty-sitemapindex",
          Information,
          "sitemapindex",
          "Sitemap index contains no locations",
        )
      }
      for reference in refs {
        enhanced_location_findings(
          findings,
          canonical_seen,
          reference.loc,
          max_findings,
        )
      }
    }
  }
  sort_findings(findings)
  findings
}

///|
/// Audit a sitemap and return deterministic findings together with counts.
///
/// In addition to `audit`, this enhanced form detects empty documents,
/// fragments, and duplicate fetch targets after scheme/host/default-port
/// canonicalization. `max_findings` bounds retained report memory.
pub fn audit_report(
  robots : @model.RobotsDocument,
  sitemap : @model.SitemapDocument,
  user_agent : String,
  site_origin : String,
  max_findings? : Int = 100000,
) -> AuditReport raise @model.DiscoveryError {
  let base = audit(robots, sitemap, user_agent, site_origin)
  let findings = append_enhanced_findings(base, sitemap, max_findings)
  { findings, summary: summarize_findings(findings) }
}