debtmap 0.16.4

Code complexity and technical debt analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Priority item formatting for markdown output
//!
//! Formats individual mixed priority items (function-level and file-level debt)

use crate::formatting::FormattingConfig;
use crate::priority::{DebtItem, FileDebtItem};
use std::fmt::Write;

use super::details::format_priority_item_markdown;
use super::utilities::{
    complexity_category, format_file_impact, function_category, get_file_extension,
    get_severity_label, score_category,
};

pub(crate) fn format_mixed_priority_item_markdown(
    output: &mut String,
    rank: usize,
    item: &DebtItem,
    verbosity: u8,
    config: &FormattingConfig,
) {
    match item {
        DebtItem::Function(func_item) => {
            format_priority_item_markdown(output, rank, func_item, verbosity);
        }
        DebtItem::File(file_item) => {
            format_file_priority_item_markdown(
                output,
                rank,
                file_item,
                verbosity,
                config.show_splits,
            );
        }
    }
}

pub(crate) fn format_file_priority_item_markdown(
    output: &mut String,
    rank: usize,
    item: &FileDebtItem,
    verbosity: u8,
    show_splits: bool,
) {
    let severity = get_severity_label(item.score);

    // Determine file type using context-aware thresholds (spec 135)
    let is_god_object = item
        .metrics
        .god_object_analysis
        .as_ref()
        .is_some_and(|a| a.is_god_object);

    let type_label = if is_god_object {
        "FILE - GOD OBJECT"
    } else if let Some(ref file_type) = item.metrics.file_type {
        use crate::organization::get_threshold;
        let threshold = get_threshold(
            file_type,
            item.metrics.function_count,
            item.metrics.total_lines,
        );
        if item.metrics.total_lines > threshold.base_threshold {
            "FILE - HIGH COMPLEXITY"
        } else {
            "FILE"
        }
    } else {
        // Legacy behavior if no file type
        if item.metrics.total_lines > 500 {
            "FILE - HIGH COMPLEXITY"
        } else {
            "FILE"
        }
    };

    // File items (god objects) are always T1 Critical Architecture
    let tier_label = "[T1] ";

    // Header with rank, tier, and score
    writeln!(
        output,
        "### #{} {}Score: {:.1} [{}]",
        rank, tier_label, item.score, severity
    )
    .unwrap();

    writeln!(output, "**Type:** {}", type_label).unwrap();
    writeln!(
        output,
        "**File:** `{}` ({} lines, {} functions)",
        item.metrics.path.display(),
        item.metrics.total_lines,
        item.metrics.function_count
    )
    .unwrap();

    // God object details if applicable
    if let Some(ref god_analysis) = item.metrics.god_object_analysis {
        if god_analysis.is_god_object {
            writeln!(output, "**God Object Metrics:**").unwrap();
            writeln!(output, "- Methods: {}", god_analysis.method_count).unwrap();
            writeln!(output, "- Fields: {}", god_analysis.field_count).unwrap();
            writeln!(
                output,
                "- Responsibilities: {}",
                god_analysis.responsibility_count
            )
            .unwrap();
            writeln!(
                output,
                "- God Object Score: {:.1}",
                god_analysis.god_object_score
            )
            .unwrap();

            // Show coverage data if available
            if item.metrics.coverage_percent > 0.0 {
                writeln!(
                    output,
                    "- Test Coverage: {:.1}% ({} uncovered lines)",
                    item.metrics.coverage_percent, item.metrics.uncovered_lines
                )
                .unwrap();
            }
        }
    }

    // Show split recommendations if available (Spec 208)
    format_split_recommendations_markdown(output, item, verbosity, show_splits);

    writeln!(output, "**Recommendation:** {}", item.recommendation).unwrap();

    writeln!(output, "**Impact:** {}", format_file_impact(&item.impact)).unwrap();

    if verbosity >= 1 {
        writeln!(output, "\n**Scoring Breakdown:**").unwrap();
        writeln!(
            output,
            "- File size: {}",
            score_category(item.metrics.total_lines)
        )
        .unwrap();
        writeln!(
            output,
            "- Functions: {}",
            function_category(item.metrics.function_count)
        )
        .unwrap();
        writeln!(
            output,
            "- Complexity: {}",
            complexity_category(item.metrics.avg_complexity)
        )
        .unwrap();
        if item.metrics.function_count > 0 {
            writeln!(
                output,
                "- Dependencies: {} functions may have complex interdependencies",
                item.metrics.function_count
            )
            .unwrap();
        }
    }
}

