///|
fn hex_value(c : Char) -> Int? {
  if c >= '0' && c <= '9' {
    Some(c.to_int() - '0'.to_int())
  } else if c >= 'a' && c <= 'f' {
    Some(c.to_int() - 'a'.to_int() + 10)
  } else if c >= 'A' && c <= 'F' {
    Some(c.to_int() - 'A'.to_int() + 10)
  } else {
    None
  }
}

///|
fn hex_digit(value : Int) -> Char {
  match value {
    0 => '0'
    1 => '1'
    2 => '2'
    3 => '3'
    4 => '4'
    5 => '5'
    6 => '6'
    7 => '7'
    8 => '8'
    9 => '9'
    10 => 'A'
    11 => 'B'
    12 => 'C'
    13 => 'D'
    14 => 'E'
    _ => 'F'
  }
}

///|
fn is_unreserved(c : Char) -> Bool {
  c.is_ascii_alphabetic() ||
  c.is_ascii_digit() ||
  c == '-' ||
  c == '.' ||
  c == '_' ||
  c == '~'
}

///|
fn is_uri_ascii(c : Char) -> Bool {
  is_unreserved(c) ||
  c == ':' ||
  c == '/' ||
  c == '?' ||
  c == '[' ||
  c == ']' ||
  c == '@' ||
  c == '!' ||
  c == '&' ||
  c == '\'' ||
  c == '(' ||
  c == ')' ||
  c == '+' ||
  c == ',' ||
  c == ';' ||
  c == '='
}

///|
fn append_percent_octet(out : StringBuilder, value : Int) -> Unit {
  out.write_char('%')
  out.write_char(hex_digit(value / 16))
  out.write_char(hex_digit(value % 16))
}

///|
fn append_raw_char(out : StringBuilder, c : Char) -> Unit {
  if c.is_ascii() && is_uri_ascii(c) {
    out.write_char(c)
  } else {
    for byte in @utf8.encode("\{c}") {
      append_percent_octet(out, byte.to_int())
    }
  }
}

///|
fn normalize_escaped(
  value : String,
  decode_unreserved : Bool,
  preserve_pattern_tokens : Bool,
) -> String raise @model.DiscoveryError {
  let chars = value.to_array()
  let out = StringBuilder()
  let mut index = 0
  while index < chars.length() {
    let c = chars[index]
    if preserve_pattern_tokens &&
      (c == '*' || (c == '$' && index + 1 == chars.length())) {
      out.write_char(c)
      index += 1
    } else if c == '%' {
      if index + 2 >= chars.length() {
        raise InvalidUri(uri=value, reason="incomplete percent escape")
      }
      match (hex_value(chars[index + 1]), hex_value(chars[index + 2])) {
        (Some(high), Some(low)) => {
          let octet = high * 16 + low
          match octet.to_char() {
            Some(decoded) if decode_unreserved &&
              octet < 128 &&
              is_unreserved(decoded) => out.write_char(decoded)
            _ => append_percent_octet(out, octet)
          }
          index += 3
        }
        _ => raise InvalidUri(uri=value, reason="invalid percent escape")
      }
    } else {
      let code = c.to_int()
      if code < 0x21 || code == 0x7f {
        raise InvalidUri(
          uri=value,
          reason="URI contains a control character or space",
        )
      }
      append_raw_char(out, c)
      index += 1
    }
  }
  out.to_string()
}

///|
fn strip_fragment(uri : String) -> String {
  match uri.find("#") {
    Some(offset) => uri[:offset].to_owned()
    None => uri
  }
}

///|
fn is_scheme(value : StringView) -> Bool {
  if value.is_empty() {
    return false
  }
  let chars = value.to_owned().to_array()
  if !chars[0].is_ascii_alphabetic() {
    return false
  }
  for index, c in chars {
    if index > 0 &&
      !(c.is_ascii_alphabetic() ||
      c.is_ascii_digit() ||
      c == '+' ||
      c == '-' ||
      c == '.') {
      return false
    }
  }
  true
}

