use colored::Colorize;
use std::collections::HashMap;
use crate::models::{CheckStatus, DiagnosticResult, HealthScore, HealthStatus, ProjectStack};
use crate::modules::stack_detector::detect_stack;
pub const PLANETARY_WIDTH: usize = 60;
const INNER_WIDTH: usize = PLANETARY_WIDTH - 4;
const HEALTH_CELLS: usize = 20;
const NODE_SYSTEMS: &[(&str, &str)] = &[
("package.json", "⚙️ Main Engine Core"),
(".env", "🛡️ Shield Generator"),
("node_modules/", "🔧 System Components Bay"),
("src/", "💾 Data Core"),
(".gitignore", "🚫 Lockdown Protocol"),
("package-lock.json", "📋 Manifest Registry"),
];
const PYTHON_SYSTEMS: &[(&str, &str)] = &[
("requirements.txt", "⚙️ Dependencies Matrix"),
("venv/", "🔧 Isolation Pod"),
(".env", "🛡️ Credentials Vault"),
("setup.py", "📋 Build Sequence"),
("main.py", "💾 Mission Core"),
];
const RUST_SYSTEMS: &[(&str, &str)] = &[
("Cargo.toml", "⚙️ Build Configuration"),
("src/", "💾 Source Matrix"),
("Cargo.lock", "📋 Build Seal"),
("target/", "🔧 Artifact Chamber"),
];
fn stack_systems(stack: &ProjectStack) -> &'static [(&'static str, &'static str)] {
match stack {
ProjectStack::Node { .. } => NODE_SYSTEMS,
ProjectStack::Python { .. } => PYTHON_SYSTEMS,
ProjectStack::Rust { .. } => RUST_SYSTEMS,
ProjectStack::Go { .. } | ProjectStack::Java { .. } | ProjectStack::Docker | ProjectStack::Unknown => &[],
}
}
pub fn get_planetary_mapping(stack: &ProjectStack) -> HashMap<String, String> {
stack_systems(stack)
.iter()
.map(|(file, name)| ((*file).to_string(), (*name).to_string()))
.collect()
}
pub fn theatrical_status(status: CheckStatus) -> &'static str {
match status {
CheckStatus::Pass => "OPERATIONAL",
CheckStatus::Warn => "MINOR ALERT",
CheckStatus::Fail => "OFFLINE",
}
}
pub fn status_icon(status: CheckStatus) -> &'static str {
match status {
CheckStatus::Pass => "✓",
CheckStatus::Warn => "⚠",
CheckStatus::Fail => "✖",
}
}
pub fn render_planetary_diagnostics(diagnostics: &[DiagnosticResult]) -> String {
let stack = detect_stack(".");
let mapping = get_planetary_mapping(&stack);
render_planetary_inner(stack_systems(&stack), &mapping, diagnostics, true)
}
pub fn render_planetary_diagnostics_plain(diagnostics: &[DiagnosticResult]) -> String {
let stack = detect_stack(".");
let mapping = get_planetary_mapping(&stack);
render_planetary_inner(stack_systems(&stack), &mapping, diagnostics, false)
}
pub fn planetary_scan() {
let state = crate::modules::diagnostics::build_snapshot(".");
print!("{}", render_planetary_diagnostics(&state.diagnostics));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowStyle {
Border,
Title,
Plain,
Healthy,
Pass,
Warn,
Fail,
}
fn render_planetary_inner(
systems: &[(&str, &str)],
mapping: &HashMap<String, String>,
diagnostics: &[DiagnosticResult],
colored: bool,
) -> String {
let mut rows = vec![
(RowStyle::Border, border_line(true)),
(
RowStyle::Title,
box_row("🌌 PLANETARY MODE — MISSION CONTROL REPORT"),
),
(RowStyle::Border, separator_line()),
(RowStyle::Plain, box_row("")),
];
for (file, fallback) in systems {
let hits: Vec<&DiagnosticResult> = diagnostics
.iter()
.filter(|d| diagnostic_refs(d, file))
.collect();
if hits.is_empty() {
continue;
}
let name = mapping.get(*file).map(String::as_str).unwrap_or(fallback);
let worst = hits
.iter()
.map(|d| d.status)
.max_by_key(status_rank)
.unwrap();
let style = style_for(worst);
rows.push((style, box_row(&format!("{name} ({file})"))));
for d in &hits {
rows.push((
style_for(d.status),
box_row(&format!(
" [{}] Status: {}",
status_icon(d.status),
theatrical_status(d.status)
)),
));
if d.status != CheckStatus::Pass {
if let Some(remediation) = &d.remediation {
rows.extend(
action_rows(remediation)
.into_iter()
.map(|row| (RowStyle::Plain, row)),
);
}
}
}
rows.push((RowStyle::Plain, box_row("")));
}
let score = HealthScore::from_results(diagnostics);
let health_style = match score.overall_status {
HealthStatus::Healthy => RowStyle::Healthy,
HealthStatus::Caution => RowStyle::Warn,
HealthStatus::Critical => RowStyle::Fail,
};
rows.push((
health_style,
box_row(&format!(
"Mission Health: {}% [{}]",
score.percentage,
health_bar(score.percentage)
)),
));
rows.push((health_style, box_row("🚀 Ready for deployment? Y/n")));
rows.push((RowStyle::Border, border_line(false)));
let mut out = String::new();
for (style, row) in rows {
out.push_str(&paint(row, style, colored));
out.push('\n');
}
out
}
fn diagnostic_refs(diagnostic: &DiagnosticResult, file: &str) -> bool {
let combined = format!("{} {}", diagnostic.check_name, diagnostic.message);
file_tokens(file).iter().any(|token| combined.contains(token))
}
fn file_tokens(file: &str) -> Vec<&str> {
match file.strip_suffix('/') {
Some(bare) => vec![file, bare],
None => vec![file],
}
}
fn status_rank(status: &CheckStatus) -> u8 {
match status {
CheckStatus::Pass => 0,
CheckStatus::Warn => 1,
CheckStatus::Fail => 2,
}
}
fn style_for(status: CheckStatus) -> RowStyle {
match status {
CheckStatus::Pass => RowStyle::Pass,
CheckStatus::Warn => RowStyle::Warn,
CheckStatus::Fail => RowStyle::Fail,
}
}
fn health_bar(percentage: u32) -> String {
let filled = ((percentage as f64 / 100.0) * HEALTH_CELLS as f64).round() as usize;
let filled = filled.min(HEALTH_CELLS);
format!("{}{}", "█".repeat(filled), "░".repeat(HEALTH_CELLS - filled))
}
fn action_rows(remediation: &str) -> Vec<String> {
wrap(remediation, INNER_WIDTH - 10)
.into_iter()
.enumerate()
.map(|(i, line)| {
if i == 0 {
box_row(&format!(" → {line}"))
} else {
box_row(&format!(" {line}"))
}
})
.collect()
}
fn paint(row: String, style: RowStyle, colored: bool) -> String {
if !colored {
return row;
}
match style {
RowStyle::Plain => row.normal().to_string(),
RowStyle::Border | RowStyle::Title => row.cyan().to_string(),
RowStyle::Healthy => row.green().bold().to_string(),
RowStyle::Pass => row.green().to_string(),
RowStyle::Warn => row.yellow().to_string(),
RowStyle::Fail => row.red().to_string(),
}
}
fn border_line(top: bool) -> String {
let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
format!("{left}{}{right}", "─".repeat(PLANETARY_WIDTH - 2))
}
fn separator_line() -> String {
format!("├{}┤", "─".repeat(PLANETARY_WIDTH - 2))
}
fn box_row(content: &str) -> String {
format!("│ {} │", pad(content))
}
fn pad(content: &str) -> String {
let used = content.chars().count();
format!("{content}{}", " ".repeat(INNER_WIDTH.saturating_sub(used)))
}
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 node_stack() -> ProjectStack {
ProjectStack::Node {
version: "22.9.0".into(),
package_manager: "npm".into(),
}
}
fn render_for(
stack: &ProjectStack,
diagnostics: &[DiagnosticResult],
) -> String {
let mapping = get_planetary_mapping(stack);
render_planetary_inner(stack_systems(stack), &mapping, diagnostics, false)
}
#[test]
fn maps_every_common_node_file() {
let map = get_planetary_mapping(&node_stack());
assert_eq!(map.get("package.json").unwrap(), "⚙️ Main Engine Core");
assert_eq!(map.get(".env").unwrap(), "🛡️ Shield Generator");
assert_eq!(map.get("node_modules/").unwrap(), "🔧 System Components Bay");
assert_eq!(map.get("src/").unwrap(), "💾 Data Core");
assert_eq!(map.get(".gitignore").unwrap(), "🚫 Lockdown Protocol");
assert_eq!(
map.get("package-lock.json").unwrap(),
"📋 Manifest Registry"
);
assert_eq!(map.len(), 6);
}
#[test]
fn maps_every_common_python_file() {
let map = get_planetary_mapping(&ProjectStack::Python {
version: "3.12".into(),
});
assert_eq!(
map.get("requirements.txt").unwrap(),
"⚙️ Dependencies Matrix"
);
assert_eq!(map.get("venv/").unwrap(), "🔧 Isolation Pod");
assert_eq!(map.get(".env").unwrap(), "🛡️ Credentials Vault");
assert_eq!(map.get("setup.py").unwrap(), "📋 Build Sequence");
assert_eq!(map.get("main.py").unwrap(), "💾 Mission Core");
assert_eq!(map.len(), 5);
}
#[test]
fn maps_every_common_rust_file() {
let map = get_planetary_mapping(&ProjectStack::Rust {
version: "1.98.0".into(),
});
assert_eq!(map.get("Cargo.toml").unwrap(), "⚙️ Build Configuration");
assert_eq!(map.get("src/").unwrap(), "💾 Source Matrix");
assert_eq!(map.get("Cargo.lock").unwrap(), "📋 Build Seal");
assert_eq!(map.get("target/").unwrap(), "🔧 Artifact Chamber");
assert_eq!(map.len(), 4);
}
#[test]
fn unmapped_stacks_have_empty_dictionary() {
assert!(get_planetary_mapping(&ProjectStack::Docker).is_empty());
assert!(get_planetary_mapping(&ProjectStack::Unknown).is_empty());
}
#[test]
fn theatrical_labels_map_to_check_status() {
assert_eq!(theatrical_status(CheckStatus::Pass), "OPERATIONAL");
assert_eq!(theatrical_status(CheckStatus::Warn), "MINOR ALERT");
assert_eq!(theatrical_status(CheckStatus::Fail), "OFFLINE");
assert_eq!(status_icon(CheckStatus::Pass), "✓");
assert_eq!(status_icon(CheckStatus::Warn), "⚠");
assert_eq!(status_icon(CheckStatus::Fail), "✖");
}
#[test]
fn report_attributes_diagnostics_to_the_right_systems() {
let diagnostics = vec![
DiagnosticResult::new("Dependencies", CheckStatus::Fail, "node_modules/ is missing")
.with_remediation("Run npm install"),
DiagnosticResult::new(
"Dependency audit",
CheckStatus::Warn,
"package.json pins an outdated version",
),
];
let report = render_for(&node_stack(), &diagnostics);
assert!(report.contains("🔧 System Components Bay (node_modules/)"));
assert!(report.contains("[✖] Status: OFFLINE"));
assert!(report.contains("→ Run npm install"));
assert!(report.contains("⚙️ Main Engine Core (package.json)"));
assert!(report.contains("[⚠] Status: MINOR ALERT"));
assert!(report.contains("Mission Health: 0%"));
}
#[test]
fn passing_systems_report_operational() {
let diagnostics = vec![DiagnosticResult::new(
"Dependencies",
CheckStatus::Pass,
"node_modules present — 42 deps resolved",
)];
let report = render_for(&node_stack(), &diagnostics);
assert!(report.contains("🔧 System Components Bay (node_modules/)"));
assert!(report.contains("[✓] Status: OPERATIONAL"));
assert!(report.contains("Mission Health: 100%"));
}
#[test]
fn passes_no_remediation_for_healthy_system() {
let diagnostics = vec![DiagnosticResult::new(
"Env Audit",
CheckStatus::Pass,
".env present",
)
.with_remediation("Nothing to do")];
let report = render_for(&node_stack(), &diagnostics);
assert!(report.contains("[✓] Status: OPERATIONAL"));
assert!(!report.contains("→"));
}
#[test]
fn health_bar_is_recomputed_from_results() {
let diagnostics = vec![
DiagnosticResult::new("Env Audit", CheckStatus::Pass, ".env present"),
DiagnosticResult::new("Port Scan", CheckStatus::Fail, "8080 blocked"),
];
let report = render_for(&node_stack(), &diagnostics);
assert!(report.contains("Mission Health: 50%"));
assert!(report.contains("[██████████░░░░░░░░░░]"));
}
#[test]
fn ignores_diagnostics_without_a_mapped_file() {
let diagnostics = vec![DiagnosticResult::new(
"Port Scan",
CheckStatus::Warn,
"MongoDB occupies port 27017",
)];
let report = render_for(&node_stack(), &diagnostics);
assert!(!report.contains("Main Engine Core"));
assert!(!report.contains("Shield Generator"));
assert!(report.contains("Mission Health:"));
}
#[test]
fn matches_directory_files_with_and_without_slash() {
assert!(diagnostic_refs(
&DiagnosticResult::new("Dependencies", CheckStatus::Fail, "node_modules missing"),
"node_modules/"
));
assert!(diagnostic_refs(
&DiagnosticResult::new("Dependencies", CheckStatus::Fail, "node_modules/ missing"),
"node_modules/"
));
assert!(!diagnostic_refs(
&DiagnosticResult::new("Port Scan", CheckStatus::Pass, "ports all free"),
"node_modules/"
));
}
#[test]
fn every_box_line_is_exactly_report_width() {
let diagnostics = vec![
DiagnosticResult::new("Dependencies", CheckStatus::Fail, "Cargo.lock is missing")
.with_remediation("Run `cargo build` once to generate it"),
DiagnosticResult::new("Env Audit", CheckStatus::Pass, "no .env needed"),
];
let report = render_for(
&ProjectStack::Rust {
version: "1.98.0".into(),
},
&diagnostics,
);
for line in report.lines() {
assert_eq!(
line.chars().count(),
PLANETARY_WIDTH,
"off-width row: {line:?}"
);
}
}
#[test]
fn plain_variant_never_emits_ansi() {
let diagnostics = vec![DiagnosticResult::new(
"Env Audit",
CheckStatus::Warn,
".env file missing",
)];
let report = render_planetary_diagnostics_plain(&diagnostics);
assert!(!report.contains('\u{1b}'));
assert!(report.contains("Mission Health:"));
}
#[test]
fn colored_variant_wraps_in_mission_control_box() {
let diagnostics = vec![DiagnosticResult::new(
"Env Audit",
CheckStatus::Fail,
".env file missing! Found .env.example template.",
)];
let report = render_planetary_diagnostics(&diagnostics);
assert!(report.contains("🌌 PLANETARY MODE — MISSION CONTROL REPORT"));
assert!(report.contains("🚀 Ready for deployment? Y/n"));
}
}