///|
/// Pure MoonBit YAML Core formatter and parser for CUE YAML export and `vet_yaml`.
/// Supports standard YAML mappings, block sequences, flow collections, comments,
/// quoted/plain scalars, booleans, nulls, integers, and floats.

///|
/// Format a `@json.Json` value into clean YAML 1.2 output.
pub fn format_yaml(j : Json) -> String {
  let buf = StringBuilder()
  write_yaml_root(j, buf, 0)
  buf.to_string()
}

///|
fn write_yaml_root(j : Json, buf : StringBuilder, indent : Int32) -> Unit {
  match j {
    Object(map) =>
      if map.is_empty() {
        buf.write_string("{}\n")
      } else {
        for k, v in map {
          write_spaces(buf, indent)
          write_yaml_key(k, buf)
          match v {
            Object(m) if !m.is_empty() => {
              buf.write_string(":\n")
              write_yaml_root(v, buf, indent + 2)
            }
            Array(a) if !a.is_empty() => {
              buf.write_string(":\n")
              write_yaml_root(v, buf, indent + 2)
            }
            _ => {
              buf.write_string(": ")
              write_yaml_scalar(v, buf)
              buf.write_char('\n')
            }
          }
        }
      }
    Array(items) =>
      if items.is_empty() {
        buf.write_string("[]\n")
      } else {
        for item in items {
          write_spaces(buf, indent)
          match item {
            Object(m) if !m.is_empty() => {
              let mut first = true
              for k, v in m {
                if first {
                  buf.write_string("- ")
                  first = false
                } else {
                  write_spaces(buf, indent + 2)
                }
                write_yaml_key(k, buf)
                match v {
                  Object(sub) if !sub.is_empty() => {
                    buf.write_string(":\n")
                    write_yaml_root(v, buf, indent + 4)
                  }
                  Array(sub) if !sub.is_empty() => {
                    buf.write_string(":\n")
                    write_yaml_root(v, buf, indent + 4)
                  }
                  _ => {
                    buf.write_string(": ")
                    write_yaml_scalar(v, buf)
                    buf.write_char('\n')
                  }
                }
              }
            }
            Array(a) if !a.is_empty() => {
              buf.write_string("-\n")
              write_yaml_root(item, buf, indent + 2)
            }
            _ => {
              buf.write_string("- ")
              write_yaml_scalar(item, buf)
              buf.write_char('\n')
            }
          }
        }
      }
    _ => {
      write_yaml_scalar(j, buf)
      buf.write_char('\n')
    }
  }
}

///|
fn yaml_needs_quoting(s : String) -> Bool {
  if s.is_empty() {
    return true
  }
  match s {
    "null"
    | "Null"
    | "NULL"
    | "~"
    | "true"
    | "True"
    | "TRUE"
    | "false"
    | "False"
    | "FALSE"
    | "yes"
    | "no"
    | "on"
    | "off" => return true
    _ => ()
  }
  let chars = s.to_array()
  let c0 = chars[0]
  if c0 == ' ' ||
    c0 == '-' ||
    c0 == '?' ||
    c0 == ':' ||
    c0 == '[' ||
    c0 == ']' ||
    c0 == '{' ||
    c0 == '}' ||
    c0 == '#' ||
    c0 == '&' ||
    c0 == '*' ||
    c0 == '!' ||
    c0 == '|' ||
    c0 == '>' ||
    c0 == '\'' ||
    c0 == '"' ||
    c0 == '%' ||
    c0 == '@' ||
    c0 == '`' {
    return true
  }
  if chars[chars.length() - 1] == ' ' {
    return true
  }
  for c in chars {
    if c == ':' || c == '#' || c == '\n' || c == '\r' || c == '\t' {
      return true
    }
  }
  // Quote strings that look like numbers
  let as_int : Result[Int64, Error] = Ok(@string.parse_int64(s)) catch {
    e => Err(e)
  }
  if as_int is Ok(_) {
    return true
  }
  let as_dbl : Result[Double, Error] = Ok(@string.parse_double(s)) catch {
    e => Err(e)
  }
  if as_dbl is Ok(_) {
    return true
  }
  false
}

///|
fn write_yaml_key(k : String, buf : StringBuilder) -> Unit {
  if yaml_needs_quoting(k) {
    write_json_string(k, buf)
  } else {
    buf.write_string(k)
  }
}

