///|
/// The value of `x:Uri`: the original text, accepted as .NET `new Uri(text,
/// UriKind.RelativeOrAbsolute)` accepts it (design D12, Owner 2F-OD3).
///
/// The acceptance rules are a port of the parts of .NET's `System.Uri` constructor that decide
/// whether text is an absolute URI, a relative URI or an error, as .NET 10 does on Windows. The text
/// is kept unchanged, so saving writes it back as it was read. Two values are equal when their texts
/// are equal.
pub struct XamlUri {
  priv text : String
  priv absolute : Bool
}

///|
/// The text as it was given.
pub fn XamlUri::text(self : XamlUri) -> String {
  self.text
}

///|
/// Whether .NET reads the text as an absolute URI rather than a relative one.
pub fn XamlUri::is_absolute(self : XamlUri) -> Bool {
  self.absolute
}

///|
pub impl Eq for XamlUri with fn equal(self, other) {
  self.text == other.text
}

///|
pub impl Hash for XamlUri with fn hash_combine(self, hasher) {
  hasher.combine_string(self.text)
}

///|
pub impl Show for XamlUri with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend XamlUri with Show::{to_string}

///|
pub impl Debug for XamlUri with fn to_repr(self) {
  @debug.Repr::literal("XamlUri(\{@debug.to_string(self.text)})")
}

///|
/// Accept `text` as `x:Uri` does, or raise `ValueError` naming `x:Uri`, the text and the reason
/// .NET gives.
pub fn XamlUri::parse(text : String) -> XamlUri raise ValueError {
  match classify_uri(text) {
    Ok(absolute) => { text, absolute, }
    Err(reason) =>
      raise ValueError("\"\{text}\" is not an x:Uri: Invalid URI: \{reason}")
  }
}

///|
/// The parsing errors of .NET's `Uri`, in its order: the first four leave the text a relative URI.
priv enum UriError {
  BadFormat
  BadScheme
  BadAuthority
  SchemeLimit
  MustRootedPath
  BadHostName
  BadPort
  BadAuthorityTerminator
}

///|
fn UriError::relative_ok(self : UriError) -> Bool {
  self is (BadFormat | BadScheme | BadAuthority)
}

///|
fn UriError::reason(self : UriError) -> String {
  match self {
    BadFormat => "The format of the URI could not be determined."
    BadScheme => "The URI scheme is not valid."
    BadAuthority => "The Authority/Host could not be parsed."
    SchemeLimit => "The Uri scheme is too long."
    MustRootedPath => "A Dos path must be rooted, for example, 'c:\\'."
    BadHostName => "The hostname could not be parsed."
    BadPort => "Invalid port specified."
    BadAuthorityTerminator =>
      "The Authority/Host cannot end with a backslash character ('\\')."
  }
}

///|
/// The syntax flags of a .NET URI parser (`UriSyntaxFlags`) that acceptance depends on.
priv struct UriSyntax {
  must_have_authority : Bool
  optional_authority : Bool
  may_have_user_info : Bool
  may_have_port : Bool
  allow_empty_host : Bool
  allow_dos_path : Bool
  file_like : Bool
  mail_to_like : Bool
  allow_ipv6 : Bool
  allow_dns : Bool
  allow_unc : Bool
  v1_unknown : Bool
  is_file : Bool
}

///|
/// A syntax with every flag off except those given.
fn uri_syntax(
  must_have_authority~ : Bool = false,
  optional_authority~ : Bool = false,
  may_have_user_info~ : Bool = false,
  may_have_port~ : Bool = false,
  allow_empty_host~ : Bool = false,
  allow_dos_path~ : Bool = false,
  file_like~ : Bool = false,
  mail_to_like~ : Bool = false,
  internet_host~ : Bool = false,
  allow_unc~ : Bool = false,
  v1_unknown~ : Bool = false,
  is_file~ : Bool = false,
) -> UriSyntax {
  {
    must_have_authority,
    optional_authority,
    may_have_user_info,
    may_have_port,
    allow_empty_host,
    allow_dos_path,
    file_like,
    mail_to_like,
    allow_ipv6: internet_host,
    allow_dns: internet_host,
    allow_unc,
    v1_unknown,
    is_file,
  }
}

