///|
/// The severity of a diagnostic.
///
/// ```mbt check
/// test {
///   assert_eq(KdlSeverity::Error, KdlSeverity::Error)
///   assert_eq(KdlSeverity::Warning, KdlSeverity::Warning)
/// }
/// ```
pub(all) enum KdlSeverity {
  Error
  Warning
} derive(Eq, Debug)

///|
/// One diagnostic: a source span, message, optional label and help, and a
/// severity.
///
/// ```mbt check
/// test {
///   let d = KdlDiagnostic::new(
///     "a b",
///     0,
///     1,
///     Some("boom"),
///     None,
///     None,
///     KdlSeverity::Error,
///   )
///   assert_eq(d.message, Some("boom"))
///   assert_eq(d.severity, KdlSeverity::Error)
/// }
/// ```
pub struct KdlDiagnostic {
  input : String
  span_start : Int
  span_len : Int
  message : String?
  label : String?
  help : String?
  severity : KdlSeverity
} derive(Eq, Debug)

///|
/// Build a diagnostic with a source span, message and severity.
///
/// ```mbt check
/// test {
///   let d = KdlDiagnostic::new(
///     "a b",
///     0,
///     1,
///     Some("boom"),
///     None,
///     Some("try again"),
///     KdlSeverity::Error,
///   )
///   assert_eq(d.message, Some("boom"))
///   assert_eq(d.help, Some("try again"))
///   assert_eq(d.severity, KdlSeverity::Error)
/// }
/// ```
pub fn KdlDiagnostic::new(
  input : String,
  span_start : Int,
  span_len : Int,
  message : String?,
  label : String?,
  help : String?,
  severity : KdlSeverity,
) -> KdlDiagnostic {
  { input, span_start, span_len, message, label, help, severity }
}

///|
/// A collection of diagnostics produced by parsing or validation.
///
/// ```mbt check
/// test {
///   let e = KdlError::new("x")
///   e.push(
///     KdlDiagnostic::new("x", 0, 1, Some("boom"), None, None, KdlSeverity::Error),
///   )
///   assert_false(e.is_empty())
/// }
/// ```
pub struct KdlError {
  input : String
  diagnostics : Array[KdlDiagnostic]
} derive(Eq, Debug)

///|
/// An error with no diagnostics yet.
///
/// ```mbt check
/// test {
///   let e = KdlError::new("input")
///   assert_true(e.is_empty())
/// }
/// ```
pub fn KdlError::new(input : String) -> KdlError {
  { input, diagnostics: [] }
}

///|
/// Append a diagnostic to this error.
///
/// ```mbt check
/// test {
///   let e = KdlError::new("x")
///   e.push(
///     KdlDiagnostic::new("x", 0, 1, Some("boom"), None, None, KdlSeverity::Error),
///   )
///   assert_false(e.is_empty())
/// }
/// ```
pub fn KdlError::push(self : KdlError, diag : KdlDiagnostic) -> Unit {
  self.diagnostics.push(diag)
}

///|
/// Whether this error holds no diagnostics.
///
/// ```mbt check
/// test {
///   let e = KdlError::new("x")
///   assert_true(e.is_empty())
///   e.push(
///     KdlDiagnostic::new("x", 0, 1, Some("boom"), None, None, KdlSeverity::Error),
///   )
///   assert_false(e.is_empty())
/// }
/// ```
pub fn KdlError::is_empty(self : KdlError) -> Bool {
  self.diagnostics.length() == 0
}

///|
fn clamp_int(v : Int, lo : Int, hi : Int) -> Int {
  if v < lo {
    lo
  } else if v > hi {
    hi
  } else {
    v
  }
}

///|
fn severity_name(sev : KdlSeverity) -> String {
  match sev {
    Error => "error"
    Warning => "warning"
  }
}

///|
fn is_newline_unit(u : Int) -> Bool {
  u == 10
}

///|
/// 1-based (line, col) for a UTF-16 code-unit offset into `input`.
/// Out-of-range offsets are clamped into the string.
fn line_col_at(input : String, offset : Int) -> (Int, Int) {
  let mut line = 1
  let mut line_start = 0
  let n = input.length()
  let clamped = clamp_int(offset, 0, n)
  for i in 0.. Array[(Int, Int, Int, Int, Int)] {
  let result : Array[(Int, Int, Int, Int, Int)] = []
  let n = input.length()
  let mut line_no = 1
  let mut line_start = 0
  for i in 0.. line_start &&
      input.code_unit_at(line_end - 1).to_int() == 13 {
      line_end - 1
    } else {
      line_end
    }
    let caret_start = if start > line_start { start } else { line_start }
    let caret_end = if end < display_end { end } else { display_end }
    let caret_col = caret_start - line_start + 1
    let caret_width = if caret_end > caret_start {
      caret_end - caret_start
    } else {
      1
    }
    result.push((line_no, line_start, display_end, caret_col, caret_width))
    if line_end >= end {
      break
    }
    line_no = line_no + 1
    line_start = line_end + 1
  }
  result
}

