// Word splitting and case conversion (implements spec.mbt).

///|
/// Strip Rust raw-identifier `r#` prefixes at string start or right after a
/// non-alphanumeric / `_` separator (`r#CreateParams` -> `CreateParams`,
/// `PublicOplogEntry_r#ActivatePluginParams` ->
/// `PublicOplogEntry_ActivatePluginParams`).
fn strip_rust_raw_prefixes(input : String) -> String {
  let chars : Array[Char] = []
  for ch in input {
    chars.push(ch)
  }
  let buf = StringBuilder()
  let mut i = 0
  while i < chars.length() {
    let at_boundary = i == 0 ||
      !(chars[i - 1] is ('A'..<='Z' | 'a'..<='z' | '0'..<='9'))
    if at_boundary &&
      i + 1 < chars.length() &&
      chars[i] is 'r' &&
      chars[i + 1] is '#' {
      i += 2
      continue
    }
    buf.write_char(chars[i])
    i += 1
  }
  buf.to_string()
}

///|
pub fn split_words(input : String) -> Array[String] {
  let words : Array[String] = []
  for segment in sanitize(input).split("_") {
    for word in split_camel(segment) {
      words.push(word)
    }
  }
  words
}

///|
/// Split one separator-free segment at camelCase and acronym boundaries:
/// - `lower -> upper` (`httpApi` -> `http`, `Api`)
/// - `digit -> letter` (`v2Api` -> `v2`, `Api`; digits attach to preceding word)
/// - `upper -> upper -> lower` (`HTTPServer` -> `HTTP`, `Server`;
///   `OAuth2Provider` -> `O`, `Auth2`, `Provider`)
fn split_camel(segment : StringView) -> Array[String] {
  let chars : Array[Char] = []
  for c in segment {
    chars.push(c)
  }
  let words : Array[String] = []
  let buf = StringBuilder()
  for i, c in chars {
    let kind = char_kind(c)
    let boundary = if i == 0 {
      false
    } else {
      let prev_kind = char_kind(chars[i - 1])
      match (prev_kind, kind) {
        (Lower, Upper) => true
        (Digit, Upper | Lower) => true
        (Upper, Upper) =>
          i + 1 < chars.length() && char_kind(chars[i + 1]) is Lower
        _ => false
      }
    }
    if boundary && !buf.is_empty() {
      words.push(buf.to_string())
      buf.reset()
    }
    buf.write_char(c)
  }
  if !buf.is_empty() {
    words.push(buf.to_string())
  }
  words
}

///|
priv enum CharKind {
  Upper
  Lower
  Digit
  Other
}

///|
fn char_kind(c : Char) -> CharKind {
  if c is ('A'..<='Z') {
    Upper
  } else if c is ('a'..<='z') {
    Lower
  } else if c.is_digit(10) {
    Digit
  } else {
    Other
  }
}

///|
fn is_all_upper(w : String) -> Bool {
  let mut has_upper = false
  for c in w {
    if c is ('a'..<='z') {
      return false
    }
    if c is ('A'..<='Z') {
      has_upper = true
    }
  }
  has_upper
}

///|
fn join_case(
  input : String,
  first : (String) -> String,
  rest : (String) -> String,
  sep : String,
) -> String {
  let words = split_words(input)
  let parts : Array[String] = []
  for i, w in words {
    parts.push(if i == 0 { first(w) } else { rest(w) })
  }
  parts.join(sep)
}

///|
/// Convert `input` to `PascalCase` (for type and variant names).
pub fn to_pascal(input : String) -> String {
  join_case(input, capitalize_first, capitalize_first, "")
}

///|
/// Convert `input` to `camelCase`.
pub fn to_camel(input : String) -> String {
  join_case(input, lower_word, capitalize_first, "")
}

///|
/// Convert `input` to `snake_case` (for function, parameter, and field names).
pub fn to_snake(input : String) -> String {
  join_case(input, fn(w) { w.to_lower() }, fn(w) { w.to_lower() }, "_")
}

///|
/// Convert `input` to `kebab-case`.
pub fn to_kebab(input : String) -> String {
  join_case(input, fn(w) { w.to_lower() }, fn(w) { w.to_lower() }, "-")
}

///|
/// Capitalize a single word for PascalCase: ALL_CAPS words (`HTTP`, `GOLEM`)
/// are normalized to title case (`Http`, `Golem`), while mixed-case words
/// keep their interior casing.
fn capitalize_first(w : String) -> String {
  if w == "" {
    w
  } else if is_all_upper(w) && w.length() > 1 {
    w[0:1].to_owned().to_upper() + w[1:].to_owned().to_lower()
  } else {
    w[0:1].to_owned().to_upper() + w[1:].to_owned()
  }
}

///|
/// Lowercase the leading word for camelCase: ALL_CAPS words (`HTTP`, `GOLEM`)
/// are fully lowercased (`http`, `golem`).
fn lower_word(w : String) -> String {
  if w == "" {
    w
  } else if is_all_upper(w) {
    w.to_lower()
  } else {
    w[0:1].to_owned().to_lower() + w[1:].to_owned()
  }
}