///|
/// The parser of a scheme, by lowercase name, as .NET's `UriParser` registers the built-in schemes;
/// any other scheme gets the syntax of an unknown scheme.
fn scheme_syntax(scheme : String) -> UriSyntax {
  match scheme {
    "http" | "https" | "ws" | "wss" | "ftp" | "gopher" | "nntp" | "telnet" =>
      uri_syntax(
        must_have_authority=true,
        may_have_user_info=true,
        may_have_port=true,
        internet_host=true,
        allow_unc=true,
      )
    "file" =>
      uri_syntax(
        must_have_authority=true,
        allow_empty_host=true,
        allow_dos_path=true,
        file_like=true,
        internet_host=true,
        allow_unc=true,
        is_file=true,
      )
    "vsmacros" =>
      uri_syntax(
        must_have_authority=true,
        allow_empty_host=true,
        allow_dos_path=true,
        file_like=true,
        internet_host=true,
        allow_unc=true,
      )
    "ldap" =>
      uri_syntax(
        must_have_authority=true,
        allow_empty_host=true,
        may_have_user_info=true,
        may_have_port=true,
        internet_host=true,
        allow_unc=true,
      )
    "mailto" =>
      uri_syntax(
        allow_empty_host=true,
        may_have_user_info=true,
        may_have_port=true,
        mail_to_like=true,
        internet_host=true,
        allow_unc=true,
      )
    "news" | "uuid" => uri_syntax()
    "net.tcp" =>
      uri_syntax(
        must_have_authority=true,
        may_have_port=true,
        internet_host=true,
      )
    "net.pipe" => uri_syntax(must_have_authority=true, internet_host=true)
    _ =>
      uri_syntax(
        v1_unknown=true,
        optional_authority=true,
        may_have_user_info=true,
        may_have_port=true,
        allow_empty_host=true,
        allow_dos_path=true,
        internet_host=true,
        allow_unc=true,
      )
  }
}

///|
/// .NET `UriHelper.IsLWS`.
fn is_lws(unit : UInt16) -> Bool {
  unit is (' ' | '\t' | '\r' | '\n')
}

///|
fn is_slash(unit : UInt16) -> Bool {
  unit is ('/' | '\\')
}

///|
fn is_ascii_letter(unit : UInt16) -> Bool {
  (unit >= 'a' && unit <= 'z') || (unit >= 'A' && unit <= 'Z')
}

///|
fn is_ascii_digit(unit : UInt16) -> Bool {
  unit >= '0' && unit <= '9'
}

///|
fn is_ascii_hex_digit(unit : UInt16) -> Bool {
  is_ascii_digit(unit) ||
  (unit >= 'a' && unit <= 'f') ||
  (unit >= 'A' && unit <= 'F')
}

///|
/// Whether `text` is an absolute URI (`true`) or a relative one (`false`), or the reason .NET
/// rejects it.
fn classify_uri(text : String) -> Result[Bool, String] {
  let length = text.length()
  if length == 0 {
    return Ok(false)
  }
  // `ParseSchemeCheckImplicitFile`.
  let mut idx = 0
  while idx < length && is_lws(text.at(idx)) {
    idx += 1
  }
  let mut end = idx
  while end < length && text.at(end) != ':' {
    end += 1
  }
  let relative_or = (error : UriError) => {
    if error.relative_ok() {
      Ok(false)
    } else {
      Err(error.reason())
    }
  }
  if idx + 2 >= length || end == idx {
    return relative_or(BadFormat)
  }
  let second = text.at(idx + 1)
  if second == ':' || second == '|' {
    if is_ascii_letter(text.at(idx)) {
      // A DOS path such as `c:\path` is an implicit file URI.
      return if is_slash(text.at(idx + 2)) {
        Ok(true)
      } else {
        relative_or(MustRootedPath)
      }
    }
    return relative_or(if second == ':' { BadScheme } else { BadFormat })
  }
  if is_slash(text.at(idx)) {
    if !is_slash(second) {
      return relative_or(BadFormat)
    }
    // A UNC path. Only one that starts the text with `\\` is absolute.
    if text.at(0) != '\\' || text.at(1) != '\\' {
      return Ok(false)
    }
    idx += 2
    while idx < length && is_slash(text.at(idx)) {
      idx += 1
    }
    return match parse_unc_path(text, idx) {
      None => Ok(true)
      Some(error) => relative_or(error)
    }
  }
  if end == length {
    return relative_or(BadFormat)
  }
  // `CheckSchemeSyntax`.
  if !is_ascii_letter(text.at(idx)) {
    return relative_or(BadScheme)
  }
  if end - idx > 1024 {
    return relative_or(SchemeLimit)
  }
  let scheme = StringBuilder()
  for i in idx..= 'A' && unit <= 'Z' { unit + 32 } else { unit }
    scheme.write_char(lower.to_int().unsafe_to_char())
  }
  match parse_minimal(text, end + 1, scheme_syntax(scheme.to_string())) {
    None => Ok(true)
    Some(error) => relative_or(error)
  }
}