///|
/// Render this diagnostic as a miette-style human-readable report:
/// severity + message, line/column, the offending source line(s) with a caret
/// under the span, an optional label annotation and optional help text.
///
/// ```text
/// error: unexpected `=` inside a children block
///   --> line 1, col 9
///    |
///  1 | server { host="a" }
///    |         ^
/// ```
///
/// The label is appended after the caret when present (the parser's constant
/// `"here"` label is omitted as redundant). When the diagnostic has no source
/// text (`input` is empty) only the header — plus help, if any — is rendered.
///
/// ```mbt check
/// test {
///   let d = KdlDiagnostic::new(
///     "a b",
///     2,
///     1,
///     Some("boom"),
///     None,
///     Some("try again"),
///     KdlSeverity::Error,
///   )
///   let out = d.to_display_string()
///   assert_true(out.contains("boom"))
///   assert_true(out.contains("try again"))
/// }
/// ```
pub fn KdlDiagnostic::to_display_string(self : KdlDiagnostic) -> String {
  let input = self.input
  let start = clamp_int(self.span_start, 0, input.length())
  let len = if self.span_len < 0 { 0 } else { self.span_len }
  let n = input.length()
  let end = if start + len > n { n } else { start + len }
  let text = match self.message {
    Some(m) => m
    None => self.label.unwrap_or("unknown error")
  }
  let sb = StringBuilder::new()
  sb.write_string(severity_name(self.severity))
  sb.write_string(": ")
  sb.write_string(text)
  if input.is_empty() {
    match self.help {
      Some(h) => {
        sb.write_string("\n  = help: ")
        sb.write_string(h)
      }
      None => ()
    }
    return sb.to_string()
  }
  let (start_line, start_col) = line_col_at(input, start)
  sb.write_string("\n  --> line ")
  sb.write_string(start_line.to_string())
  sb.write_string(", col ")
  sb.write_string(start_col.to_string())
  sb.write_string("\n")
  let lines = span_lines(input, start, end)
  let mut gutter_width = 0
  for line in lines {
    let (line_no, _, _, _, _) = line
    let w = line_no.to_string().length()
    if w > gutter_width {
      gutter_width = w
    }
  }
  sb.write_string(" ".repeat(gutter_width + 2))
  sb.write_string("|\n")
  let mut first_line = true
  for line in lines {
    let (line_no, line_start, line_end, caret_col, caret_width) = line
    if !first_line {
      sb.write_string("\n")
    }
    first_line = false
    let num = line_no.to_string()
    sb.write_string(" ")
    sb.write_string(" ".repeat(gutter_width - num.length()))
    sb.write_string(num)
    sb.write_string(" | ")
    let raw_line = input[line_start:line_end].to_owned()
    sb.write_string(raw_line.replace(old="\t", new=" "))
    sb.write_string("\n")
    sb.write_string(" ")
    sb.write_string(" ".repeat(gutter_width))
    sb.write_string(" | ")
    sb.write_string(" ".repeat(caret_col - 1))
    sb.write_string("^".repeat(caret_width))
    match self.label {
      Some(l) =>
        if l != "here" {
          sb.write_string(" ")
          sb.write_string(l)
        }
      None => ()
    }
  }
  match self.help {
    Some(h) => {
      sb.write_string("\n  = help: ")
      sb.write_string(h)
    }
    None => ()
  }
  sb.to_string()
}

///|
/// Render every diagnostic as a miette-style human-readable report, one after
/// the other (separated by a blank line). Returns the empty string when there
/// are no diagnostics.
///
/// ```text
/// error: unexpected `=` inside a children block
///   --> line 1, col 9
///    |
///  1 | server { host="a" }
///    |         ^
/// ```
///
/// ```mbt check
/// test {
///   let e = KdlError::new("a b")
///   e.push(
///     KdlDiagnostic::new(
///       "a b",
///       0,
///       1,
///       Some("first"),
///       None,
///       None,
///       KdlSeverity::Error,
///     ),
///   )
///   e.push(
///     KdlDiagnostic::new(
///       "a b",
///       2,
///       1,
///       Some("second"),
///       None,
///       None,
///       KdlSeverity::Error,
///     ),
///   )
///   let out = e.to_display_string()
///   assert_true(out.contains("first"))
///   assert_true(out.contains("second"))
/// }
/// ```
pub fn KdlError::to_display_string(self : KdlError) -> String {
  if self.diagnostics.is_empty() {
    return ""
  }
  let sb = StringBuilder::new()
  let mut first = true
  for diag in self.diagnostics {
    if !first {
      sb.write_string("\n\n")
    }
    first = false
    sb.write_string(diag.to_display_string())
  }
  sb.to_string()
}