// Strict RFC 3986 / RFC 9110 absolute URL and authority parser/validator
// backed by `moonbitstack/moonurl` with explicit overflow-safe port validation,
// IPv6 syntax validation, and backslash/non-ASCII rejection.

///|
fn has_control_or_space(s : String) -> Bool {
  for i in 0.. Bool {
  let len = port.length()
  if len == 0 || len > 5 {
    return false
  }
  let mut val : Int32 = 0
  for i in 0.. 0x39 {
      return false
    }
    val = val * 10 + (c - 0x30)
  }
  val >= 1 && val <= 65535
}

///|
/// Validate an ASCII `reg-name` / hostname (no `[`, `]`, `\`, `@`, `/`, `?`,
/// `#`, whitespace, control chars, or non-ASCII codepoints; callers needing
/// internationalized domains must Punycode-encode them first).
fn is_valid_reg_name(host : String) -> Bool {
  if host.is_empty() {
    return false
  }
  let mut i = 0
  let len = host.length()
  while i < len {
    let c = host.code_unit_at(i).to_int()
    let is_unreserved = (c >= 0x41 && c <= 0x5A) ||
      (c >= 0x61 && c <= 0x7A) ||
      (c >= 0x30 && c <= 0x39) ||
      c == 0x2D ||
      c == 0x2E ||
      c == 0x5F ||
      c == 0x7E
    let is_sub_delim = c == 0x21 ||
      c == 0x24 ||
      c == 0x26 ||
      c == 0x27 ||
      c == 0x28 ||
      c == 0x29 ||
      c == 0x2A ||
      c == 0x2B ||
      c == 0x2C ||
      c == 0x3B ||
      c == 0x3D
    if is_unreserved || is_sub_delim {
      i += 1
    } else if c == 0x25 && i + 2 < len {
      let h1 = host.code_unit_at(i + 1).to_int()
      let h2 = host.code_unit_at(i + 2).to_int()
      if is_ascii_hex(h1) && is_ascii_hex(h2) {
        i += 3
      } else {
        return false
      }
    } else {
      return false
    }
  }
  true
}

///|
fn is_ascii_hex(c : Int32) -> Bool {
  (c >= 0x30 && c <= 0x39) ||
  (c >= 0x41 && c <= 0x46) ||
  (c >= 0x61 && c <= 0x66)
}

///|
/// Validate an IPv6 literal interior (inside `[...]`, e.g. `::1`, `2001:db8::1`,
/// `::ffff:192.0.2.1`): must contain at least one `:`, valid hex/`.` groups,
/// and at most one `::` compression.
fn is_valid_ipv6_interior(inner : String) -> Bool {
  if inner.is_empty() || !inner.contains(":") {
    return false
  }
  // Reject non-hex/colon/dot characters (and reject zone IDs or brackets).
  for i in 0.. return false
  }
  parsed.host is Some(_)
}

///|
/// Validate an HTTP/WS URL authority (`host[:port]` or `[ipv6][:port]`).
/// Rejects empty hosts, unclosed/nested brackets, bogus IPv6 literals,
/// backslashes, non-ASCII hosts, port `0` or `> 65535` (preventing `Int32`
/// wraparound), control characters, and userinfo `@` (unless
/// `allow_userinfo=true`).
pub fn is_valid_authority(
  authority : String,
  allow_userinfo~ : Bool = false,
) -> Bool {
  if authority.is_empty() || has_control_or_space(authority) {
    return false
  }
  if authority.contains("/") ||
    authority.contains("\\") ||
    authority.contains("?") ||
    authority.contains("#") {
    return false
  }
  let hostport = match authority.find("@") {
    Some(at) => {
      if !allow_userinfo {
        return false
      }
      let userinfo = authority[:at].to_owned()
      if userinfo.contains("@") || authority[at + 1:].to_owned().contains("@") {
        return false
      }
      authority[at + 1:].to_owned()
    }
    None => authority
  }
  if hostport.is_empty() {
    return false
  }
  if hostport.has_prefix("[") {
    let close = match hostport.find("]") {
      Some(idx) => idx
      None => return false
    }
    let ipv6 = hostport[1:close].to_owned()
    if !is_valid_ipv6_interior(ipv6) {
      return false
    }
    let rest = hostport[close + 1:].to_owned()
    if rest.is_empty() {
      true
    } else if rest.has_prefix(":") {
      is_valid_port_text(rest[1:].to_owned())
    } else {
      false
    }
  } else {
    if hostport.contains("[") || hostport.contains("]") {
      return false
    }
    match hostport.find(":") {
      Some(colon) => {
        let host = hostport[:colon].to_owned()
        let port = hostport[colon + 1:].to_owned()
        is_valid_reg_name(host) && is_valid_port_text(port)
      }
      None => is_valid_reg_name(hostport)
    }
  }
}

///|
/// Split an absolute `scheme://authority[path][?query][#fragment]` URL with
/// strict authority, port, and character validation.
///
/// Returns `Some((lowercase_scheme, authority, path_with_query, has_fragment))`
/// where:
/// - `authority` has been validated with `is_valid_authority(allow_userinfo=false)`
/// - `path_with_query` has any `#fragment` stripped, defaults to `"/"` if
///   absent, and prefixes `"/"` if only `?query` was present
/// - `has_fragment` is `true` if a `#` delimiter was present.
///
/// Returns `None` if `url` is empty, contains whitespace, control characters,
/// or backslashes, lacks `://`, or has an invalid scheme or authority.
pub fn split_absolute_url(url : String) -> (String, String, String, Bool)? {
  if url.is_empty() || has_control_or_space(url) || url.contains("\\") {
    return None
  }
  let sep = match url.find("://") {
    Some(idx) if idx > 0 => idx
    _ => return None
  }
  let raw_scheme = url[:sep].to_owned()
  // RFC 3986 ยง3.1: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  let first_sc = raw_scheme.code_unit_at(0).to_int()
  if !((first_sc >= 0x41 && first_sc <= 0x5A) ||
    (first_sc >= 0x61 && first_sc <= 0x7A)) {
    return None
  }
  for i in 1..= 0x41 && c <= 0x5A) ||
      (c >= 0x61 && c <= 0x7A) ||
      (c >= 0x30 && c <= 0x39) ||
      c == 0x2B ||
      c == 0x2D ||
      c == 0x2E
    if !ok {
      return None
    }
  }
  let scheme = raw_scheme.to_lower()
  let after_sep = url[sep + 3:].to_owned()
  // Find first delimiter ending authority: `/`, `?`, or `#`
  let mut auth_end = after_sep.length()
  for i in 0.. (tail[:idx].to_owned(), true)
    None => (tail, false)
  }
  let path_with_query = if before_frag.is_empty() {
    "/"
  } else if before_frag.has_prefix("?") {
    "/" + before_frag
  } else {
    before_frag
  }
  Some((scheme, authority, path_with_query, has_fragment))
}