/// Write a hint message suggesting --show-splits flag
fn format_splits_hint(output: &mut String) {
    writeln!(output).unwrap();
    writeln!(
        output,
        "*(Use --show-splits for detailed module split recommendations)*"
    )
    .unwrap();
}

/// Write diagnostic message when no splits are available
fn format_no_splits_diagnostic(output: &mut String) {
    writeln!(output).unwrap();
    writeln!(output, "**NO DETAILED SPLITS AVAILABLE**").unwrap();
    writeln!(
        output,
        "- Analysis could not generate responsibility-based splits for this file."
    )
    .unwrap();
    writeln!(output, "- This may indicate:").unwrap();
    writeln!(
        output,
        "  - File has too few functions (< 3 per responsibility)"
    )
    .unwrap();
    writeln!(output, "  - Functions lack clear responsibility signals").unwrap();
    writeln!(output, "  - File may be test-only or configuration").unwrap();
    writeln!(
        output,
        "- Consider manual analysis or consult documentation."
    )
    .unwrap();
    writeln!(output).unwrap();
}

/// Format a method list with sampling (shows max 5 methods)
fn format_split_methods(output: &mut String, methods: &[String]) {
    if methods.is_empty() {
        return;
    }
    let total = methods.len();
    let sample_size = 5.min(total);

    writeln!(output, "  - Methods ({} total):", total).unwrap();
    for method in methods.iter().take(sample_size) {
        writeln!(output, "    - `{}()`", method).unwrap();
    }
    if total > sample_size {
        writeln!(output, "    - ... and {} more", total - sample_size).unwrap();
    }
}

/// Format classification evidence with confidence warnings
fn format_split_evidence(
    output: &mut String,
    evidence: &crate::analysis::multi_signal_aggregation::AggregatedClassification,
) {
    writeln!(
        output,
        "  - Confidence: {:.1}% | Signals: {}",
        evidence.confidence * 100.0,
        evidence.evidence.len()
    )
    .unwrap();

    if evidence.confidence < 0.80 && !evidence.alternatives.is_empty() {
        writeln!(
            output,
            "  - **⚠ Low confidence classification - review recommended**"
        )
        .unwrap();
    }
}

/// Format a single module split recommendation
fn format_single_split(
    output: &mut String,
    split: &crate::organization::god_object::ModuleSplit,
    extension: &str,
    verbosity: u8,
) {
    // Module name and responsibility
    writeln!(output, "- **{}.{}**", split.suggested_name, extension).unwrap();

    let priority_indicator = match split.priority {
        crate::organization::Priority::High => "High",
        crate::organization::Priority::Medium => "Medium",
        crate::organization::Priority::Low => "Low",
    };

    writeln!(
        output,
        "  - Category: {} | Priority: {}",
        split.responsibility, priority_indicator
    )
    .unwrap();
    writeln!(
        output,
        "  - Size: {} methods, ~{} lines",
        split.methods_to_move.len(),
        split.estimated_lines,
    )
    .unwrap();

    // Evidence (conditional on verbosity)
    if verbosity > 0 {
        if let Some(ref evidence) = split.classification_evidence {
            format_split_evidence(output, evidence);
        }
    }

    // Methods list (prefer representative_methods, fallback to methods_to_move)
    let methods = if !split.representative_methods.is_empty() {
        &split.representative_methods
    } else {
        &split.methods_to_move
    };
    format_split_methods(output, methods);

    // Fields needed
    if !split.fields_needed.is_empty() {
        writeln!(
            output,
            "  - Fields needed: {}",
            split.fields_needed.join(", ")
        )
        .unwrap();
    }

    // Trait extraction (conditional on verbosity)
    if let Some(ref trait_suggestion) = split.trait_suggestion {
        if verbosity > 0 {
            writeln!(output, "  - Trait extraction:").unwrap();
            for line in trait_suggestion.lines() {
                writeln!(output, "    {}", line).unwrap();
            }
        }
    }

    // Structs
    if !split.structs_to_move.is_empty() {
        writeln!(output, "  - Structs: {}", split.structs_to_move.join(", ")).unwrap();
    }

    // Warning
    if let Some(warning) = &split.warning {
        writeln!(output, "  - **⚠ {}**", warning).unwrap();
    }

    writeln!(output).unwrap();
}