///|
/// `PrivateParseMinimal` for an implicit UNC file path whose host starts at `idx`.
fn parse_unc_path(text : String, idx : Int32) -> UriError? {
  let length = trimmed_length(text, idx)
  let (_, error) = check_authority(
    text,
    idx,
    length,
    scheme_syntax("file"),
    implicit_file=true,
  )
  error
}

///|
/// The length of `text` without trailing white space after `idx`.
fn trimmed_length(text : String, idx : Int32) -> Int32 {
  let mut length = text.length()
  while length > idx && is_lws(text.at(length - 1)) {
    length -= 1
  }
  length
}

///|
/// `PrivateParseMinimal` for an explicit scheme: the text after the scheme starts at `start`.
fn parse_minimal(text : String, start : Int32, syntax : UriSyntax) -> UriError? {
  let mut idx = start
  let length = trimmed_length(text, idx)
  let mut authority_found = false
  let mut dos_path = false
  let mut unc_path = false
  if syntax.allow_empty_host && syntax.allow_dos_path && idx + 1 < length {
    let mut i = idx
    while i < length && is_slash(text.at(i)) {
      i += 1
    }
    if syntax.file_like || i - idx <= 3 {
      if i - idx >= 2 {
        authority_found = true
      }
      if i + 1 < length &&
        text.at(i + 1) is (':' | '|') &&
        is_ascii_letter(text.at(i)) {
        if i + 2 >= length || !is_slash(text.at(i + 2)) {
          if syntax.file_like {
            return Some(MustRootedPath)
          }
        } else {
          dos_path = true
        }
      } else if syntax.file_like &&
        i - idx >= 2 &&
        i - idx != 3 &&
        i < length &&
        !(text.at(i) is ('?' | '#')) {
        unc_path = true
        idx = i
      }
    }
  }
  if !dos_path && !unc_path {
    if idx + 2 <= length {
      let first = text.at(idx)
      let second = text.at(idx + 1)
      if syntax.must_have_authority {
        if is_slash(first) && is_slash(second) {
          idx += 2
        } else {
          return Some(BadAuthority)
        }
      } else if syntax.optional_authority &&
        (authority_found || (first == '/' && second == '/')) {
        idx += 2
      } else if !syntax.mail_to_like {
        return None
      }
    } else if syntax.must_have_authority {
      return Some(BadAuthority)
    } else if !syntax.mail_to_like {
      return None
    }
  }
  if dos_path {
    return None
  }
  let (host_end, error) = check_authority(
    text,
    idx,
    length,
    syntax,
    implicit_file=false,
  )
  if error is Some(_) {
    return error
  }
  if host_end < length && text.at(host_end) == '\\' && !syntax.allow_dos_path {
    return Some(BadAuthorityTerminator)
  }
  None
}

///|
priv enum HostType {
  NotParsed
  Parsed
}

