///|
/// Stable category for a non-fatal robots policy inspection finding.
///
/// The parser remains deliberately strict for malformed core records.  These
/// diagnostics additionally make it possible to inspect documents assembled
/// by a caller, migrated from a permissive parser, or edited in memory.
pub(all) enum RobotsDiagnosticCode {
  EmptyUserAgent
  InvalidUserAgent
  DuplicateUserAgent
  GroupWithoutRules
  IgnoredEmptyRule
  DuplicateRule
  ConflictingRule
  InvalidPattern
  UnmatchablePattern
  InvalidSitemapUrl
  DuplicateSitemapUrl
} derive(Debug, Eq)

///|
/// One deterministic, non-fatal policy finding.
///
/// `group_index` and `line` are absent when the source record has no group or
/// source line provenance, such as a retained `Sitemap` extension record.
pub(all) struct RobotsDiagnostic {
  code : RobotsDiagnosticCode
  group_index : Int?
  line : Int?
  subject : String
  message : String
} derive(Debug, Eq)

///|
/// Result of inspecting a parsed or caller-constructed robots policy.
///
/// `sitemap_urls` contains each accepted absolute HTTP(S) Sitemap URL once,
/// in first-seen order. `diagnostics` preserves document order, which makes
/// the result suitable for stable command-line and CI reporting.
pub(all) struct RobotsPolicyInspection {
  diagnostics : Array[RobotsDiagnostic]
  sitemap_urls : Array[String]
  group_count : Int
  rule_count : Int
  actionable_rule_count : Int
} derive(Debug, Eq)

///|
/// Return whether a value is empty after removing robots field whitespace.
fn blank_robots_value(value : String) -> Bool {
  value.trim(chars=" \t\r\n").is_empty()
}

///|
/// Describe an invalid percent escape without raising so inspection can
/// continue and report every independently actionable finding.
fn invalid_percent_reason(value : String) -> String? {
  let chars = value.to_array()
  let mut index = 0
  while index < chars.length() {
    if chars[index] == '%' {
      if index + 2 >= chars.length() ||
        hex_value(chars[index + 1]) is None ||
        hex_value(chars[index + 2]) is None {
        return Some("contains an incomplete or malformed percent escape")
      }
      index += 3
    } else {
      index += 1
    }
  }
  None
}

///|
/// Return the policy reason a pattern is invalid or cannot match an RFC 9309
/// origin-form comparison URI. Empty rules are handled separately because RFC
/// semantics intentionally ignore them instead of treating them as an error.
fn pattern_problem(pattern : String) -> (RobotsDiagnosticCode, String)? {
  if has_forbidden_control(pattern) {
    return Some(
      (InvalidPattern, "pattern contains a control character or whitespace"),
    )
  }
  match invalid_percent_reason(pattern) {
    Some(reason) => return Some((InvalidPattern, reason))
    None => ()
  }
  if pattern == "$" {
    return Some((UnmatchablePattern, "end anchor has no path expression"))
  }
  // `decide` always compares an origin-form URI beginning with `/`.  A rule
  // without a leading wildcard or slash cannot match such a value, even
  // though strict parsing is allowed to preserve it for caller visibility.
  if !pattern.has_prefix("/") && !pattern.has_prefix("*") {
    return Some(
      (
        UnmatchablePattern,
        "pattern cannot match an origin-form URI beginning with '/'",
      ),
    )
  }
  None
}

///|
/// Build a key where rule polarity is part of the identity. The key stays
/// internal; the original rule pattern is always used in user-facing output.
fn exact_rule_key(rule : @model.RobotsRule) -> String {
  (if rule.allow { "allow:" } else { "disallow:" }) + rule.pattern
}