/// Write a note explaining single cohesive group detection
fn format_single_group_note(output: &mut String) {
    writeln!(
        output,
        "*NOTE: Only one cohesive group detected. This suggests methods are tightly coupled.*"
    )
    .unwrap();
    writeln!(
        output,
        "*Consider splitting by feature/responsibility rather than call patterns.*"
    )
    .unwrap();
    writeln!(output).unwrap();
}

/// Format detailed splits display with header and all split recommendations
fn format_detailed_splits(
    output: &mut String,
    god_analysis: &crate::organization::GodObjectAnalysis,
    extension: &str,
    verbosity: u8,
) {
    writeln!(output).unwrap();

    // Use different header based on number of splits
    if god_analysis.recommended_splits.len() == 1 {
        writeln!(
            output,
            "**EXTRACTION CANDIDATE** (single cohesive group found):"
        )
        .unwrap();
    } else {
        writeln!(
            output,
            "**RECOMMENDED SPLITS** ({} modules):",
            god_analysis.recommended_splits.len()
        )
        .unwrap();
    }

    writeln!(output).unwrap();

    for split in god_analysis.recommended_splits.iter() {
        format_single_split(output, split, extension, verbosity);
    }

    // Add explanation if only 1 group found
    if god_analysis.recommended_splits.len() == 1 {
        format_single_group_note(output);
    }
}

