///|
/// Values that can render themselves to HTML strings.
///
/// Generated template implementations use this trait so callers can render
/// pages with `page.render()`. The method allows `raise` because template code
/// can call ordinary MoonBit functions that use checked errors. User-defined
/// page structs normally receive their implementation from `template_codegen`.
pub(open) trait Render {
  fn render(Self) -> String raise
}

///|
/// Error values reserved for render-time failures.
///
/// The current generator mostly reports parse and codegen problems before
/// rendering, but this error type gives runtime integrations a stable place for
/// checked failures such as invalid dynamic includes.
#derive(Eq, Debug)
pub(all) suberror RenderError {
  Message(String)
  InvalidInclude(String)
}

///|
pub extend RenderError with Eq::{equal, not_equal}

///|
pub extend RenderError with @debug.Debug::{to_repr}

///|
/// HTML that has already been validated by the caller.
///
/// `SafeHtml` is the trust boundary for raw output. Generated templates escape
/// ordinary values by default; wrapping a string in this type documents that the
/// caller intentionally wants the markup written without escaping.
pub struct SafeHtml {
  value : String
}

///|
/// Wraps trusted HTML so it can be passed through raw template output.
///
/// Prefer constructing this value near the code that validates or produces the
/// markup, so the trust decision remains visible at the call site.
pub fn SafeHtml::new(value : String) -> SafeHtml {
  { value, }
}

///|
/// Returns the trusted HTML payload without escaping it.
///
/// This is useful when adapting `SafeHtml` to another renderer or writing tests
/// that need to inspect the exact trusted markup.
pub fn SafeHtml::to_string(self : SafeHtml) -> String {
  self.value
}

///|
/// Creates a trusted HTML wrapper.
///
/// This convenience constructor is equivalent to `SafeHtml::new(value)` and is
/// exported for template-facing code that prefers function-style helpers.
pub fn safe_html(value : String) -> SafeHtml {
  SafeHtml::new(value)
}

///|
/// Writes trusted HTML as-is when interpolated or rendered as a raw value.
pub impl Show for SafeHtml with fn output(self, logger) {
  logger.write_string(self.value)
}

///|
pub extend SafeHtml with Show::{output}

///|
/// Formats a value the same way MoonBit string interpolation does.
///
/// Generated templates call this for expression output before applying the
/// escaped or raw write path, so any type with a `Show` implementation can be
/// rendered consistently.
///
/// `Show::to_string` is the same entry point string interpolation uses, but
/// calling it directly lets types that override it — `String` in particular —
/// return their existing value instead of allocating a formatted copy.
pub fn[T : Show] render_value(value : T) -> String {
  value.to_string()
}

///|
/// The escape classifications returned by `classify_escape`.
///
/// A payload-free enum keeps the scan allocation-free, and the escaped
/// characters are all ASCII, so code units at or above `128` are classified
/// without being decoded into a `Char`. The scan therefore never touches
/// surrogate pairs.
priv enum Escape {
  Plain
  Amp
  Lt
  Gt
  Quot
  Apos
}

///|
/// Classifies one UTF-16 code unit for HTML escaping.
#inline
fn classify_escape(code : UInt16) -> Escape {
  if code.to_int() < 128 {
    match code.unsafe_to_char() {
      '&' => Amp
      '<' => Lt
      '>' => Gt
      '"' => Quot
      '\'' => Apos
      _ => Plain
    }
  } else {
    Plain
  }
}

///|
/// Returns the offset of the first code unit that needs escaping.
///
/// The result is the string length when nothing needs escaping, which lets
/// `escape_html` return the input unchanged after a single scan.
fn first_escape(value : String) -> Int32 {
  let len = value.length()
  let mut offset = 0
  let mut scanning = true
  while offset < len && scanning {
    match classify_escape(value.unsafe_get(offset)) {
      Plain => offset = offset + 1
      _ => scanning = false
    }
  }
  offset
}

///|
/// Appends `value` to `out` starting at `start`, escaping as it goes.
///
/// `[0, start)` must already be plain: the caller either wrote it itself or
/// proved it needs no escaping, which is what lets `escape_html` skip a second
/// scan. Runs between escapable characters are copied as views, so this path
/// neither builds intermediate strings nor decodes characters: the code-unit
/// scan can never split a surrogate pair, and the blit copies whole runs.
fn write_escaped_from(
  out : StringBuilder,
  value : String,
  start : Int32,
) -> Unit {
  let len = value.length()
  let mut copied = 0
  for offset = start; offset < len; offset = offset + 1 {
    let entity = match classify_escape(value.unsafe_get(offset)) {
      Plain => ""
      Amp => "&"
      Lt => "<"
      Gt => ">"
      Quot => """
      Apos => "'"
    }
    if !entity.is_empty() {
      if copied < offset {
        out.write_stringview(value.unsafe_view(start=copied, end=offset))
      }
      out.write_string(entity)
      copied = offset + 1
    }
  }
  if copied < len {
    out.write_stringview(value.unsafe_view(start=copied, end=len))
  }
}

///|
/// Escapes the HTML-sensitive characters `&`, `<`, `>`, `"`, and `'`.
///
/// The returned string is safe to place in normal HTML text positions produced
/// by templates. Raw output must be requested explicitly through template syntax
/// or by rendering trusted `SafeHtml`.
///
/// Strings that contain none of those characters are returned unchanged instead
/// of being copied, which is the common case for template data. MoonBit strings
/// are immutable, so sharing the input is safe.
pub fn escape_html(value : String) -> String {
  let first = first_escape(value)
  if first == value.length() {
    return value
  }
  let out = StringBuilder(capacity=value.length() + 8)
  write_escaped_from(out, value, first)
  out.to_string()
}

///|
/// Writes raw text into a template output buffer without escaping it.
///
/// Generated renderers use this path for trusted content and raw template
/// expressions. Prefer `write_escaped` for ordinary user-provided strings.
pub fn write_raw(out : StringBuilder, value : String) -> Unit {
  out.write_string(value)
}

///|
/// Escapes text and writes it into a template output buffer.
///
/// This is the default output path for generated escaped expressions such as
/// `<%= value %>`. Escaping happens while writing, so no intermediate escaped
/// string is allocated.
pub fn write_escaped(out : StringBuilder, value : String) -> Unit {
  write_escaped_from(out, value, 0)
}