///|
/// HCL Identifier type with validation
///
/// Represents a validated HCL identifier. Identifiers are used for attribute
/// names, block labels, variable references, etc.
///
/// Validation uses Unicode XID_Start/XID_Continue rules matching the lexer:
/// - First character: a-z, A-Z, underscore, Latin extended, CJK, Hangul, etc.
/// - Remaining characters: all of the above plus 0-9, hyphen, combining marks
///
/// ```mbt check
/// test {
///   let id = Ident::new("name")
///   assert_eq(id.as_str(), "name")
///   assert_eq(id.len(), 4)
/// }
/// ```
pub struct Ident {
  inner : String
} derive(Eq)

///|
/// Create a new Ident after validating.
///
/// Panics if the identifier is empty or contains invalid characters.
///
/// ```mbt check
/// test {
///   let id = Ident::new("server")
///   assert_eq(id.as_str(), "server")
/// }
/// ```
pub fn Ident::new(s : String) -> Ident {
  if !is_ident(s) {
    panic()
  }
  { inner: s }
}

///|
/// Create a new Ident after validating, returning error on failure.
///
/// ```mbt check
/// test {
///   assert_eq(Ident::try_new("ok_name").unwrap().as_str(), "ok_name")
///   assert_true(Ident::try_new("bad name") is Err(_))
/// }
/// ```
pub fn Ident::try_new(s : String) -> HCLResult[Ident] {
  if !is_ident(s) {
    Err(HCLError::invalid_value("invalid identifier: " + s))
  } else {
    Ok({ inner: s })
  }
}

///|
/// Create a new Ident, sanitizing invalid input.
///
/// Rules:
/// - Empty string becomes "_"
/// - Invalid characters replaced with "_"
/// - If first char is valid as id_continue but not id_start, prefix with "_"
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new_sanitized("my name").as_str(), "my_name")
///   assert_eq(Ident::new_sanitized("").as_str(), "_")
/// }
/// ```
pub fn Ident::new_sanitized(s : String) -> Ident {
  if s.is_empty() {
    return { inner: "_" }
  }
  let buf = StringBuilder::new(size_hint=s.length())
  let mut i = 0
  let len = s.length()
  while i < len {
    let ch = s[i].to_int().unsafe_to_char()
    if i == 0 && is_id_start(ch) {
      buf.write_char(ch)
    } else if is_id_continue(ch) {
      if i == 0 {
        buf.write_char('_')
      }
      buf.write_char(ch)
    } else {
      buf.write_char('_')
    }
    i = i + 1
  }
  { inner: buf.to_string() }
}

///|
/// Create a new Ident without validation.
///
/// Caller must ensure the string is a valid identifier.
/// Invalid identifiers will produce broken HCL output when serialized.
///
/// ```mbt check
/// test {
///   let id = Ident::new_unchecked("anything")
///   assert_eq(id.as_str(), "anything")
/// }
/// ```
pub fn Ident::new_unchecked(s : String) -> Ident {
  { inner: s }
}

///|
/// Get the identifier as a string reference.
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("x").as_str(), "x")
/// }
/// ```
pub fn Ident::as_str(self : Ident) -> String {
  self.inner
}

///|
/// Consume the Ident and return the inner String.
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("x").into_string(), "x")
/// }
/// ```
pub fn Ident::into_string(self : Ident) -> String {
  self.inner
}

///|
/// Check if the identifier is empty (should never happen for valid idents).
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("x").is_empty(), false)
///   assert_eq(Ident::new_unchecked("").is_empty(), true)
/// }
/// ```
pub fn Ident::is_empty(self : Ident) -> Bool {
  self.inner.is_empty()
}

///|
/// Get the length of the identifier.
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("abcd").len(), 4)
/// }
/// ```
pub fn Ident::len(self : Ident) -> Int {
  self.inner.length()
}