///|
fn first_path_or_query(value : String) -> Int? {
  match (value.find("/"), value.find("?")) {
    (None, None) => None
    (Some(offset), None) | (None, Some(offset)) => Some(offset)
    (Some(left), Some(right)) => Some(if left < right { left } else { right })
  }
}

///|
fn match_path(uri : String) -> String raise @model.DiscoveryError {
  let without_fragment = strip_fragment(uri)
  if without_fragment.has_prefix("/") {
    return without_fragment
  }
  match without_fragment.find("://") {
    Some(scheme_end) if is_scheme(without_fragment[:scheme_end]) => {
      let authority_and_path = without_fragment[scheme_end + 3:].to_owned()
      match first_path_or_query(authority_and_path) {
        None => {
          if authority_and_path.is_empty() {
            raise InvalidUri(uri~, reason="absolute URI has no authority")
          }
          "/"
        }
        Some(offset) => {
          if offset == 0 {
            raise InvalidUri(uri~, reason="absolute URI has no authority")
          }
          if authority_and_path[offset] == '?' {
            "/" + authority_and_path[offset:].to_owned()
          } else {
            authority_and_path[offset:].to_owned()
          }
        }
      }
    }
    _ =>
      raise InvalidUri(uri~, reason="expected an absolute or origin-form URI")
  }
}

///|
/// Normalize an origin-form or absolute URI into RFC 9309 comparison octets.
/// Raw non-ASCII bytes and literal `*`/`$` are percent encoded; percent-encoded
/// unreserved ASCII octets are decoded before matching as the RFC requires.
pub fn normalize_uri_for_match(
  uri : String,
) -> String raise @model.DiscoveryError {
  let path = match_path(uri)
  if path.is_empty() || !path.has_prefix("/") {
    raise InvalidUri(uri~, reason="expected an absolute or origin-form URI")
  }
  normalize_escaped(path, true, false)
}

///|
fn normalize_rule_pattern(
  pattern : String,
) -> String raise @model.DiscoveryError {
  normalize_escaped(pattern, false, true)
}

///|
fn literal_matches_at(
  text : Array[Char],
  start : Int,
  literal : Array[Char],
) -> Bool {
  if start < 0 || start + literal.length() > text.length() {
    return false
  }
  for offset in 0.. Array[Int] {
  let failure = Array::make(pattern.length(), 0)
  let mut matched = 0
  for index in 1.. 0 && pattern[index] != pattern[matched] {
      matched = failure[matched - 1]
    }
    if pattern[index] == pattern[matched] {
      matched += 1
    }
    failure[index] = matched
  }
  failure
}

///|
/// Find one literal inside a bounded interval in linear time.  Wildcard
/// matching advances through disjoint intervals, so the whole rule match is
/// linear in the URI and rule sizes instead of repeatedly restarting a glob.
fn find_literal(
  text : Array[Char],
  start : Int,
  limit : Int,
  literal : Array[Char],
) -> Int? {
  if literal.is_empty() {
    return Some(start)
  }
  let failure = kmp_failure(literal)
  let mut matched = 0
  for index in start.. 0 && text[index] != literal[matched] {
      matched = failure[matched - 1]
    }
    if text[index] == literal[matched] {
      matched += 1
    }
    if matched == literal.length() {
      return Some(index + 1)
    }
  }
  None
}

///|
fn wildcard_chunks(raw : String) -> Array[String] {
  let result : Array[String] = []
  let chars = raw.to_array()
  let mut start = 0
  for index, c in chars {
    if c == '*' {
      if start < index {
        result.push(raw[start:index].to_owned())
      }
      start = index + 1
    }
  }
  if start < chars.length() {
    result.push(raw[start:].to_owned())
  }
  result
}