///|
/// `CheckAuthorityHelper`: check the user information, host and port that start at `idx`. It
/// returns where the host ends and the error, if any.
fn check_authority(
  text : String,
  idx : Int32,
  length : Int32,
  syntax : UriSyntax,
  implicit_file~ : Bool,
) -> (Int32, UriError?) {
  if idx == length {
    return (idx, empty_host(syntax, implicit_file))
  }
  let first = text.at(idx)
  if first == '/' || (first == '\\' && syntax.is_file) || first is ('#' | '?') {
    return (idx, empty_host(syntax, implicit_file))
  }
  let mut start = idx
  if syntax.may_have_user_info {
    while start < length {
      let unit = text.at(start)
      if start == length - 1 || unit is ('?' | '#' | '\\' | '/') {
        start = idx
        break
      }
      if unit == '@' {
        start += 1
        break
      }
      start += 1
    }
  }
  let ch = text.at(start)
  let not_implicit_file = !implicit_file
  let mut end = length
  let mut host = HostType::NotParsed
  if ch == '[' && syntax.allow_ipv6 {
    if ipv6_end(text, start + 1, length) is Some(after) {
      host = Parsed
      end = after
    }
  }
  if host is NotParsed && syntax.allow_dns {
    if dns_host_end(text, start, length, not_implicit_file) is Some(after) {
      host = Parsed
      end = after
    }
  }
  if host is NotParsed && syntax.allow_unc {
    if unc_host_end(text, start, length, not_implicit_file) is Some(after) &&
      after - start <= 256 {
      host = Parsed
      end = after
    }
  }
  if end < length && text.at(end) == '\\' && host is Parsed && !syntax.is_file {
    if syntax.v1_unknown {
      return (end, Some(BadHostName))
    }
    host = NotParsed
  } else if end < length && text.at(end) == ':' {
    if syntax.may_have_port {
      let mut port = 0
      let mut i = end + 1
      while i < length {
        let unit = text.at(i)
        if is_ascii_digit(unit) {
          port = port * 10 + (unit.to_int() - '0'.to_int())
          if port > 0xFFFF {
            break
          }
        } else if unit is ('/' | '?' | '#') {
          break
        } else {
          return (i, Some(BadPort))
        }
        i += 1
      }
      if port > 0xFFFF {
        return (i, Some(BadPort))
      }
    } else {
      host = NotParsed
    }
  }
  if host is NotParsed {
    if syntax.v1_unknown {
      // V1 compatibility: an unknown scheme accepts the host names `.` and `..`.
      let mut dot_found = false
      let mut i = idx
      while i < length {
        let unit = text.at(i)
        if dot_found && unit is ('/' | '?' | '#') {
          break
        } else if i < idx + 2 && unit == '.' {
          dot_found = true
        } else {
          return (idx, Some(BadHostName))
        }
        i += 1
      }
      return (i, None)
    }
    if syntax.must_have_authority || syntax.mail_to_like {
      return (idx, Some(BadHostName))
    }
  }
  (end, None)
}

///|
/// The error for an empty host.
fn empty_host(syntax : UriSyntax, implicit_file : Bool) -> UriError? {
  if syntax.allow_empty_host && !implicit_file {
    None
  } else {
    Some(BadHostName)
  }
}

///|
/// Where a host name ends: at `/` or `\`, and also at `:`, `?` or `#` when the text has an explicit
/// scheme.
fn is_host_terminator(unit : UInt16, not_implicit_file : Bool) -> Bool {
  is_slash(unit) || (not_implicit_file && unit is (':' | '?' | '#'))
}

///|
/// The separators of domain name labels: `.` and its ideographic and full-width forms.
fn is_label_separator(unit : UInt16) -> Bool {
  unit is ('.' | '\u{3002}' | '\u{FF0E}' | '\u{FF61}')
}

