///|
/// RFC 9309 requires parsers to process at least 500 KiB.  One MiB leaves
/// headroom while making the in-memory parser's resource boundary explicit.
let maximum_robots_input_bytes : Int = 1024 * 1024

///|
/// A line may be as large as RFC 9309's mandatory 500 KiB parsing floor, but
/// cannot exceed it independently of the bounded complete input.
let maximum_robots_line_bytes : Int = 500 * 1024

///|
let maximum_robots_groups : Int = 4096

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

///|
fn field(line : String) -> (String, String)? {
  match line.find(":") {
    None => None
    Some(offset) => {
      let key = line[:offset].trim(chars=" \t").to_owned().to_lower()
      let value = line[offset + 1:].trim(chars=" \t").to_owned()
      if key.is_empty() {
        None
      } else {
        Some((key, value))
      }
    }
  }
}

///|
fn is_product_token(value : String) -> Bool {
  if value == "*" {
    return true
  }
  if value.is_empty() {
    return false
  }
  for c in value {
    if !(c.is_ascii_alphabetic() || c == '_' || c == '-') {
      return false
    }
  }
  true
}

///|
fn has_forbidden_control(value : String) -> Bool {
  for c in value {
    let code = c.to_int()
    if code <= 0x20 || code == 0x7f {
      return true
    }
  }
  false
}

///|
fn validate_percent_escapes(
  value : String,
  line : Int,
) -> Unit raise @model.DiscoveryError {
  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 {
        raise InvalidRobots(
          line~,
          reason="invalid percent escape in Allow/Disallow pattern",
        )
      }
      index += 3
    } else {
      index += 1
    }
  }
}

///|
fn validate_rule_pattern(
  value : String,
  line : Int,
) -> Unit raise @model.DiscoveryError {
  if has_forbidden_control(value) {
    raise InvalidRobots(
      line~,
      reason="Allow/Disallow pattern contains a control character",
    )
  }
  validate_percent_escapes(value, line)
}

///|
fn append_group(
  groups : Array[@model.RobotsGroup],
  agents : Array[String],
  rules : Array[@model.RobotsRule],
) -> Unit raise @model.DiscoveryError {
  if !agents.is_empty() {
    if groups.length() >= maximum_robots_groups {
      raise LimitExceeded(kind="robots groups", limit=maximum_robots_groups)
    }
    groups.push({ user_agents: agents, rules })
  }
}

///|
fn normalize_newlines(text : String) -> String {
  text.replace_all(old="\r\n", new="\n").replace_all(old="\r", new="\n")
}

///|
fn parse_text(
  text : String,
) -> @model.RobotsDocument raise @model.DiscoveryError {
  let groups : Array[@model.RobotsGroup] = []
  let sitemaps : Array[String] = []
  let others : Array[(String, String)] = []
  let mut agents : Array[String] = []
  let mut rules : Array[@model.RobotsRule] = []
  let mut saw_rule = false
  let mut line_no = 0
  for raw in normalize_newlines(text).split("\n") {
    line_no += 1
    if @utf8.encode(raw).length() > maximum_robots_line_bytes {
      raise LimitExceeded(
        kind="robots line bytes",
        limit=maximum_robots_line_bytes,
      )
    }
    let line = without_comment(raw).trim(chars=" \t").to_owned()
    if line.is_empty() {
      continue
    }
    match field(line) {
      None =>
        raise InvalidRobots(
          line=line_no,
          reason="expected a field followed by ':'",
        )
      Some((key, value)) =>
        match key {
          "user-agent" => {
            if !is_product_token(value) {
              raise InvalidRobots(
                line=line_no,
                reason="User-agent must be an RFC 9309 product token or '*'",
              )
            }
            if saw_rule {
              append_group(groups, agents, rules)
              agents = []
              rules = []
              saw_rule = false
            }
            agents.push(value.to_lower())
          }
          "allow" | "disallow" =>
            // RFC 9309 asks crawlers to ignore rules outside a group while
            // continuing to parse later, valid groups.
            if !agents.is_empty() {
              validate_rule_pattern(value, line_no)
              rules.push({
                allow: key == "allow",
                pattern: value,
                line: line_no,
              })
              saw_rule = true
            }
          "sitemap" | "sitemaps" => {
            if !value.is_empty() {
              sitemaps.push(value)
            }
            others.push((key, value))
          }
          _ => others.push((key, value))
        }
    }
  }
  append_group(groups, agents, rules)
  { groups, sitemap_locations: sitemaps, other_records: others }
}

///|
/// Decode and parse a UTF-8 robots file.  This entry point lets callers keep
/// malformed byte input outside the normal `String` API and receive a checked
/// `InvalidUtf8` error instead of a panic.
pub fn parse_bytes(
  input : Bytes,
) -> @model.RobotsDocument raise @model.DiscoveryError {
  if input.length() > maximum_robots_input_bytes {
    raise LimitExceeded(
      kind="robots input bytes",
      limit=maximum_robots_input_bytes,
    )
  }
  let text = @utf8.decode(input, ignore_bom=true) catch {
    _ => raise InvalidUtf8(component="robots.txt")
  }
  parse_text(text)
}

///|
/// Parse RFC 9309 groups/rules and retain records outside the core grammar.
/// `String` inputs are encoded as UTF-8 before the same byte, line, and group
/// limits used by `parse_bytes` are applied.
pub fn parse(
  text : String,
) -> @model.RobotsDocument raise @model.DiscoveryError {
  parse_bytes(@utf8.encode(text))
}