///|
fn write_yaml_scalar(j : Json, buf : StringBuilder) -> Unit {
  match j {
    Null => buf.write_string("null")
    True => buf.write_string("true")
    False => buf.write_string("false")
    Number(d, repr~) =>
      match repr {
        Some(r) => buf.write_string(r)
        None => {
          let i = d.to_int64()
          if i.to_double() == d {
            buf.write_string("\{i}")
          } else {
            buf.write_string("\{d}")
          }
        }
      }
    String(s) =>
      if yaml_needs_quoting(s) {
        write_json_string(s, buf)
      } else {
        buf.write_string(s)
      }
    Array([]) => buf.write_string("[]")
    Object(m) if m.is_empty() => buf.write_string("{}")
    _ => write_json(j, buf, 0, 0)
  }
}

///|
/// Parse a YAML Core configuration string directly into a CUE `Value`.
pub fn parse_yaml_value(src : String) -> Value raise CueError {
  let raw_lines = src.split("\n").collect()
  let lines : Array[(Int32, String, Int32)] = [] // (indent, content, 1-based line_no)
  for idx = 0; idx < raw_lines.length(); idx = idx + 1 {
    let raw = raw_lines[idx].to_owned().trim_end(chars="\r").to_owned()
    let stripped = strip_yaml_comment(raw)
    let trimmed = stripped.trim().to_owned()
    if trimmed.is_empty() || trimmed == "---" || trimmed == "..." {
      continue
    }
    let indent = count_leading_spaces(stripped)
    lines.push((indent, trimmed, idx + 1))
  }
  if lines.is_empty() {
    return VStruct(StructVal::empty())
  }
  let (val, _next) = parse_yaml_block(lines, 0, lines[0].0)
  val
}

///|
fn count_leading_spaces(s : String) -> Int32 {
  let mut n = 0
  for ch in s {
    if ch == ' ' {
      n += 1
    } else if ch == '\t' {
      n += 2
    } else {
      break
    }
  }
  n
}

///|
fn strip_yaml_comment(line : String) -> String {
  let chars = line.to_array()
  let mut in_single = false
  let mut in_double = false
  for i = 0; i < chars.length(); i = i + 1 {
    let c = chars[i]
    if c == '\'' && !in_double {
      in_single = !in_single
    } else if c == '"' && !in_single {
      if i == 0 || chars[i - 1] != '\\' {
        in_double = !in_double
      }
    } else if c == '#' && !in_single && !in_double {
      if i == 0 || chars[i - 1] == ' ' || chars[i - 1] == '\t' {
        return line.clamped_view(start=0, end=i).to_owned()
      }
    }
  }
  line
}

///|
fn parse_yaml_block(
  lines : Array[(Int32, String, Int32)],
  start_idx : Int32,
  base_indent : Int32,
) -> (Value, Int32) raise CueError {
  if start_idx >= lines.length() {
    return (VNull, start_idx)
  }
  let (_, first_content, _) = lines[start_idx]
  if first_content.has_prefix("- ") || first_content == "-" {
    return parse_yaml_seq(lines, start_idx, base_indent)
  }
  if find_yaml_colon(first_content) >= 0 {
    return parse_yaml_map(lines, start_idx, base_indent)
  }
  (parse_yaml_scalar(first_content, lines[start_idx].2), start_idx + 1)
}

///|
fn parse_yaml_seq(
  lines : Array[(Int32, String, Int32)],
  start_idx : Int32,
  base_indent : Int32,
) -> (Value, Int32) raise CueError {
  let elems : Array[Value] = []
  let mut i = start_idx
  while i < lines.length() {
    let (ind, content, line_no) = lines[i]
    if ind < base_indent {
      break
    }
    if ind > base_indent {
      raise CueError::new(
        YamlError,
        "unexpected indentation at line \{line_no}",
      )
    }
    if !(content.has_prefix("- ") || content == "-") {
      break
    }
    let rest = if content == "-" {
      ""
    } else {
      content.clamped_view(start=2).to_owned().trim().to_owned()
    }
    if rest.is_empty() {
      if i + 1 < lines.length() && lines[i + 1].0 > base_indent {
        let (v, next_i) = parse_yaml_block(lines, i + 1, lines[i + 1].0)
        elems.push(v)
        i = next_i
      } else {
        elems.push(VNull)
        i += 1
      }
    } else if find_yaml_colon(rest) >= 0 && !rest.has_prefix("{") {
      // Inline mapping item under `- key: val`
      let item_indent = base_indent + 2
      let sub_lines : Array[(Int32, String, Int32)] = [
        (item_indent, rest, line_no),
      ]
      let mut j = i + 1
      while j < lines.length() && lines[j].0 >= item_indent {
        sub_lines.push(lines[j])
        j += 1
      }
      let (v, _) = parse_yaml_map(sub_lines, 0, item_indent)
      elems.push(v)
      i = j
    } else {
      elems.push(parse_yaml_scalar(rest, line_no))
      i += 1
    }
  }
  (VList({ elems, open_tail: None, }), i)
}

