1use crate::models::{MentorMessage, Severity};
39
40pub const BOX_WIDTH: usize = 60;
44
45const INNER_WIDTH: usize = BOX_WIDTH - 4;
47
48const BODY_INDENT: usize = 4;
50
51const TOP_LEFT: char = '┌';
53const TOP_RIGHT: char = '┐';
54
55const BOTTOM_LEFT: char = '└';
57const BOTTOM_RIGHT: char = '┘';
58
59const HORIZONTAL: char = '─';
61const VERTICAL: char = '│';
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct Palette {
72 pub info: &'static str,
74 pub warning: &'static str,
76 pub critical: &'static str,
78 pub reset: &'static str,
80}
81
82pub const PALETTE: Palette = Palette {
84 info: "\x1b[94m",
85 warning: "\x1b[33m",
86 critical: "\x1b[91m",
87 reset: "\x1b[0m",
88};
89
90pub fn accent_for(severity: Severity) -> &'static str {
101 match severity {
102 Severity::Info => PALETTE.info,
103 Severity::Warning => PALETTE.warning,
104 Severity::Critical => PALETTE.critical,
105 }
106}
107
108pub fn note_emoji(severity: Severity) -> &'static str {
118 match severity {
119 Severity::Info => "💡",
120 Severity::Warning => "⚠️",
121 Severity::Critical => "🚨",
122 }
123}
124
125pub fn action_emoji(severity: Severity) -> &'static str {
136 match severity {
137 Severity::Info => "✅",
138 Severity::Warning => "⚡",
139 Severity::Critical => "🚨",
140 }
141}
142
143pub fn action_label(severity: Severity) -> &'static str {
156 match severity {
157 Severity::Info => "Next step:",
158 Severity::Warning => "Quick action:",
159 Severity::Critical => "URGENT ACTION REQUIRED:",
160 }
161}
162
163pub fn format_mentor_message(msg: &MentorMessage) -> String {
168 render_box(msg, true)
169}
170
171pub fn format_mentor_message_plain(msg: &MentorMessage) -> String {
175 render_box(msg, false)
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180enum RowKind {
181 Border,
182 Heading,
183 Body,
184}
185
186fn render_box(msg: &MentorMessage, colored: bool) -> String {
187 let severity = msg.severity;
188 let accent = accent_for(severity);
189
190 let header_lines = wrap(
191 &format!(
192 "{} MENTOR NOTE: {}",
193 note_emoji(severity),
194 msg.plain_english
195 ),
196 INNER_WIDTH,
197 );
198
199 let mut rows: Vec<(RowKind, String)> = Vec::new();
200 rows.push((RowKind::Border, border_line(TOP_LEFT, TOP_RIGHT)));
201 for line in header_lines {
202 rows.push((RowKind::Heading, content_line(&line)));
203 }
204 rows.push((RowKind::Body, content_line("")));
205 rows.push((RowKind::Heading, content_line("📋 Why this matters:")));
206 for line in wrap_indented(&msg.technical_detail) {
207 rows.push((RowKind::Body, content_line(&line)));
208 }
209 rows.push((RowKind::Body, content_line("")));
210 rows.push((
211 RowKind::Heading,
212 content_line(&format!(
213 "{} {}",
214 action_emoji(severity),
215 action_label(severity)
216 )),
217 ));
218 for line in wrap_indented(&msg.suggested_action) {
219 rows.push((RowKind::Body, content_line(&line)));
220 }
221 rows.push((RowKind::Border, border_line(BOTTOM_LEFT, BOTTOM_RIGHT)));
222
223 let mut out = String::new();
224 for (kind, line) in rows {
225 let rendered = if colored && kind != RowKind::Body {
226 format!("{accent}{line}{}", PALETTE.reset)
227 } else {
228 line
229 };
230 out.push_str(&rendered);
231 out.push('\n');
232 }
233 out
234}
235
236fn border_line(left: char, right: char) -> String {
238 let mut line = String::new();
239 line.push(left);
240 for _ in 0..(BOX_WIDTH - 2) {
241 line.push(HORIZONTAL);
242 }
243 line.push(right);
244 line
245}
246
247fn content_line(content: &str) -> String {
249 format!("{VERTICAL} {content:<INNER_WIDTH$} {VERTICAL}")
250}
251
252fn wrap_indented(text: &str) -> Vec<String> {
254 let width = INNER_WIDTH - BODY_INDENT;
255 wrap(text, width)
256 .into_iter()
257 .map(|line| format!("{}{line}", " ".repeat(BODY_INDENT)))
258 .collect()
259}
260
261fn wrap(text: &str, width: usize) -> Vec<String> {
266 if text.is_empty() || width == 0 {
267 return vec![String::new()];
268 }
269
270 let mut lines = Vec::new();
271 let mut current = String::new();
272
273 for word in text.split(' ') {
274 let word_len = word.chars().count();
275 if word_len == 0 {
276 continue;
277 }
278 if word_len > width {
279 if !current.is_empty() {
280 lines.push(std::mem::take(&mut current));
281 }
282 let mut chunk = String::new();
283 for ch in word.chars() {
284 if chunk.chars().count() == width {
285 lines.push(std::mem::take(&mut chunk));
286 }
287 chunk.push(ch);
288 }
289 current = chunk;
290 } else if current.is_empty() {
291 current.push_str(word);
292 } else if current.chars().count() + 1 + word_len <= width {
293 current.push(' ');
294 current.push_str(word);
295 } else {
296 lines.push(std::mem::take(&mut current));
297 current.push_str(word);
298 }
299 }
300
301 if !current.is_empty() {
302 lines.push(current);
303 }
304 if lines.is_empty() {
305 lines.push(String::new());
306 }
307 lines
308}
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313
314 fn msg(severity: Severity) -> MentorMessage {
315 MentorMessage {
316 severity,
317 plain_english: "Node is ready.".into(),
318 technical_detail: "Runtime v22.9.0 detected.".into(),
319 suggested_action: "None.".into(),
320 }
321 }
322
323 #[test]
324 fn info_box_renders_exact_plain_output() {
325 let pad = |content: &str| {
326 format!(
327 "{content}{}",
328 " ".repeat(INNER_WIDTH - content.chars().count())
329 )
330 };
331 let row = |content: String| format!("│ {content} │");
332 let border =
333 |left: char, right: char| format!("{left}{}{right}", "─".repeat(BOX_WIDTH - 2));
334
335 let expected = format!(
336 "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n",
337 border(TOP_LEFT, TOP_RIGHT),
338 row(pad("💡 MENTOR NOTE: Node is ready.")),
339 row(pad("")),
340 row(pad("📋 Why this matters:")),
341 row(pad(" Runtime v22.9.0 detected.")),
342 row(pad("")),
343 row(pad("✅ Next step:")),
344 row(pad(" None.")),
345 border(BOTTOM_LEFT, BOTTOM_RIGHT),
346 );
347 assert_eq!(format_mentor_message_plain(&msg(Severity::Info)), expected);
348 }
349
350 #[test]
351 fn warning_box_uses_quick_action_label() {
352 let out = format_mentor_message_plain(&msg(Severity::Warning));
353 assert!(out.contains("⚠️ MENTOR NOTE:"));
354 assert!(out.contains("⚡ Quick action:"));
355 assert!(!out.contains("URGENT ACTION REQUIRED:"));
356 }
357
358 #[test]
359 fn critical_box_marks_action_as_urgent() {
360 let out = format_mentor_message_plain(&msg(Severity::Critical));
361 assert!(out.contains("🚨 MENTOR NOTE:"));
362 assert!(out.contains("🚨 URGENT ACTION REQUIRED:"));
363 }
364
365 #[test]
366 fn every_plain_line_is_exactly_box_width() {
367 for severity in [Severity::Info, Severity::Warning, Severity::Critical] {
368 let out = format_mentor_message_plain(&msg(severity));
369 for line in out.lines() {
370 assert_eq!(line.chars().count(), BOX_WIDTH);
371 }
372 assert!(!out.contains('\x1b'));
373 }
374 }
375
376 #[test]
377 fn colored_output_uses_muted_ansi_palette() {
378 let info = format_mentor_message(&msg(Severity::Info));
379 assert!(info.contains(accent_for(Severity::Info)));
380 assert!(info.contains(PALETTE.reset));
381
382 let warning = format_mentor_message(&msg(Severity::Warning));
383 assert!(warning.contains(accent_for(Severity::Warning)));
384 assert!(warning.contains(PALETTE.reset));
385
386 let critical = format_mentor_message(&msg(Severity::Critical));
387 assert!(critical.contains(accent_for(Severity::Critical)));
388 assert!(critical.contains(PALETTE.reset));
389 }
390
391 #[test]
392 fn long_messages_wrap_within_box() {
393 let long = MentorMessage {
394 severity: Severity::Info,
395 plain_english: "The npm package manager was not found on your PATH, which means the install command cannot resolve it.".into(),
396 technical_detail: "Neither `npm` nor `npx` resolve to an executable under any of the configured PATH entries.".into(),
397 suggested_action: "Run `npm install -g node` or reinstall Node and then restart your terminal before trying again.".into(),
398 };
399 let plain = format_mentor_message_plain(&long);
400 assert!(plain.lines().count() > 9, "wrapping should add rows");
401 for line in plain.lines() {
402 assert_eq!(line.chars().count(), BOX_WIDTH);
403 }
404 assert!(plain.contains("📋 Why this matters:"));
405 assert!(plain.contains("Next step:"));
406 }
407
408 #[test]
409 fn wrap_respects_width() {
410 let text = "one two three four five";
411 assert_eq!(
412 wrap(text, 10),
413 vec![
414 "one two".to_string(),
415 "three four".to_string(),
416 "five".to_string(),
417 ]
418 );
419 }
420
421 #[test]
422 fn wrap_hard_splits_overlong_words() {
423 assert_eq!(
424 wrap("abcdefghijk", 4),
425 vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string(),]
426 );
427 }
428
429 #[test]
430 fn wrap_collapses_multiple_spaces() {
431 assert_eq!(wrap("a b", 10), vec!["a b".to_string()]);
432 }
433
434 #[test]
435 fn wrap_empty_and_width_zero() {
436 assert_eq!(wrap("", 10), vec![String::new()]);
437 assert_eq!(wrap("abc", 0), vec![String::new()]);
438 }
439
440 #[test]
441 fn indented_body_stays_within_inner_width() {
442 let lines = wrap_indented("Short body.");
443 assert_eq!(lines[0], " Short body.");
444 assert!(lines.iter().all(|l| l.chars().count() <= INNER_WIDTH));
445 }
446
447 #[test]
448 fn palette_values_are_exact_ansi_codes() {
449 assert_eq!(PALETTE.info, "\x1b[94m");
450 assert_eq!(PALETTE.warning, "\x1b[33m");
451 assert_eq!(PALETTE.critical, "\x1b[91m");
452 assert_eq!(PALETTE.reset, "\x1b[0m");
453 }
454
455 #[test]
456 fn test_mentor_message_formatting() {
457 let msg = MentorMessage {
458 severity: Severity::Warning,
459 plain_english: "Port 3000 is jammed.".to_string(),
460 technical_detail: "EADDRINUSE".to_string(),
461 suggested_action: "Free the port, then retry".to_string(),
462 };
463
464 let plain = format_mentor_message_plain(&msg);
465 assert!(!plain.contains("\x1b["), "plain output must have no ANSI");
466 assert!(plain.contains("Port 3000 is jammed."));
467 assert!(plain.contains("EADDRINUSE"));
468 assert!(plain.contains("Free the port, then retry"));
469 assert!(plain.contains("MENTOR NOTE:"), "severity label should be rendered");
470
471 let colored = format_mentor_message(&msg);
472 assert!(colored.contains("\x1b["), "colored output must use ANSI");
473 assert!(colored.contains("Port 3000 is jammed."));
474 }
475}