///|
/// Determines if ch is a valid HCL identifier start character.
///
/// Valid start: a-z, A-Z, underscore, and Unicode XID_Start characters
/// (Latin extended, CJK, Hangul, Cyrillic, Greek, Arabic, etc.)
///
/// ```mbt check
/// test {
///   assert_eq(is_id_start('a'), true)
///   assert_eq(is_id_start('_'), true)
///   assert_eq(is_id_start('1'), false)
/// }
/// ```
pub fn is_id_start(ch : Char) -> Bool {
  if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_' {
    return true
  }
  let cp = ch.to_int()
  // Latin Extended (À-ÿ) excluding × and ÷
  if cp >= 0x00C0 && cp <= 0x00FF && cp != 0x00D7 && cp != 0x00F7 {
    return true
  }
  // Latin Extended-A
  if cp >= 0x0100 && cp <= 0x017F {
    return true
  }
  // Latin Extended-B
  if cp >= 0x0180 && cp <= 0x024F {
    return true
  }
  // Greek
  if cp >= 0x0370 && cp <= 0x03FF {
    return true
  }
  // Cyrillic
  if cp >= 0x0400 && cp <= 0x04FF {
    return true
  }
  // Arabic
  if cp >= 0x0600 && cp <= 0x06FF {
    return true
  }
  // Devanagari
  if cp >= 0x0900 && cp <= 0x097F {
    return true
  }
  // Thai
  if cp >= 0x0E00 && cp <= 0x0E7F {
    return true
  }
  // CJK Extension A
  if cp >= 0x3400 && cp <= 0x4DBF {
    return true
  }
  // CJK Unified Ideographs
  if cp >= 0x4E00 && cp <= 0x9FFF {
    return true
  }
  // Hangul Syllables
  if cp >= 0xAC00 && cp <= 0xD7AF {
    return true
  }
  false
}

///|
/// Determines if ch is a valid HCL identifier continue character.
///
/// Valid continue: a-z, A-Z, 0-9, underscore, hyphen,
/// and Unicode XID_Continue characters (combining marks)
///
/// ```mbt check
/// test {
///   assert_eq(is_id_continue('a'), true)
///   assert_eq(is_id_continue('1'), true)
///   assert_eq(is_id_continue('-'), true)
///   assert_eq(is_id_continue(' '), false)
/// }
/// ```
pub fn is_id_continue(ch : Char) -> Bool {
  if is_id_start(ch) {
    return true
  }
  if ch >= '0' && ch <= '9' {
    return true
  }
  if ch == '-' {
    return true
  }
  let cp = ch.to_int()
  // Combining Diacritical Marks
  if cp >= 0x0300 && cp <= 0x036F {
    return true
  }
  false
}

///|
/// Determines if s is a valid HCL identifier.
///
/// A valid identifier must:
/// - Not be empty
/// - First char passes is_id_start
/// - All remaining chars pass is_id_continue
///
/// ```mbt check
/// test {
///   assert_eq(is_ident("server_name"), true)
///   assert_eq(is_ident("1x"), false)
///   assert_eq(is_ident(""), false)
/// }
/// ```
pub fn is_ident(s : String) -> Bool {
  if s.is_empty() {
    return false
  }
  let mut i = 0
  let len = s.length()
  while i < len {
    let ch = s[i].to_int().unsafe_to_char()
    if i == 0 {
      if !is_id_start(ch) {
        return false
      }
    } else if !is_id_continue(ch) {
      return false
    }
    i = i + 1
  }
  true
}

///|
/// Implement Display for Ident (output the raw string)
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("x").output(), "x")
/// }
/// ```
pub fn Ident::output(self : Ident) -> String {
  self.inner
}

///|
/// Debug representation
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("foo").to_string(), "Ident(foo)")
/// }
/// ```
pub fn Ident::to_string(self : Ident) -> String {
  "Ident(" + self.inner + ")"
}

///|
/// Implement hash for Ident (delegates to inner string)
///
/// ```mbt check
/// test {
///   assert_eq(Ident::new("a").hash(), Ident::new("a").hash())
/// }
/// ```
pub fn Ident::hash(self : Ident) -> Int {
  self.inner.hash()
}