///|
/// `DomainNameHelper.IsValid` with IRI parsing: the end of a domain name that starts at `start`.
/// Labels hold ASCII letters, digits, `-` and `_`, or non-ASCII characters, and are not empty; a
/// final separator is allowed.
fn dns_host_end(
  text : String,
  start : Int32,
  length : Int32,
  not_implicit_file : Bool,
) -> Int32? {
  let mut end = start
  while end < length {
    let unit = text.at(end)
    let valid = is_ascii_letter(unit) ||
      is_ascii_digit(unit) ||
      unit is ('-' | '_') ||
      is_label_separator(unit) ||
      unit >= 0x80
    if !valid {
      if !is_host_terminator(unit, not_implicit_file) {
        return None
      }
      break
    }
    end += 1
  }
  if end == start {
    return None
  }
  // A label weighs one per code unit, one more per code unit from U+0100 on, and four more (the
  // `xn--` prefix) when it holds non-ASCII; .NET 10 on Windows rejects a weight above 63.
  let mut units = 0
  let mut wide = 0
  let mut non_ascii = false
  for i = start; i <= end; i = i + 1 {
    if i == end || is_label_separator(text.at(i)) {
      if units == 0 {
        // An empty label is an error, except after a final separator.
        if i == end && i > start {
          break
        }
        return None
      }
      if units + wide + (if non_ascii { 4 } else { 0 }) > 63 {
        return None
      }
      units = 0
      wide = 0
      non_ascii = false
    } else {
      let unit = text.at(i)
      units += 1
      if unit >= 0x100 {
        wide += 1
      }
      if unit >= 0x80 {
        non_ascii = true
      }
    }
  }
  Some(end)
}

///|
/// An approximation of .NET `char.IsLetter` on one UTF-16 code unit: ASCII letters, and non-ASCII
/// code units outside surrogates, private use, and the Latin-1, general punctuation, currency,
/// symbol, CJK punctuation and full-width punctuation blocks. MoonBit has no Unicode category
/// tables; other non-letters, such as non-ASCII digits, count as letters (deliberate difference 21).
fn is_letter_approximation(unit : UInt16) -> Bool {
  if unit < 0x80 {
    return is_ascii_letter(unit)
  }
  let c = unit.to_int()
  let not_letter = (c < 0xC0 && !(c is (0xAA | 0xB5 | 0xBA))) ||
    c is (0xD7 | 0xF7) ||
    (c >= 0x2000 && c <= 0x206F) ||
    (c >= 0x20A0 && c <= 0x20CF) ||
    (c >= 0x2190 && c <= 0x2BFF) ||
    (c >= 0x3000 && c <= 0x3004) ||
    (c >= 0x3008 && c <= 0x3020) ||
    c == 0x3030 ||
    (c >= 0x303D && c <= 0x303F) ||
    (c >= 0xD800 && c <= 0xF8FF) ||
    (c >= 0xFF01 && c <= 0xFF20) ||
    (c >= 0xFF3B && c <= 0xFF40) ||
    (c >= 0xFF5B && c <= 0xFF65) ||
    c >= 0xFFF0
  !not_letter
}

///|
/// `UncNameHelper.IsValid`: the end of a UNC server name that starts at `start`.
fn unc_host_end(
  text : String,
  start : Int32,
  length : Int32,
  not_implicit_file : Bool,
) -> Int32? {
  if start == length {
    return None
  }
  let is_letter = is_letter_approximation
  let mut end = length
  let mut valid_short_name = false
  let mut i = start
  // The first segment may consist of `_` or `-` only, but not of digits only.
  while i < end {
    let unit = text.at(i)
    if is_host_terminator(unit, not_implicit_file) {
      end = i
      break
    } else if unit == '.' {
      i += 1
      break
    }
    if is_letter(unit) || unit is ('-' | '_') {
      valid_short_name = true
    } else if !is_ascii_digit(unit) {
      return None
    }
    i += 1
  }
  if !valid_short_name {
    return None
  }
  // Later segments start with a letter or a digit.
  while i < end {
    let unit = text.at(i)
    if is_host_terminator(unit, not_implicit_file) {
      end = i
      break
    } else if unit == '.' {
      if !valid_short_name || (i - 1 >= start && text.at(i - 1) == '.') {
        return None
      }
      valid_short_name = false
    } else if unit is ('-' | '_') {
      if !valid_short_name {
        return None
      }
    } else if is_letter(unit) || is_ascii_digit(unit) {
      valid_short_name = true
    } else {
      return None
    }
    i += 1
  }
  if i - 1 >= start && text.at(i - 1) == '.' {
    valid_short_name = true
  }
  if valid_short_name {
    Some(end)
  } else {
    None
  }
}