///|
/// Validate only the retrieval-relevant part of a Sitemap extension URL.
///
/// It intentionally accepts IDNs, IPv6 literals, user-info, paths, queries,
/// and ports while rejecting relative references, fragments, controls, and
/// malformed percent escapes. Network fetching is explicitly out of scope.
fn is_absolute_http_sitemap_url(value : String) -> Bool {
  if blank_robots_value(value) || has_forbidden_control(value) {
    return false
  }
  if invalid_percent_reason(value) is Some(_) || value.find("#") is Some(_) {
    return false
  }
  match value.find("://") {
    None => false
    Some(scheme_end) => {
      let scheme = value[:scheme_end].to_owned().to_lower()
      if scheme != "http" && scheme != "https" {
        return false
      }
      let after_scheme = value[scheme_end + 3:].to_owned()
      let mut authority_end = after_scheme.length()
      for index, character in after_scheme {
        if character == '/' || character == '?' {
          authority_end = index
          break
        }
      }
      let authority = after_scheme[:authority_end].to_owned()
      if authority.is_empty() {
        return false
      }
      let host = match authority.rev_find("@") {
        Some(offset) => authority[offset + 1:].to_owned()
        None => authority
      }
      if host.is_empty() || host.has_prefix(":") {
        return false
      }
      if host.has_prefix("[") && !host.contains("]") {
        return false
      }
      true
    }
  }
}

///|
/// Collect all candidate Sitemap extension values, including values retained
/// only in `other_records` by a caller-built `RobotsDocument`.
fn sitemap_candidates(document : @model.RobotsDocument) -> Array[String] {
  let candidates : Array[String] = []
  for value in document.sitemap_locations {
    candidates.push(value)
  }
  for record in document.other_records {
    let (key, value) = record
    let normalized_key = key.trim(chars=" \t\r\n").to_lower()
    if normalized_key == "sitemap" || normalized_key == "sitemaps" {
      candidates.push(value)
    }
  }
  candidates
}

///|
/// Extract valid absolute HTTP(S) Sitemap URLs from core locations and retained
/// extension records. Invalid and duplicate values are omitted; accepted URLs
/// retain their first-seen spelling and order.
///
/// # Example
/// ```mbt check
/// test {
///   let document = parse("Sitemap: https://example.test/map.xml\n")
///   assert_eq(extract_sitemap_urls(document), ["https://example.test/map.xml"])
/// }
/// ```
pub fn extract_sitemap_urls(document : @model.RobotsDocument) -> Array[String] {
  let urls : Array[String] = []
  let seen : Map[String, Unit] = Map([])
  for candidate in sitemap_candidates(document) {
    let normalized = candidate.trim(chars=" \t\r\n").to_owned()
    if is_absolute_http_sitemap_url(normalized) && !seen.contains(normalized) {
      seen[normalized] = ()
      urls.push(normalized)
    }
  }
  urls
}

///|
/// Add diagnostics for retained Sitemap extension records. Parser-produced
/// records preserve one entry per source line, so duplicate warnings describe
/// duplicate source directives instead of duplicated storage representations.
fn inspect_sitemap_records(
  document : @model.RobotsDocument,
  diagnostics : Array[RobotsDiagnostic],
) -> Unit {
  let seen : Map[String, Unit] = Map([])
  for record in document.other_records {
    let (key, raw_value) = record
    let normalized_key = key.trim(chars=" \t\r\n").to_lower()
    if normalized_key != "sitemap" && normalized_key != "sitemaps" {
      continue
    }
    let value = raw_value.trim(chars=" \t\r\n").to_owned()
    if !is_absolute_http_sitemap_url(value) {
      diagnostics.push({
        code: InvalidSitemapUrl,
        group_index: None,
        line: None,
        subject: raw_value,
        message: "Sitemap extension value is not an absolute HTTP(S) retrieval URL",
      })
    } else if seen.contains(value) {
      diagnostics.push({
        code: DuplicateSitemapUrl,
        group_index: None,
        line: None,
        subject: value,
        message: "Sitemap extension URL repeats an earlier source directive",
      })
    } else {
      seen[value] = ()
    }
  }
}

