// INI parsing.
//
// `moonbit-community/ini` exposes no way to enumerate sections, so the format is
// parsed here to keep arbitrary INI files usable as data.

///|
/// Parse a small INI document: `[section]` headers and `key = value` pairs.
///
/// Top-level keys stay at the root, section keys become nested objects, and
/// scalars are typed so `port = 8000` works without a schema.
pub fn parse_ini(text : StringView) -> Json {
  let top : Map[String, Json] = Map([])
  let sections : Map[String, Map[String, Json]] = Map([])
  let mut current = ""
  for raw in @core.lines(text) {
    let line = @core.trim(raw)
    if line == "" || line.has_prefix(";") || line.has_prefix("#") {
      continue
    }
    if line.has_prefix("[") && line.has_suffix("]") {
      current = @core.trim(@core.slice(line, 1, line.length() - 1))
      if !sections.contains(current) {
        sections.set(current, Map([]))
      }
      continue
    }
    match index_of_char(line, '=') {
      Some(at) => {
        let key = @core.trim(@core.slice(line, 0, at))
        let value = ini_scalar(
          @core.trim(@core.slice(line, at + 1, line.length())),
        )
        if key == "" {
          continue
        }
        if current == "" {
          top.set(key, value)
        } else {
          match sections.get(current) {
            Some(section) => section.set(key, value)
            None => ()
          }
        }
      }
      None => ()
    }
  }
  for name, section in sections {
    top.set(name, Json::object(section))
  }
  Json::object(top)
}

// Convert an INI scalar: quoted strings stay strings, otherwise booleans and
// numbers are recognised.

///|
fn ini_scalar(text : StringView) -> Json {
  let value = @core.trim(text)
  if value.length() >= 2 {
    let first = @core.char_at(value, 0)
    if (first == '"' || first == '\'') &&
      @core.char_at(value, value.length() - 1) == first {
      return Json::string(@core.trim_quotes(value))
    }
  }
  if value == "true" {
    return Json::boolean(true)
  }
  if value == "false" {
    return Json::boolean(false)
  }
  match @core.parse_double(value) {
    Some(n) => Json::number(n)
    None => Json::string(value)
  }
}

// Position of the first `needle` character.

///|
fn index_of_char(text : StringView, needle : Char) -> Int32? {
  let chars = text.to_array()
  for i = 0; i < chars.length(); i = i + 1 {
    if chars[i] == needle {
      return Some(i)
    }
  }
  None
}