///|
fn parse_yaml_map(
  lines : Array[(Int32, String, Int32)],
  start_idx : Int32,
  base_indent : Int32,
) -> (Value, Int32) raise CueError {
  let fields : Array[StructField] = []
  let mut i = start_idx
  while i < lines.length() {
    let (ind, content, line_no) = lines[i]
    if ind < base_indent {
      break
    }
    if ind > base_indent {
      raise CueError::new(
        YamlError,
        "unexpected indentation at line \{line_no}",
      )
    }
    let colon = find_yaml_colon(content)
    if colon < 0 {
      raise CueError::new(
        YamlError,
        "expected 'key: value' mapping entry at line \{line_no}",
      )
    }
    let raw_key = content
      .clamped_view(start=0, end=colon)
      .to_owned()
      .trim()
      .to_owned()
    let key = unquote_yaml_string(raw_key)
    let rest = content
      .clamped_view(start=colon + 1)
      .to_owned()
      .trim()
      .to_owned()
    let val : Value = if rest.is_empty() {
      if i + 1 < lines.length() &&
        (
          lines[i + 1].0 > base_indent ||
          (
            lines[i + 1].0 == base_indent &&
            (lines[i + 1].1.has_prefix("- ") || lines[i + 1].1 == "-")
          )
        ) {
        let (v, next_i) = parse_yaml_block(lines, i + 1, lines[i + 1].0)
        i = next_i
        v
      } else {
        i += 1
        VNull
      }
    } else {
      i += 1
      parse_yaml_scalar(rest, line_no)
    }
    fields.push({
      name: key,
      value: val,
      constraint: Regular,
      is_definition: false,
      is_hidden: false,
    })
  }
  (VStruct({ fields, patterns: [], is_closed: false, embed: None, }), i)
}

///|
fn find_yaml_colon(s : String) -> Int32 {
  let chars = s.to_array()
  let mut in_single = false
  let mut in_double = false
  let mut brace_depth = 0
  let mut brack_depth = 0
  for i = 0; i < chars.length(); i = i + 1 {
    let c = chars[i]
    if c == '\'' && !in_double {
      in_single = !in_single
    } else if c == '"' && !in_single {
      if i == 0 || chars[i - 1] != '\\' {
        in_double = !in_double
      }
    } else if !in_single && !in_double {
      if c == '{' {
        brace_depth += 1
      } else if c == '}' && brace_depth > 0 {
        brace_depth -= 1
      } else if c == '[' {
        brack_depth += 1
      } else if c == ']' && brack_depth > 0 {
        brack_depth -= 1
      } else if c == ':' && brace_depth == 0 && brack_depth == 0 {
        if i + 1 == chars.length() ||
          chars[i + 1] == ' ' ||
          chars[i + 1] == '\t' {
          return i
        }
      }
    }
  }
  -1
}

///|
fn unquote_yaml_string(s : String) -> String {
  if s.length() >= 2 && s.has_prefix("\"") && s.has_suffix("\"") {
    let parsed : Result[Json, Error] = Ok(@json.parse(s)) catch { e => Err(e) }
    match parsed {
      Ok(String(unq)) => return unq
      _ => return s.clamped_view(start=1, end=s.length() - 1).to_owned()
    }
  }
  if s.length() >= 2 && s.has_prefix("'") && s.has_suffix("'") {
    return s.clamped_view(start=1, end=s.length() - 1).to_owned()
  }
  s
}