/// Format split recommendations for markdown output (Spec 208)
pub(crate) fn format_split_recommendations_markdown(
    output: &mut String,
    item: &FileDebtItem,
    verbosity: u8,
    show_splits: bool,
) {
    let god_analysis = match &item.metrics.god_object_analysis {
        Some(analysis) => analysis,
        None => return,
    };

    if god_analysis.recommended_splits.is_empty() {
        if show_splits {
            format_no_splits_diagnostic(output);
        }
        return;
    }

    if !show_splits {
        format_splits_hint(output);
        return;
    }

    let extension = get_file_extension(&item.metrics.path);
    format_detailed_splits(output, god_analysis, extension, verbosity);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::multi_signal_aggregation::{
        AggregatedClassification, ResponsibilityCategory, SignalEvidence, SignalType,
    };
    use crate::organization::god_object::ModuleSplit;
    use crate::organization::Priority;

    #[test]
    fn format_split_methods_shows_sample_when_many() {
        let mut output = String::new();
        let methods: Vec<String> = vec!["a", "b", "c", "d", "e", "f", "g"]
            .into_iter()
            .map(String::from)
            .collect();

        format_split_methods(&mut output, &methods);

        assert!(output.contains("Methods (7 total)"));
        assert!(output.contains("`a()`"));
        assert!(output.contains("`e()`"));
        assert!(output.contains("... and 2 more"));
        assert!(!output.contains("`f()`"));
    }

    #[test]
    fn format_split_methods_empty_produces_no_output() {
        let mut output = String::new();
        format_split_methods(&mut output, &[]);
        assert!(output.is_empty());
    }

    #[test]
    fn format_split_methods_all_shown_when_five_or_less() {
        let mut output = String::new();
        let methods: Vec<String> = vec!["a", "b", "c"].into_iter().map(String::from).collect();

        format_split_methods(&mut output, &methods);

        assert!(output.contains("Methods (3 total)"));
        assert!(output.contains("`a()`"));
        assert!(output.contains("`b()`"));
        assert!(output.contains("`c()`"));
        assert!(!output.contains("... and"));
    }

    #[test]
    fn format_split_evidence_shows_confidence_and_signals() {
        let mut output = String::new();
        let evidence = AggregatedClassification {
            primary: ResponsibilityCategory::FileIO,
            confidence: 0.92,
            evidence: vec![
                SignalEvidence {
                    signal_type: SignalType::IoDetection,
                    category: ResponsibilityCategory::FileIO,
                    confidence: 0.95,
                    weight: 1.0,
                    contribution: 0.95,
                    description: "File I/O detected".to_string(),
                },
                SignalEvidence {
                    signal_type: SignalType::Name,
                    category: ResponsibilityCategory::FileIO,
                    confidence: 0.80,
                    weight: 0.5,
                    contribution: 0.40,
                    description: "Name pattern match".to_string(),
                },
            ],
            alternatives: vec![],
        };

        format_split_evidence(&mut output, &evidence);

        assert!(output.contains("Confidence: 92.0%"));
        assert!(output.contains("Signals: 2"));
        assert!(!output.contains("Low confidence"));
    }

    #[test]
    fn format_split_evidence_warns_on_low_confidence() {
        let mut output = String::new();
        let evidence = AggregatedClassification {
            primary: ResponsibilityCategory::Unknown,
            confidence: 0.65,
            evidence: vec![SignalEvidence {
                signal_type: SignalType::Name,
                category: ResponsibilityCategory::Unknown,
                confidence: 0.65,
                weight: 0.5,
                contribution: 0.325,
                description: "Weak signal".to_string(),
            }],
            alternatives: vec![(ResponsibilityCategory::Validation, 0.40)],
        };

        format_split_evidence(&mut output, &evidence);

        assert!(output.contains("Confidence: 65.0%"));
        assert!(output.contains("Low confidence"));
    }

    #[test]
    fn format_splits_hint_shows_suggestion() {
        let mut output = String::new();
        format_splits_hint(&mut output);
        assert!(output.contains("--show-splits"));
        assert!(output.contains("detailed module split recommendations"));
    }

    #[test]
    fn format_no_splits_diagnostic_lists_reasons() {
        let mut output = String::new();
        format_no_splits_diagnostic(&mut output);
        assert!(output.contains("NO DETAILED SPLITS AVAILABLE"));
        assert!(output.contains("too few functions"));
        assert!(output.contains("responsibility signals"));
    }

    #[test]
    fn format_single_group_note_explains_tight_coupling() {
        let mut output = String::new();
        format_single_group_note(&mut output);
        assert!(output.contains("one cohesive group"));
        assert!(output.contains("tightly coupled"));
        assert!(output.contains("feature/responsibility"));
    }

    #[test]
    fn format_single_split_shows_basic_info() {
        let mut output = String::new();
        let split = ModuleSplit {
            suggested_name: "io_handler".to_string(),
            responsibility: "I/O Operations".to_string(),
            methods_to_move: vec![
                "read_file".to_string(),
                "write_file".to_string(),
                "open_connection".to_string(),
            ],
            estimated_lines: 150,
            priority: Priority::High,
            ..Default::default()
        };

        format_single_split(&mut output, &split, "rs", 0);

        assert!(output.contains("**io_handler.rs**"));
        assert!(output.contains("Category: I/O Operations"));
        assert!(output.contains("Priority: High"));
        assert!(output.contains("Size: 3 methods, ~150 lines"));
        assert!(output.contains("Methods (3 total)"));
    }

    #[test]
    fn format_single_split_prefers_representative_methods() {
        let mut output = String::new();
        let split = ModuleSplit {
            suggested_name: "parser".to_string(),
            responsibility: "Parsing".to_string(),
            methods_to_move: vec!["internal1".to_string(), "internal2".to_string()],
            estimated_lines: 80,
            priority: Priority::Medium,
            representative_methods: vec!["parse_json".to_string(), "parse_yaml".to_string()],
            ..Default::default()
        };

        format_single_split(&mut output, &split, "rs", 0);

        assert!(output.contains("`parse_json()`"));
        assert!(output.contains("`parse_yaml()`"));
        assert!(!output.contains("`internal1()`"));
    }

    #[test]
    fn format_single_split_shows_warning_when_present() {
        let mut output = String::new();
        let split = ModuleSplit {
            suggested_name: "legacy".to_string(),
            responsibility: "Legacy".to_string(),
            methods_to_move: vec!["old_method".to_string()],
            estimated_lines: 50,
            priority: Priority::Low,
            warning: Some("May require significant refactoring".to_string()),
            ..Default::default()
        };

        format_single_split(&mut output, &split, "rs", 0);

        assert!(output.contains("**⚠ May require significant refactoring**"));
    }
}