///|
/// `IPv6AddressHelper.IsValid`: for an address that starts after `[` at `start`, the offset after
/// its closing `]`.
fn ipv6_end(text : String, start : Int32, length : Int32) -> Int32? {
  let mut sequence_count = 0
  let mut sequence_length = 0
  let mut have_compressor = false
  let mut have_ipv4 = false
  let mut have_prefix = false
  let mut expecting_number = true
  let mut last_sequence = 1
  let mut closing = -1
  let mut i = start
  while i < length && closing < 0 {
    let unit = text.at(i)
    let digit = if have_prefix {
      is_ascii_digit(unit)
    } else {
      is_ascii_hex_digit(unit)
    }
    if digit {
      sequence_length += 1
      expecting_number = false
      i += 1
      continue
    }
    if sequence_length > 4 {
      return None
    }
    if sequence_length != 0 {
      sequence_count += 1
      last_sequence = i - sequence_length
    }
    let mut next = unit
    if next == '%' {
      // A zone identifier: anything up to `]` or `/`.
      i += 1
      while i < length && !(text.at(i) is (']' | '/')) {
        i += 1
      }
      if i == length {
        return None
      }
      next = text.at(i)
      if next == ']' {
        // The sequence length is kept, as .NET jumps to `]` without resetting it.
        closing = i
        continue
      }
    }
    match next {
      ']' => {
        closing = i
        continue
      }
      ':' =>
        if i > 0 && text.at(i - 1) == ':' {
          if have_compressor {
            return None
          }
          have_compressor = true
          expecting_number = false
        } else {
          expecting_number = true
        }
      '/' => {
        if sequence_count == 0 || have_prefix {
          return None
        }
        have_prefix = true
        expecting_number = true
      }
      '.' => {
        if have_ipv4 {
          return None
        }
        guard ipv4_canonical_end(text, last_sequence, length) is Some(after) else {
          return None
        }
        // An IPv4 address takes two of the eight sequences; one was counted at the `.`.
        sequence_count += 1
        have_ipv4 = true
        i = after
        sequence_length = 0
        continue
      }
      _ => return None
    }
    sequence_length = 0
    i += 1
  }
  if closing < 0 {
    return None
  }
  if have_prefix && (sequence_length < 1 || sequence_length > 2) {
    return None
  }
  let expected = 8 + (if have_prefix { 1 } else { 0 })
  let count_ok = if have_compressor {
    sequence_count < expected
  } else {
    sequence_count == expected
  }
  if !expecting_number && sequence_length <= 4 && count_ok {
    Some(closing + 1)
  } else {
    None
  }
}

///|
/// `IPv4AddressHelper.IsValidCanonical` inside an IPv6 address: four decimal numbers of at most
/// 255 without leading zeros, ending at `]`, `/` or `%`. It returns the offset after the address.
fn ipv4_canonical_end(text : String, start : Int32, length : Int32) -> Int32? {
  let mut dots = 0
  let mut number = 0
  let mut have_number = false
  let mut first_is_zero = false
  let mut i = start
  while i < length {
    let unit = text.at(i)
    if unit is (']' | '/' | '%') {
      break
    }
    if is_ascii_digit(unit) {
      if !have_number && unit == '0' {
        if i + 1 < length && text.at(i + 1) == '0' {
          return None
        }
        first_is_zero = true
      }
      have_number = true
      number = number * 10 + (unit.to_int() - '0'.to_int())
      if number > 255 {
        return None
      }
    } else if unit == '.' {
      if !have_number || (number > 0 && first_is_zero) {
        return None
      }
      dots += 1
      have_number = false
      number = 0
      first_is_zero = false
    } else {
      return None
    }
    i += 1
  }
  if dots == 3 && have_number {
    Some(i)
  } else {
    None
  }
}