///|
/// Inspect a robots policy without changing RFC decision behavior.
///
/// Empty `Allow` and `Disallow` patterns are reported as ignored because the
/// matcher deliberately gives them no effect. Duplicate and contradictory
/// rules are reported within each group; this mirrors the scope where their
/// precedence is directly comparable. The function never fetches a URL and
/// never raises for policy quality issues.
///
/// # Example
/// ```mbt check
/// test {
///   let document = parse("User-agent: bot\nDisallow: \n")
///   let inspection = inspect_policy(document)
///   assert_eq(inspection.actionable_rule_count, 0)
///   assert_eq(inspection.diagnostics[0].code, IgnoredEmptyRule)
/// }
/// ```
pub fn inspect_policy(
  document : @model.RobotsDocument,
) -> RobotsPolicyInspection {
  let diagnostics : Array[RobotsDiagnostic] = []
  let mut rule_count = 0
  let mut actionable_rule_count = 0
  for group_index, group in document.groups {
    if group.user_agents.is_empty() {
      diagnostics.push({
        code: EmptyUserAgent,
        group_index: Some(group_index),
        line: None,
        subject: "group",
        message: "group has no User-agent value and cannot be selected",
      })
    }
    let seen_agents : Map[String, Unit] = Map([])
    for raw_agent in group.user_agents {
      let agent = raw_agent.trim(chars=" \t\r\n").to_owned()
      if agent.is_empty() {
        diagnostics.push({
          code: EmptyUserAgent,
          group_index: Some(group_index),
          line: None,
          subject: raw_agent,
          message: "empty User-agent does not select a crawler",
        })
      } else if !is_product_token(agent) {
        diagnostics.push({
          code: InvalidUserAgent,
          group_index: Some(group_index),
          line: None,
          subject: raw_agent,
          message: "User-agent is not an RFC 9309 product token or '*'",
        })
      } else if seen_agents.contains(agent.to_lower()) {
        diagnostics.push({
          code: DuplicateUserAgent,
          group_index: Some(group_index),
          line: None,
          subject: raw_agent,
          message: "User-agent repeats an earlier value in the same group",
        })
      } else {
        seen_agents[agent.to_lower()] = ()
      }
    }
    if group.rules.is_empty() {
      diagnostics.push({
        code: GroupWithoutRules,
        group_index: Some(group_index),
        line: None,
        subject: "group",
        message: "group has User-agent records but no Allow or Disallow rules",
      })
    }
    let exact_rules : Map[String, Unit] = Map([])
    let rule_effects : Map[String, Bool] = Map([])
    for rule in group.rules {
      rule_count += 1
      let directive = if rule.allow { "Allow" } else { "Disallow" }
      let subject = "{directive}: {rule.pattern}"
      let exact_key = exact_rule_key(rule)
      if exact_rules.contains(exact_key) {
        diagnostics.push({
          code: DuplicateRule,
          group_index: Some(group_index),
          line: Some(rule.line),
          subject,
          message: "rule exactly repeats an earlier rule in the same group",
        })
      } else {
        exact_rules[exact_key] = ()
      }
      match rule_effects.get(rule.pattern) {
        Some(previous_allow) if previous_allow != rule.allow =>
          diagnostics.push({
            code: ConflictingRule,
            group_index: Some(group_index),
            line: Some(rule.line),
            subject,
            message: "Allow and Disallow use the same pattern; Allow wins an equal-specificity tie",
          })
        Some(_) => ()
        None => rule_effects[rule.pattern] = rule.allow
      }
      if blank_robots_value(rule.pattern) {
        diagnostics.push({
          code: IgnoredEmptyRule,
          group_index: Some(group_index),
          line: Some(rule.line),
          subject: directive,
          message: "empty rule has no matching effect under RFC 9309 semantics",
        })
      } else {
        match pattern_problem(rule.pattern) {
          Some((code, message)) =>
            diagnostics.push({
              code,
              group_index: Some(group_index),
              line: Some(rule.line),
              subject,
              message,
            })
          None => actionable_rule_count += 1
        }
      }
    }
  }
  inspect_sitemap_records(document, diagnostics)
  {
    diagnostics,
    sitemap_urls: extract_sitemap_urls(document),
    group_count: document.groups.length(),
    rule_count,
    actionable_rule_count,
  }
}