use crate::models::{MentorMessage, Severity};
pub const BOX_WIDTH: usize = 60;
const INNER_WIDTH: usize = BOX_WIDTH - 4;
const BODY_INDENT: usize = 4;
const TOP_LEFT: char = '┌';
const TOP_RIGHT: char = '┐';
const BOTTOM_LEFT: char = '└';
const BOTTOM_RIGHT: char = '┘';
const HORIZONTAL: char = '─';
const VERTICAL: char = '│';
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Palette {
pub info: &'static str,
pub warning: &'static str,
pub critical: &'static str,
pub reset: &'static str,
}
pub const PALETTE: Palette = Palette {
info: "\x1b[94m",
warning: "\x1b[33m",
critical: "\x1b[91m",
reset: "\x1b[0m",
};
pub fn accent_for(severity: Severity) -> &'static str {
match severity {
Severity::Info => PALETTE.info,
Severity::Warning => PALETTE.warning,
Severity::Critical => PALETTE.critical,
}
}
pub fn note_emoji(severity: Severity) -> &'static str {
match severity {
Severity::Info => "💡",
Severity::Warning => "⚠️",
Severity::Critical => "🚨",
}
}
pub fn action_emoji(severity: Severity) -> &'static str {
match severity {
Severity::Info => "✅",
Severity::Warning => "⚡",
Severity::Critical => "🚨",
}
}
pub fn action_label(severity: Severity) -> &'static str {
match severity {
Severity::Info => "Next step:",
Severity::Warning => "Quick action:",
Severity::Critical => "URGENT ACTION REQUIRED:",
}
}
pub fn format_mentor_message(msg: &MentorMessage) -> String {
render_box(msg, true)
}
pub fn format_mentor_message_plain(msg: &MentorMessage) -> String {
render_box(msg, false)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowKind {
Border,
Heading,
Body,
}
fn render_box(msg: &MentorMessage, colored: bool) -> String {
let severity = msg.severity;
let accent = accent_for(severity);
let header_lines = wrap(
&format!(
"{} MENTOR NOTE: {}",
note_emoji(severity),
msg.plain_english
),
INNER_WIDTH,
);
let mut rows: Vec<(RowKind, String)> = Vec::new();
rows.push((RowKind::Border, border_line(TOP_LEFT, TOP_RIGHT)));
for line in header_lines {
rows.push((RowKind::Heading, content_line(&line)));
}
rows.push((RowKind::Body, content_line("")));
rows.push((RowKind::Heading, content_line("📋 Why this matters:")));
for line in wrap_indented(&msg.technical_detail) {
rows.push((RowKind::Body, content_line(&line)));
}
rows.push((RowKind::Body, content_line("")));
rows.push((
RowKind::Heading,
content_line(&format!(
"{} {}",
action_emoji(severity),
action_label(severity)
)),
));
for line in wrap_indented(&msg.suggested_action) {
rows.push((RowKind::Body, content_line(&line)));
}
rows.push((RowKind::Border, border_line(BOTTOM_LEFT, BOTTOM_RIGHT)));
let mut out = String::new();
for (kind, line) in rows {
let rendered = if colored && kind != RowKind::Body {
format!("{accent}{line}{}", PALETTE.reset)
} else {
line
};
out.push_str(&rendered);
out.push('\n');
}
out
}
fn border_line(left: char, right: char) -> String {
let mut line = String::new();
line.push(left);
for _ in 0..(BOX_WIDTH - 2) {
line.push(HORIZONTAL);
}
line.push(right);
line
}
fn content_line(content: &str) -> String {
format!("{VERTICAL} {content:<INNER_WIDTH$} {VERTICAL}")
}
fn wrap_indented(text: &str) -> Vec<String> {
let width = INNER_WIDTH - BODY_INDENT;
wrap(text, width)
.into_iter()
.map(|line| format!("{}{line}", " ".repeat(BODY_INDENT)))
.collect()
}
fn wrap(text: &str, width: usize) -> Vec<String> {
if text.is_empty() || width == 0 {
return vec![String::new()];
}
let mut lines = Vec::new();
let mut current = String::new();
for word in text.split(' ') {
let word_len = word.chars().count();
if word_len == 0 {
continue;
}
if word_len > width {
if !current.is_empty() {
lines.push(std::mem::take(&mut current));
}
let mut chunk = String::new();
for ch in word.chars() {
if chunk.chars().count() == width {
lines.push(std::mem::take(&mut chunk));
}
chunk.push(ch);
}
current = chunk;
} else if current.is_empty() {
current.push_str(word);
} else if current.chars().count() + 1 + word_len <= width {
current.push(' ');
current.push_str(word);
} else {
lines.push(std::mem::take(&mut current));
current.push_str(word);
}
}
if !current.is_empty() {
lines.push(current);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
fn msg(severity: Severity) -> MentorMessage {
MentorMessage {
severity,
plain_english: "Node is ready.".into(),
technical_detail: "Runtime v22.9.0 detected.".into(),
suggested_action: "None.".into(),
}
}
#[test]
fn info_box_renders_exact_plain_output() {
let pad = |content: &str| {
format!(
"{content}{}",
" ".repeat(INNER_WIDTH - content.chars().count())
)
};
let row = |content: String| format!("│ {content} │");
let border =
|left: char, right: char| format!("{left}{}{right}", "─".repeat(BOX_WIDTH - 2));
let expected = format!(
"{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n",
border(TOP_LEFT, TOP_RIGHT),
row(pad("💡 MENTOR NOTE: Node is ready.")),
row(pad("")),
row(pad("📋 Why this matters:")),
row(pad(" Runtime v22.9.0 detected.")),
row(pad("")),
row(pad("✅ Next step:")),
row(pad(" None.")),
border(BOTTOM_LEFT, BOTTOM_RIGHT),
);
assert_eq!(format_mentor_message_plain(&msg(Severity::Info)), expected);
}
#[test]
fn warning_box_uses_quick_action_label() {
let out = format_mentor_message_plain(&msg(Severity::Warning));
assert!(out.contains("⚠️ MENTOR NOTE:"));
assert!(out.contains("⚡ Quick action:"));
assert!(!out.contains("URGENT ACTION REQUIRED:"));
}
#[test]
fn critical_box_marks_action_as_urgent() {
let out = format_mentor_message_plain(&msg(Severity::Critical));
assert!(out.contains("🚨 MENTOR NOTE:"));
assert!(out.contains("🚨 URGENT ACTION REQUIRED:"));
}
#[test]
fn every_plain_line_is_exactly_box_width() {
for severity in [Severity::Info, Severity::Warning, Severity::Critical] {
let out = format_mentor_message_plain(&msg(severity));
for line in out.lines() {
assert_eq!(line.chars().count(), BOX_WIDTH);
}
assert!(!out.contains('\x1b'));
}
}
#[test]
fn colored_output_uses_muted_ansi_palette() {
let info = format_mentor_message(&msg(Severity::Info));
assert!(info.contains(accent_for(Severity::Info)));
assert!(info.contains(PALETTE.reset));
let warning = format_mentor_message(&msg(Severity::Warning));
assert!(warning.contains(accent_for(Severity::Warning)));
assert!(warning.contains(PALETTE.reset));
let critical = format_mentor_message(&msg(Severity::Critical));
assert!(critical.contains(accent_for(Severity::Critical)));
assert!(critical.contains(PALETTE.reset));
}
#[test]
fn long_messages_wrap_within_box() {
let long = MentorMessage {
severity: Severity::Info,
plain_english: "The npm package manager was not found on your PATH, which means the install command cannot resolve it.".into(),
technical_detail: "Neither `npm` nor `npx` resolve to an executable under any of the configured PATH entries.".into(),
suggested_action: "Run `npm install -g node` or reinstall Node and then restart your terminal before trying again.".into(),
};
let plain = format_mentor_message_plain(&long);
assert!(plain.lines().count() > 9, "wrapping should add rows");
for line in plain.lines() {
assert_eq!(line.chars().count(), BOX_WIDTH);
}
assert!(plain.contains("📋 Why this matters:"));
assert!(plain.contains("Next step:"));
}
#[test]
fn wrap_respects_width() {
let text = "one two three four five";
assert_eq!(
wrap(text, 10),
vec![
"one two".to_string(),
"three four".to_string(),
"five".to_string(),
]
);
}
#[test]
fn wrap_hard_splits_overlong_words() {
assert_eq!(
wrap("abcdefghijk", 4),
vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string(),]
);
}
#[test]
fn wrap_collapses_multiple_spaces() {
assert_eq!(wrap("a b", 10), vec!["a b".to_string()]);
}
#[test]
fn wrap_empty_and_width_zero() {
assert_eq!(wrap("", 10), vec![String::new()]);
assert_eq!(wrap("abc", 0), vec![String::new()]);
}
#[test]
fn indented_body_stays_within_inner_width() {
let lines = wrap_indented("Short body.");
assert_eq!(lines[0], " Short body.");
assert!(lines.iter().all(|l| l.chars().count() <= INNER_WIDTH));
}
#[test]
fn palette_values_are_exact_ansi_codes() {
assert_eq!(PALETTE.info, "\x1b[94m");
assert_eq!(PALETTE.warning, "\x1b[33m");
assert_eq!(PALETTE.critical, "\x1b[91m");
assert_eq!(PALETTE.reset, "\x1b[0m");
}
#[test]
fn test_mentor_message_formatting() {
let msg = MentorMessage {
severity: Severity::Warning,
plain_english: "Port 3000 is jammed.".to_string(),
technical_detail: "EADDRINUSE".to_string(),
suggested_action: "Free the port, then retry".to_string(),
};
let plain = format_mentor_message_plain(&msg);
assert!(!plain.contains("\x1b["), "plain output must have no ANSI");
assert!(plain.contains("Port 3000 is jammed."));
assert!(plain.contains("EADDRINUSE"));
assert!(plain.contains("Free the port, then retry"));
assert!(plain.contains("MENTOR NOTE:"), "severity label should be rendered");
let colored = format_mentor_message(&msg);
assert!(colored.contains("\x1b["), "colored output must use ANSI");
assert!(colored.contains("Port 3000 is jammed."));
}
}