///|
fn split_yaml_flow_items(inner : String) -> Array[String] raise CueError {
  let chars = inner.to_array()
  let items : Array[String] = []
  let cur = StringBuilder()
  let mut in_single = false
  let mut in_double = false
  let mut brace_depth = 0
  let mut brack_depth = 0
  for i = 0; i < chars.length(); i = i + 1 {
    let c = chars[i]
    if c == '\'' && !in_double {
      in_single = !in_single
      cur.write_char(c)
    } else if c == '"' && !in_single {
      if i == 0 || chars[i - 1] != '\\' {
        in_double = !in_double
      }
      cur.write_char(c)
    } else if !in_single && !in_double {
      if c == '{' {
        brace_depth += 1
        cur.write_char(c)
      } else if c == '}' {
        brace_depth -= 1
        cur.write_char(c)
      } else if c == '[' {
        brack_depth += 1
        cur.write_char(c)
      } else if c == ']' {
        brack_depth -= 1
        cur.write_char(c)
      } else if c == ',' && brace_depth == 0 && brack_depth == 0 {
        items.push(cur.to_string().trim().to_owned())
        cur.reset()
      } else {
        cur.write_char(c)
      }
    } else {
      cur.write_char(c)
    }
  }
  if in_single || in_double || brace_depth != 0 || brack_depth != 0 {
    raise CueError::new(YamlError, "unterminated flow collection")
  }
  let tail = cur.to_string().trim().to_owned()
  if !tail.is_empty() {
    items.push(tail)
  }
  items
}

///|
fn parse_yaml_scalar(s : String, line_no : Int32) -> Value raise CueError {
  if s.has_prefix("[") {
    if !s.has_suffix("]") {
      raise CueError::new(
        YamlError,
        "unterminated flow sequence '\{s}' at line \{line_no}",
      )
    }
    let inner = s
      .clamped_view(start=1, end=s.length() - 1)
      .to_owned()
      .trim()
      .to_owned()
    if inner.is_empty() {
      return VList({ elems: [], open_tail: None, })
    }
    let parts = split_yaml_flow_items(inner)
    let elems : Array[Value] = []
    for p in parts {
      elems.push(parse_yaml_scalar(p, line_no))
    }
    return VList({ elems, open_tail: None, })
  }
  if s.has_prefix("{") {
    if !s.has_suffix("}") {
      raise CueError::new(
        YamlError,
        "unterminated flow mapping '\{s}' at line \{line_no}",
      )
    }
    let inner = s
      .clamped_view(start=1, end=s.length() - 1)
      .to_owned()
      .trim()
      .to_owned()
    if inner.is_empty() {
      return VStruct(StructVal::empty())
    }
    let parts = split_yaml_flow_items(inner)
    let fields : Array[StructField] = []
    for p in parts {
      let colon = find_yaml_colon(p)
      if colon < 0 {
        raise CueError::new(
          YamlError,
          "expected 'key: value' in flow mapping at line \{line_no}",
        )
      }
      let k = unquote_yaml_string(
        p.clamped_view(start=0, end=colon).to_owned().trim().to_owned(),
      )
      let v_str = p.clamped_view(start=colon + 1).to_owned().trim().to_owned()
      let v = parse_yaml_scalar(v_str, line_no)
      fields.push({
        name: k,
        value: v,
        constraint: Regular,
        is_definition: false,
        is_hidden: false,
      })
    }
    return VStruct({ fields, patterns: [], is_closed: false, embed: None, })
  }
  if (s.has_prefix("\"") && s.has_suffix("\"")) ||
    (s.has_prefix("'") && s.has_suffix("'")) {
    return VString(unquote_yaml_string(s))
  }
  match s {
    "null" | "Null" | "NULL" | "~" => VNull
    "true" | "True" | "TRUE" => VBool(true)
    "false" | "False" | "FALSE" => VBool(false)
    _ => {
      let as_int : Result[Int64, Error] = Ok(@string.parse_int64(s)) catch {
        e => Err(e)
      }
      match as_int {
        Ok(i) => VInt(i)
        Err(_) => {
          let as_dbl : Result[Double, Error] = Ok(@string.parse_double(s)) catch {
            e => Err(e)
          }
          match as_dbl {
            Ok(d) => VFloat(d)
            Err(_) => VString(s)
          }
        }
      }
    }
  }
}