1use colored::Colorize;
45use std::collections::HashMap;
46
47use crate::models::{CheckStatus, DiagnosticResult, HealthScore, HealthStatus, ProjectStack};
48use crate::modules::stack_detector::detect_stack;
49
50pub const PLANETARY_WIDTH: usize = 60;
57
58const INNER_WIDTH: usize = PLANETARY_WIDTH - 4;
60
61const HEALTH_CELLS: usize = 20;
63
64const NODE_SYSTEMS: &[(&str, &str)] = &[
66 ("package.json", "⚙️ Main Engine Core"),
67 (".env", "🛡️ Shield Generator"),
68 ("node_modules/", "🔧 System Components Bay"),
69 ("src/", "💾 Data Core"),
70 (".gitignore", "🚫 Lockdown Protocol"),
71 ("package-lock.json", "📋 Manifest Registry"),
72];
73
74const PYTHON_SYSTEMS: &[(&str, &str)] = &[
76 ("requirements.txt", "⚙️ Dependencies Matrix"),
77 ("venv/", "🔧 Isolation Pod"),
78 (".env", "🛡️ Credentials Vault"),
79 ("setup.py", "📋 Build Sequence"),
80 ("main.py", "💾 Mission Core"),
81];
82
83const RUST_SYSTEMS: &[(&str, &str)] = &[
85 ("Cargo.toml", "⚙️ Build Configuration"),
86 ("src/", "💾 Source Matrix"),
87 ("Cargo.lock", "📋 Build Seal"),
88 ("target/", "🔧 Artifact Chamber"),
89];
90
91fn stack_systems(stack: &ProjectStack) -> &'static [(&'static str, &'static str)] {
93 match stack {
94 ProjectStack::Node { .. } => NODE_SYSTEMS,
95 ProjectStack::Python { .. } => PYTHON_SYSTEMS,
96 ProjectStack::Rust { .. } => RUST_SYSTEMS,
97 ProjectStack::Go { .. } | ProjectStack::Java { .. } | ProjectStack::Docker | ProjectStack::Unknown => &[],
98 }
99}
100
101pub fn get_planetary_mapping(stack: &ProjectStack) -> HashMap<String, String> {
116 stack_systems(stack)
117 .iter()
118 .map(|(file, name)| ((*file).to_string(), (*name).to_string()))
119 .collect()
120}
121
122pub fn theatrical_status(status: CheckStatus) -> &'static str {
133 match status {
134 CheckStatus::Pass => "OPERATIONAL",
135 CheckStatus::Warn => "MINOR ALERT",
136 CheckStatus::Fail => "OFFLINE",
137 }
138}
139
140pub fn status_icon(status: CheckStatus) -> &'static str {
142 match status {
143 CheckStatus::Pass => "✓",
144 CheckStatus::Warn => "⚠",
145 CheckStatus::Fail => "✖",
146 }
147}
148
149pub fn render_planetary_diagnostics(diagnostics: &[DiagnosticResult]) -> String {
155 let stack = detect_stack(".");
156 let mapping = get_planetary_mapping(&stack);
157 render_planetary_inner(stack_systems(&stack), &mapping, diagnostics, true)
158}
159
160pub fn render_planetary_diagnostics_plain(diagnostics: &[DiagnosticResult]) -> String {
162 let stack = detect_stack(".");
163 let mapping = get_planetary_mapping(&stack);
164 render_planetary_inner(stack_systems(&stack), &mapping, diagnostics, false)
165}
166
167pub fn planetary_scan() {
169 let state = crate::modules::diagnostics::build_snapshot(".");
170 print!("{}", render_planetary_diagnostics(&state.diagnostics));
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178enum RowStyle {
179 Border,
180 Title,
181 Plain,
182 Healthy,
183 Pass,
184 Warn,
185 Fail,
186}
187
188fn render_planetary_inner(
189 systems: &[(&str, &str)],
190 mapping: &HashMap<String, String>,
191 diagnostics: &[DiagnosticResult],
192 colored: bool,
193) -> String {
194 let mut rows = vec![
195 (RowStyle::Border, border_line(true)),
196 (
197 RowStyle::Title,
198 box_row("🌌 PLANETARY MODE — MISSION CONTROL REPORT"),
199 ),
200 (RowStyle::Border, separator_line()),
201 (RowStyle::Plain, box_row("")),
202 ];
203
204 for (file, fallback) in systems {
205 let hits: Vec<&DiagnosticResult> = diagnostics
206 .iter()
207 .filter(|d| diagnostic_refs(d, file))
208 .collect();
209 if hits.is_empty() {
210 continue;
211 }
212
213 let name = mapping.get(*file).map(String::as_str).unwrap_or(fallback);
214 let worst = hits
215 .iter()
216 .map(|d| d.status)
217 .max_by_key(status_rank)
218 .unwrap();
219 let style = style_for(worst);
220
221 rows.push((style, box_row(&format!("{name} ({file})"))));
222 for d in &hits {
223 rows.push((
224 style_for(d.status),
225 box_row(&format!(
226 " [{}] Status: {}",
227 status_icon(d.status),
228 theatrical_status(d.status)
229 )),
230 ));
231 if d.status != CheckStatus::Pass {
232 if let Some(remediation) = &d.remediation {
233 rows.extend(
234 action_rows(remediation)
235 .into_iter()
236 .map(|row| (RowStyle::Plain, row)),
237 );
238 }
239 }
240 }
241 rows.push((RowStyle::Plain, box_row("")));
242 }
243
244 let score = HealthScore::from_results(diagnostics);
245 let health_style = match score.overall_status {
246 HealthStatus::Healthy => RowStyle::Healthy,
247 HealthStatus::Caution => RowStyle::Warn,
248 HealthStatus::Critical => RowStyle::Fail,
249 };
250 rows.push((
251 health_style,
252 box_row(&format!(
253 "Mission Health: {}% [{}]",
254 score.percentage,
255 health_bar(score.percentage)
256 )),
257 ));
258 rows.push((health_style, box_row("🚀 Ready for deployment? Y/n")));
259 rows.push((RowStyle::Border, border_line(false)));
260
261 let mut out = String::new();
262 for (style, row) in rows {
263 out.push_str(&paint(row, style, colored));
264 out.push('\n');
265 }
266 out
267}
268
269fn diagnostic_refs(diagnostic: &DiagnosticResult, file: &str) -> bool {
273 let combined = format!("{} {}", diagnostic.check_name, diagnostic.message);
274 file_tokens(file).iter().any(|token| combined.contains(token))
275}
276
277fn file_tokens(file: &str) -> Vec<&str> {
278 match file.strip_suffix('/') {
279 Some(bare) => vec![file, bare],
280 None => vec![file],
281 }
282}
283
284fn status_rank(status: &CheckStatus) -> u8 {
285 match status {
286 CheckStatus::Pass => 0,
287 CheckStatus::Warn => 1,
288 CheckStatus::Fail => 2,
289 }
290}
291
292fn style_for(status: CheckStatus) -> RowStyle {
293 match status {
294 CheckStatus::Pass => RowStyle::Pass,
295 CheckStatus::Warn => RowStyle::Warn,
296 CheckStatus::Fail => RowStyle::Fail,
297 }
298}
299
300fn health_bar(percentage: u32) -> String {
303 let filled = ((percentage as f64 / 100.0) * HEALTH_CELLS as f64).round() as usize;
304 let filled = filled.min(HEALTH_CELLS);
305 format!("{}{}", "█".repeat(filled), "░".repeat(HEALTH_CELLS - filled))
306}
307
308fn action_rows(remediation: &str) -> Vec<String> {
310 wrap(remediation, INNER_WIDTH - 10)
311 .into_iter()
312 .enumerate()
313 .map(|(i, line)| {
314 if i == 0 {
315 box_row(&format!(" → {line}"))
316 } else {
317 box_row(&format!(" {line}"))
318 }
319 })
320 .collect()
321}
322
323fn paint(row: String, style: RowStyle, colored: bool) -> String {
324 if !colored {
325 return row;
326 }
327 match style {
328 RowStyle::Plain => row.normal().to_string(),
329 RowStyle::Border | RowStyle::Title => row.cyan().to_string(),
330 RowStyle::Healthy => row.green().bold().to_string(),
331 RowStyle::Pass => row.green().to_string(),
332 RowStyle::Warn => row.yellow().to_string(),
333 RowStyle::Fail => row.red().to_string(),
334 }
335}
336
337fn border_line(top: bool) -> String {
338 let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
339 format!("{left}{}{right}", "─".repeat(PLANETARY_WIDTH - 2))
340}
341
342fn separator_line() -> String {
343 format!("├{}┤", "─".repeat(PLANETARY_WIDTH - 2))
344}
345
346fn box_row(content: &str) -> String {
348 format!("│ {} │", pad(content))
349}
350
351fn pad(content: &str) -> String {
352 let used = content.chars().count();
353 format!("{content}{}", " ".repeat(INNER_WIDTH.saturating_sub(used)))
354}
355
356fn wrap(text: &str, width: usize) -> Vec<String> {
359 if text.is_empty() || width == 0 {
360 return vec![String::new()];
361 }
362
363 let mut lines = Vec::new();
364 let mut current = String::new();
365
366 for word in text.split(' ') {
367 let word_len = word.chars().count();
368 if word_len == 0 {
369 continue;
370 }
371 if word_len > width {
372 if !current.is_empty() {
373 lines.push(std::mem::take(&mut current));
374 }
375 let mut chunk = String::new();
376 for ch in word.chars() {
377 if chunk.chars().count() == width {
378 lines.push(std::mem::take(&mut chunk));
379 }
380 chunk.push(ch);
381 }
382 current = chunk;
383 } else if current.is_empty() {
384 current.push_str(word);
385 } else if current.chars().count() + 1 + word_len <= width {
386 current.push(' ');
387 current.push_str(word);
388 } else {
389 lines.push(std::mem::take(&mut current));
390 current.push_str(word);
391 }
392 }
393
394 if !current.is_empty() {
395 lines.push(current);
396 }
397 if lines.is_empty() {
398 lines.push(String::new());
399 }
400 lines
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 fn node_stack() -> ProjectStack {
408 ProjectStack::Node {
409 version: "22.9.0".into(),
410 package_manager: "npm".into(),
411 }
412 }
413
414 fn render_for(
415 stack: &ProjectStack,
416 diagnostics: &[DiagnosticResult],
417 ) -> String {
418 let mapping = get_planetary_mapping(stack);
419 render_planetary_inner(stack_systems(stack), &mapping, diagnostics, false)
420 }
421
422 #[test]
423 fn maps_every_common_node_file() {
424 let map = get_planetary_mapping(&node_stack());
425 assert_eq!(map.get("package.json").unwrap(), "⚙️ Main Engine Core");
426 assert_eq!(map.get(".env").unwrap(), "🛡️ Shield Generator");
427 assert_eq!(map.get("node_modules/").unwrap(), "🔧 System Components Bay");
428 assert_eq!(map.get("src/").unwrap(), "💾 Data Core");
429 assert_eq!(map.get(".gitignore").unwrap(), "🚫 Lockdown Protocol");
430 assert_eq!(
431 map.get("package-lock.json").unwrap(),
432 "📋 Manifest Registry"
433 );
434 assert_eq!(map.len(), 6);
435 }
436
437 #[test]
438 fn maps_every_common_python_file() {
439 let map = get_planetary_mapping(&ProjectStack::Python {
440 version: "3.12".into(),
441 });
442 assert_eq!(
443 map.get("requirements.txt").unwrap(),
444 "⚙️ Dependencies Matrix"
445 );
446 assert_eq!(map.get("venv/").unwrap(), "🔧 Isolation Pod");
447 assert_eq!(map.get(".env").unwrap(), "🛡️ Credentials Vault");
448 assert_eq!(map.get("setup.py").unwrap(), "📋 Build Sequence");
449 assert_eq!(map.get("main.py").unwrap(), "💾 Mission Core");
450 assert_eq!(map.len(), 5);
451 }
452
453 #[test]
454 fn maps_every_common_rust_file() {
455 let map = get_planetary_mapping(&ProjectStack::Rust {
456 version: "1.98.0".into(),
457 });
458 assert_eq!(map.get("Cargo.toml").unwrap(), "⚙️ Build Configuration");
459 assert_eq!(map.get("src/").unwrap(), "💾 Source Matrix");
460 assert_eq!(map.get("Cargo.lock").unwrap(), "📋 Build Seal");
461 assert_eq!(map.get("target/").unwrap(), "🔧 Artifact Chamber");
462 assert_eq!(map.len(), 4);
463 }
464
465 #[test]
466 fn unmapped_stacks_have_empty_dictionary() {
467 assert!(get_planetary_mapping(&ProjectStack::Docker).is_empty());
468 assert!(get_planetary_mapping(&ProjectStack::Unknown).is_empty());
469 }
470
471 #[test]
472 fn theatrical_labels_map_to_check_status() {
473 assert_eq!(theatrical_status(CheckStatus::Pass), "OPERATIONAL");
474 assert_eq!(theatrical_status(CheckStatus::Warn), "MINOR ALERT");
475 assert_eq!(theatrical_status(CheckStatus::Fail), "OFFLINE");
476 assert_eq!(status_icon(CheckStatus::Pass), "✓");
477 assert_eq!(status_icon(CheckStatus::Warn), "⚠");
478 assert_eq!(status_icon(CheckStatus::Fail), "✖");
479 }
480
481 #[test]
482 fn report_attributes_diagnostics_to_the_right_systems() {
483 let diagnostics = vec![
484 DiagnosticResult::new("Dependencies", CheckStatus::Fail, "node_modules/ is missing")
485 .with_remediation("Run npm install"),
486 DiagnosticResult::new(
487 "Dependency audit",
488 CheckStatus::Warn,
489 "package.json pins an outdated version",
490 ),
491 ];
492 let report = render_for(&node_stack(), &diagnostics);
493
494 assert!(report.contains("🔧 System Components Bay (node_modules/)"));
495 assert!(report.contains("[✖] Status: OFFLINE"));
496 assert!(report.contains("→ Run npm install"));
497 assert!(report.contains("⚙️ Main Engine Core (package.json)"));
498 assert!(report.contains("[⚠] Status: MINOR ALERT"));
499 assert!(report.contains("Mission Health: 0%"));
500 }
501
502 #[test]
503 fn passing_systems_report_operational() {
504 let diagnostics = vec![DiagnosticResult::new(
505 "Dependencies",
506 CheckStatus::Pass,
507 "node_modules present — 42 deps resolved",
508 )];
509 let report = render_for(&node_stack(), &diagnostics);
510
511 assert!(report.contains("🔧 System Components Bay (node_modules/)"));
512 assert!(report.contains("[✓] Status: OPERATIONAL"));
513 assert!(report.contains("Mission Health: 100%"));
514 }
515
516 #[test]
517 fn passes_no_remediation_for_healthy_system() {
518 let diagnostics = vec![DiagnosticResult::new(
519 "Env Audit",
520 CheckStatus::Pass,
521 ".env present",
522 )
523 .with_remediation("Nothing to do")];
524 let report = render_for(&node_stack(), &diagnostics);
525
526 assert!(report.contains("[✓] Status: OPERATIONAL"));
527 assert!(!report.contains("→"));
528 }
529
530 #[test]
531 fn health_bar_is_recomputed_from_results() {
532 let diagnostics = vec![
533 DiagnosticResult::new("Env Audit", CheckStatus::Pass, ".env present"),
534 DiagnosticResult::new("Port Scan", CheckStatus::Fail, "8080 blocked"),
535 ];
536 let report = render_for(&node_stack(), &diagnostics);
537
538 assert!(report.contains("Mission Health: 50%"));
539 assert!(report.contains("[██████████░░░░░░░░░░]"));
540 }
541
542 #[test]
543 fn ignores_diagnostics_without_a_mapped_file() {
544 let diagnostics = vec![DiagnosticResult::new(
545 "Port Scan",
546 CheckStatus::Warn,
547 "MongoDB occupies port 27017",
548 )];
549 let report = render_for(&node_stack(), &diagnostics);
550
551 assert!(!report.contains("Main Engine Core"));
552 assert!(!report.contains("Shield Generator"));
553 assert!(report.contains("Mission Health:"));
554 }
555
556 #[test]
557 fn matches_directory_files_with_and_without_slash() {
558 assert!(diagnostic_refs(
559 &DiagnosticResult::new("Dependencies", CheckStatus::Fail, "node_modules missing"),
560 "node_modules/"
561 ));
562 assert!(diagnostic_refs(
563 &DiagnosticResult::new("Dependencies", CheckStatus::Fail, "node_modules/ missing"),
564 "node_modules/"
565 ));
566 assert!(!diagnostic_refs(
567 &DiagnosticResult::new("Port Scan", CheckStatus::Pass, "ports all free"),
568 "node_modules/"
569 ));
570 }
571
572 #[test]
573 fn every_box_line_is_exactly_report_width() {
574 let diagnostics = vec![
575 DiagnosticResult::new("Dependencies", CheckStatus::Fail, "Cargo.lock is missing")
576 .with_remediation("Run `cargo build` once to generate it"),
577 DiagnosticResult::new("Env Audit", CheckStatus::Pass, "no .env needed"),
578 ];
579 let report = render_for(
580 &ProjectStack::Rust {
581 version: "1.98.0".into(),
582 },
583 &diagnostics,
584 );
585
586 for line in report.lines() {
587 assert_eq!(
588 line.chars().count(),
589 PLANETARY_WIDTH,
590 "off-width row: {line:?}"
591 );
592 }
593 }
594
595 #[test]
596 fn plain_variant_never_emits_ansi() {
597 let diagnostics = vec![DiagnosticResult::new(
598 "Env Audit",
599 CheckStatus::Warn,
600 ".env file missing",
601 )];
602 let report = render_planetary_diagnostics_plain(&diagnostics);
603 assert!(!report.contains('\u{1b}'));
604 assert!(report.contains("Mission Health:"));
605 }
606
607 #[test]
608 fn colored_variant_wraps_in_mission_control_box() {
609 let diagnostics = vec![DiagnosticResult::new(
610 "Env Audit",
611 CheckStatus::Fail,
612 ".env file missing! Found .env.example template.",
613 )];
614 let report = render_planetary_diagnostics(&diagnostics);
615 assert!(report.contains("🌌 PLANETARY MODE — MISSION CONTROL REPORT"));
616 assert!(report.contains("🚀 Ready for deployment? Y/n"));
617 }
618}