///|
fn rule_matches(pattern : String, uri : String) -> Bool {
  if pattern.is_empty() {
    return false
  }
  let anchored = pattern.has_suffix("$")
  let raw = if anchored {
    pattern[:pattern.length() - 1].to_owned()
  } else {
    pattern
  }
  if raw.is_empty() {
    return false
  }
  if !raw.contains("*") {
    return if anchored { raw == uri } else { uri.has_prefix(raw) }
  }
  let chunks = wildcard_chunks(raw)
  if chunks.is_empty() {
    return true
  }
  let text = uri.to_array()
  let leading_star = raw.has_prefix("*")
  let trailing_star = raw.has_suffix("*") || !anchored
  let mut position = 0
  let mut first_chunk = 0
  let mut end_chunk = chunks.length()
  let mut limit = text.length()
  if !trailing_star {
    let suffix = chunks[chunks.length() - 1].to_array()
    if suffix.length() > text.length() {
      return false
    }
    limit = text.length() - suffix.length()
    if !literal_matches_at(text, limit, suffix) {
      return false
    }
    end_chunk -= 1
  }
  if !leading_star {
    let prefix = chunks[0].to_array()
    if !literal_matches_at(text, 0, prefix) {
      return false
    }
    position = prefix.length()
    first_chunk = 1
  }
  if position > limit {
    return false
  }
  for chunk_index in first_chunk.. position = end
      None => return false
    }
  }
  true
}

///|
fn specificity(pattern : String) -> Int {
  let chars = pattern.to_array()
  let anchored = pattern.has_suffix("$")
  let mut index = 0
  let mut result = 0
  while index < chars.length() {
    if chars[index] == '*' || (anchored && index + 1 == chars.length()) {
      index += 1
    } else if chars[index] == '%' &&
      index + 2 < chars.length() &&
      hex_value(chars[index + 1]) is Some(_) &&
      hex_value(chars[index + 2]) is Some(_) {
      result += 1
      index += 3
    } else {
      result += 1
      index += 1
    }
  }
  result
}

///|
fn matching_agents(
  document : @model.RobotsDocument,
  user_agent : String,
) -> (Array[Int], String?) {
  let needle = user_agent.to_lower()
  let result : Array[Int] = []
  let mut best = -1
  let mut selected : String? = None
  for group_index, group in document.groups {
    let mut group_best = -1
    let mut group_agent : String? = None
    for agent in group.user_agents {
      if agent == "*" || needle.contains(agent) {
        let score = if agent == "*" { 0 } else { agent.length() }
        if score > group_best {
          group_best = score
          group_agent = Some(agent)
        }
      }
    }
    if group_best > best {
      result.clear()
      result.push(group_index)
      best = group_best
      selected = group_agent
    } else if group_best == best && group_best >= 0 {
      result.push(group_index)
    }
  }
  (result, selected)
}

///|
/// Evaluate a URI for a crawler product token. Matching groups with the most
/// specific product token are merged. Among equally specific matching rules,
/// Allow deliberately wins over Disallow as required by RFC 9309.
pub fn decide(
  document : @model.RobotsDocument,
  user_agent : String,
  uri : String,
) -> @model.RobotsDecision raise @model.DiscoveryError {
  let normalized = normalize_uri_for_match(uri)
  let (groups, agent) = matching_agents(document, user_agent)
  if normalized == "/robots.txt" {
    return { allowed: true, matched_rule: None, matched_user_agent: agent }
  }
  let mut winning : @model.RobotsRule? = None
  let mut winning_score = -1
  for group_index in groups {
    let group = document.groups[group_index]
    for rule in group.rules {
      let normalized_rule = normalize_rule_pattern(rule.pattern)
      if rule_matches(normalized_rule, normalized) {
        let score = specificity(normalized_rule)
        let replace = score > winning_score ||
          (score == winning_score && rule.allow)
        if replace {
          winning = Some(rule)
          winning_score = score
        }
      }
    }
  }
  match winning {
    Some(rule) =>
      {
        allowed: rule.allow,
        matched_rule: Some(rule),
        matched_user_agent: agent,
      }
    None => { allowed: true, matched_rule: None, matched_user_agent: agent }
  }
}