///|
/// The 2009 XAML language namespace URI. It is a full equivalent of the 2006 URI
/// (`@nodes.xaml_language_namespace`), which identities use (design D11, F27).
pub let xaml_language_namespace_2009 : String = "http://schemas.microsoft.com/winfx/2009/xaml"

///|
/// The URI that identities use for `namespace_uri`: the 2006 XAML language URI for the 2009 one.
fn language_alias(namespace_uri : String) -> String {
  if namespace_uri == xaml_language_namespace_2009 {
    @nodes.xaml_language_namespace
  } else {
    namespace_uri
  }
}

///|
/// The URI of a CLR-style namespace in a scope: `clr-namespace:N;assembly=S`.
pub fn clr_namespace_uri(clr_namespace : String, scope : String) -> String {
  "clr-namespace:\{clr_namespace};assembly=\{scope}"
}

///|
/// Why a namespace URI cannot be used to look a type up.
#derive(Eq, Debug)
pub(all) suberror NamespaceError {
  /// A `clr-namespace:` URI that is not `N` or `N;assembly=A` with a non-empty `N`, or a `using:`
  /// URI that is not a non-empty `N` without clauses.
  MalformedClrNamespace(namespace_uri~ : String)
  /// Several scopes register the CLR-style namespace of a `using:` URI with the type.
  AmbiguousType(
    name~ : String,
    namespace_uri~ : String,
    scopes~ : ReadOnlyArray[String],
  )
}

///|
pub fn NamespaceError::message(self : NamespaceError) -> String {
  match self {
    MalformedClrNamespace(namespace_uri~) =>
      "the namespace \"\{namespace_uri}\" is not clr-namespace:N, clr-namespace:N;assembly=A or using:N"
    AmbiguousType(name~, namespace_uri~, scopes~) =>
      "the type \{name} of \"\{namespace_uri}\" is registered in more than one scope: \{scopes.iter().collect().join(", ")}"
  }
}

///|
/// A namespace URI as a CLR-style namespace reference.
priv enum ClrReference {
  /// A URI that is not CLR-style.
  NotClr
  /// `clr-namespace:N` with the scope after `assembly=`, or `None` without one or when it is empty.
  ClrNamespace(clr_namespace~ : String, scope~ : String?)
  /// `using:N`.
  Using(String)
}

///|
fn clr_reference(namespace_uri : String) -> ClrReference raise NamespaceError {
  if namespace_uri.has_prefix("clr-namespace:") {
    let rest = namespace_uri["clr-namespace:".length():]
    let parts = rest.split(";").map(part => part.to_owned()).collect()
    let clr_namespace = parts[0]
    if clr_namespace.is_empty() || parts.length() > 2 {
      raise MalformedClrNamespace(namespace_uri~)
    }
    if parts.length() == 1 {
      return ClrNamespace(clr_namespace~, scope=None)
    }
    guard parts[1].has_prefix("assembly=") else {
      raise MalformedClrNamespace(namespace_uri~)
    }
    let scope = parts[1]["assembly=".length():].to_owned()
    ClrNamespace(
      clr_namespace~,
      scope=if scope.is_empty() { None } else { Some(scope) },
    )
  } else if namespace_uri.has_prefix("using:") {
    let clr_namespace = namespace_uri["using:".length():].to_owned()
    if clr_namespace.is_empty() || clr_namespace.contains(";") {
      raise MalformedClrNamespace(namespace_uri~)
    }
    Using(clr_namespace)
  } else {
    NotClr
  }
}

///|
/// Check a CLR-style namespace URI and apply the local scope (design D11, F28, 2F27).
/// `clr-namespace:N` and `clr-namespace:N;assembly=` become `clr-namespace:N;assembly=A` for the
/// local scope `A`, as System.Xaml `XamlXmlReader` maps them to the local assembly; without a local
/// scope they are kept as written. Other URIs, `using:N` included, are returned unchanged.
pub fn normalize_clr_namespace(
  namespace_uri : String,
  local_scope? : String,
) -> String raise NamespaceError {
  match clr_reference(namespace_uri) {
    ClrNamespace(clr_namespace~, scope=None) =>
      match local_scope {
        Some(scope) => clr_namespace_uri(clr_namespace, scope)
        None => namespace_uri
      }
    _ => namespace_uri
  }
}

///|
/// The registered preferred prefixes and subsumptions that decide a type's preferred namespace.
priv struct NamespacePreferences {
  /// The preferred prefix of each URI.
  prefixes : Map[String, String]
  /// The newer namespace of each subsumed one.
  newer : Map[String, String]
  /// How many namespaces each namespace subsumes directly.
  subsumed_count : Map[String, Int32]
}

///|
/// Whether `a` subsumes `b`, directly or through a chain.
fn NamespacePreferences::subsumes(
  self : NamespacePreferences,
  a : String,
  b : String,
) -> Bool {
  let mut current = b
  let mut steps = 0
  // A built context has no cycles; the step bound keeps a broken one finite.
  while self.newer.get(current) is Some(next) && steps <= self.newer.length() {
    if next == a {
      return true
    }
    current = next
    steps += 1
  }
  false
}

///|
/// System.Xaml's `XmlNsInfo.NamespaceComparer.CompareNamespacesByPreference` (2F29): negative when
/// `a` is preferred over `b`.
fn NamespacePreferences::compare(
  self : NamespacePreferences,
  a : String,
  b : String,
) -> Int32 {
  if a == b {
    return 0
  }
  if self.subsumes(a, b) {
    return -1
  }
  if self.subsumes(b, a) {
    return 1
  }
  match (self.newer.contains(a), self.newer.contains(b)) {
    (false, true) => return -1
    (true, false) => return 1
    _ => ()
  }
  let count_a = self.subsumed_count.get(a).unwrap_or(0)
  let count_b = self.subsumed_count.get(b).unwrap_or(0)
  if count_a != count_b {
    return if count_a > count_b { -1 } else { 1 }
  }
  match (self.prefixes.get(a), self.prefixes.get(b)) {
    (Some(_), None) => return -1
    (None, Some(_)) => return 1
    (Some(pa), Some(pb)) if pa.length() != pb.length() =>
      return if pa.length() < pb.length() { -1 } else { 1 }
    _ => ()
  }
  a.lexical_compare(b)
}

///|
/// The preferred prefix among `candidates`: the shortest in UTF-16 units, then the ordinal least,
/// as System.Xaml `XmlNsInfo` chooses (F30).
fn choose_prefix(current : String?, candidate : String) -> String {
  match current {
    None => candidate
    Some(existing) =>
      if candidate.length() < existing.length() ||
        (
          candidate.length() == existing.length() &&
          candidate.lexical_compare(existing) < 0
        ) {
        candidate
      } else {
        existing
      }
  }
}