///|
let fnv_offset_basis : UInt32 = 0x811c9dc5U

///|
let fnv_prime : UInt32 = 0x01000193U

///|
let hex_digits : ReadOnlyArray[Char] = [
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
]

///|
/// Deterministic 32-bit FNV-1a digest over UTF-8 bytes, formatted as 8
/// lower-case hexadecimal digits. Produces the same output across all targets.
pub fn fnv1a_32_hex(input : String) -> String {
  let bytes = @utf8.encode(input)
  let mut hash = fnv_offset_basis
  for b in bytes {
    hash = hash ^ b.to_uint()
    hash = hash * fnv_prime
  }
  let buf = StringBuilder()
  for shift in [28, 24, 20, 16, 12, 8, 4, 0] {
    let nibble = ((hash >> shift) & 0xfU).reinterpret_as_int()
    buf.write_char(hex_digits[nibble])
  }
  buf.to_string()
}

///|
/// Sanitizes a human name into a compact RFC 8141 URN slug (`a-z`, `0-9`, `-`,
/// starting with `a-z`/`0-9`, at most 64 characters).
fn slug_of(raw : String, fallback : String) -> String {
  let buf = StringBuilder()
  let mut len = 0
  let mut pending_dash = false
  for c in raw {
    let lower = if c is ('A'..<='Z') { c.to_ascii_lowercase() } else { c }
    if lower is ('a'..<='z' | '0'..<='9') {
      if pending_dash && len > 0 && len < 64 {
        buf.write_char('-')
        len += 1
      }
      if len < 64 {
        buf.write_char(lower)
        len += 1
      }
      pending_dash = false
    } else if len > 0 {
      pending_dash = true
    }
  }
  if len == 0 {
    fallback
  } else {
    buf.to_string()
  }
}

///|
/// Sanitizes arbitrary path/display text into a single-line trimmed string of
/// at most `max_len` characters with no control characters.
fn sanitize_single_line(
  raw : String,
  max_len : Int32,
  fallback : String,
) -> String {
  let chars : Array[Char] = []
  let mut prev_space = true
  for c in raw {
    let code = c.to_int()
    let is_ws_or_ctrl = code <= 0x20 ||
      code == 0x7f ||
      c == '\u{00a0}' ||
      c == '\u{3000}'
    if is_ws_or_ctrl {
      if !prev_space && chars.length() < max_len {
        chars.push(' ')
        prev_space = true
      }
    } else if chars.length() < max_len {
      chars.push(c)
      prev_space = false
    }
  }
  while chars.last() is Some(' ') {
    ignore(chars.pop())
  }
  if chars.is_empty() {
    fallback
  } else {
    let buf = StringBuilder()
    for c in chars {
      buf.write_char(c)
    }
    buf.to_string()
  }
}

///|
/// Derives the deterministic RFC 8141 URN `ProjectId` (`urn:mc:proj:-`)
/// from a project's canonical anchor.
pub fn project_id_of(anchor : Anchor) -> @app.ProjectId {
  let slug = slug_of(anchor.name(), "project")
  let canonical = match anchor {
    Folder(path) => "folder:" + path.canonical_key()
    Repository(backend~, store~, ..) =>
      backend.to_string() + ":" + store.canonical_key()
  }
  let urn = "urn:mc:proj:\{slug}-\{fnv1a_32_hex(canonical)}"
  @app.ProjectId::ProjectId(urn) catch {
    _ => abort("derived project URN is invalid: \{urn}")
  }
}

///|
/// Derives the deterministic RFC 8141 URN `WorkspaceId` (`urn:mc:ws:-`)
/// from a workspace's canonical root folder.
pub fn workspace_id_of(root : FolderPath) -> @app.WorkspaceId {
  let slug = slug_of(root.name(), "workspace")
  let urn = "urn:mc:ws:\{slug}-\{fnv1a_32_hex("ws:" + root.canonical_key())}"
  @app.WorkspaceId::WorkspaceId(urn) catch {
    _ => abort("derived workspace URN is invalid: \{urn}")
  }
}

///|
/// Derives the deterministic workspace-scoped RFC 8141 URN `SourceId`
/// (`urn:mc:src:-`) for an in-tree source.
pub fn source_id_in_tree(
  workspace_id : @app.WorkspaceId,
  adapter : @app.AdapterId,
  name : @app.SourceName,
  location : @app.InTreeLocation,
) -> @app.SourceId {
  let slug = slug_of(name.to_string(), "source")
  let key = "\{workspace_id.to_string()}|in-tree|\{adapter.to_string()}|\{location.key()}"
  let urn = "urn:mc:src:\{slug}-\{fnv1a_32_hex(key)}"
  @app.SourceId::SourceId(urn) catch {
    _ => abort("derived in-tree source URN is invalid: \{urn}")
  }
}

///|
/// Derives the deterministic workspace-scoped and trust-scoped RFC 8141 URN
/// `SourceId` (`urn:mc:src:-`) for a configured mount.
pub fn source_id_mounted(
  workspace_id : @app.WorkspaceId,
  trust : @app.TrustTier,
  kind : @app.MountKind?,
  name : @app.SourceName,
) -> @app.SourceId {
  let slug = slug_of(name.to_string(), "source")
  let kind_str = match kind {
    Some(k) => k.to_string()
    None => "unknown"
  }
  let key = "\{workspace_id.to_string()}|mount|\{trust.wire_name()}|\{kind_str}|\{name.to_string()}"
  let urn = "urn:mc:src:\{slug}-\{fnv1a_32_hex(key)}"
  @app.SourceId::SourceId(urn) catch {
    _ => abort("derived mounted source URN is invalid: \{urn}")
  }
}

///|
/// Total derivation of a valid default `ProjectTitle` from a project anchor.
pub fn default_project_title(anchor : Anchor) -> @app.ProjectTitle {
  let text = sanitize_single_line(anchor.name(), 120, "project")
  @app.ProjectTitle::ProjectTitle(text) catch {
    _ => abort("derived project title is invalid: \{text}")
  }
}

///|
/// Total derivation of a valid default `WorkspaceName` from a workspace root
/// folder.
pub fn default_workspace_name(root : FolderPath) -> @app.WorkspaceName {
  let text = sanitize_single_line(root.name(), 120, "workspace")
  @app.WorkspaceName::WorkspaceName(text) catch {
    _ => abort("derived workspace name is invalid: \{text}")
  }
}