debtmap 0.16.3

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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
mod ast_analysis;
mod classifiers;
mod pattern_matchers;

use crate::analyzers::rust_data_flow_analyzer::analyze_data_flow;
use crate::core::FunctionMetrics;
use crate::priority::call_graph::{CallGraph, FunctionId};
use ast_analysis::is_simple_accessor_body;
use classifiers::{
    is_constructor_enhanced, is_debug_function, is_enum_converter_enhanced, is_io_wrapper,
    is_orchestrator, is_pattern_matching_function,
};
use pattern_matchers::{is_entry_point_by_name, matches_accessor_name};
use serde::{Deserialize, Serialize};

#[cfg(test)]
use classifiers::{
    calculate_delegation_ratio, delegates_to_tested_functions, has_diagnostic_characteristics,
    is_simple_constructor,
};
#[cfg(test)]
use pattern_matchers::matches_debug_pattern;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FunctionRole {
    PureLogic,    // Business logic, high test priority
    Orchestrator, // Coordinates other functions
    IOWrapper,    // Thin I/O layer
    EntryPoint,   // Main entry points
    PatternMatch, // Pattern matching function (low complexity)
    Debug,        // Debug/diagnostic functions (low test priority)
    Unknown,      // Cannot classify
}

pub fn classify_function_role(
    func: &FunctionMetrics,
    func_id: &FunctionId,
    call_graph: &CallGraph,
) -> FunctionRole {
    // Use a functional approach with classification rules
    // Note: AST is not available at this level, so we pass None
    // Full AST-based detection will be integrated when threading syn::ItemFn
    classify_by_rules(func, func_id, call_graph, None).unwrap_or_else(|| {
        // BUG-001 fix: Use purity analysis to prevent impure I/O functions from being
        // classified as PureLogic. If function is impure, classify as Unknown instead.
        if is_impure_function(func) {
            FunctionRole::Unknown
        } else {
            FunctionRole::PureLogic
        }
    })
}

// Pure function that applies classification rules in order
fn classify_by_rules(
    func: &FunctionMetrics,
    func_id: &FunctionId,
    call_graph: &CallGraph,
    syn_func: Option<&syn::ItemFn>,
) -> Option<FunctionRole> {
    // Entry point has highest precedence
    if is_entry_point(func_id, call_graph) {
        return Some(FunctionRole::EntryPoint);
    }

    // Check for debug/diagnostic functions early (Spec 119)
    if is_debug_function(func) {
        return Some(FunctionRole::Debug);
    }

    // Check for constructors BEFORE pattern matching (Spec 117 + 122)
    if is_constructor_enhanced(func, syn_func) {
        return Some(FunctionRole::IOWrapper);
    }

    // Check for enum converters (Spec 124)
    if let Some(syn_func) = syn_func {
        if is_enum_converter_enhanced(func, syn_func) {
            return Some(FunctionRole::IOWrapper);
        }
    }

    // Check for accessor methods (Spec 125)
    // This should come after enum converter detection but before pattern matching
    if is_accessor_method(func, syn_func) {
        return Some(FunctionRole::IOWrapper);
    }

    // Check for data flow classification (Spec 126) - only if enabled and AST available
    if let Some(syn_func) = syn_func {
        let config = crate::config::get_data_flow_classification_config();

        if config.enabled {
            let profile = analyze_data_flow(syn_func);

            // Only classify if high confidence
            if profile.confidence >= config.min_confidence
                && profile.transformation_ratio >= config.min_transformation_ratio
                && profile.business_logic_ratio < config.max_business_logic_ratio
            {
                return Some(FunctionRole::Orchestrator);
            }
        }
    }

    // Check for pattern matching functions (like detect_file_type)
    if is_pattern_matching_function(func, func_id) {
        return Some(FunctionRole::PatternMatch);
    }

    // Check I/O wrapper BEFORE orchestration
    if is_io_wrapper(func) {
        return Some(FunctionRole::IOWrapper);
    }

    // Only then check orchestration patterns
    if is_orchestrator(func, func_id, call_graph) {
        return Some(FunctionRole::Orchestrator);
    }

    None // Will default to PureLogic
}

// Pure function to check if a function is an entry point
fn is_entry_point(func_id: &FunctionId, call_graph: &CallGraph) -> bool {
    call_graph.is_entry_point(func_id) || is_entry_point_by_name(&func_id.name)
}

/// Check if a function is impure based on purity analysis (BUG-001 fix).
///
/// Used to prevent impure functions from being classified as PureLogic.
/// A function is considered impure if:
/// - `purity_level` is `Some(Impure)`
/// - `is_pure` is `Some(false)` (legacy field)
fn is_impure_function(func: &FunctionMetrics) -> bool {
    use crate::core::PurityLevel;

    // Check new purity_level field first
    if let Some(level) = func.purity_level {
        return level == PurityLevel::Impure;
    }

    // Fallback to legacy is_pure field
    func.is_pure == Some(false)
}

/// Detect simple accessor/getter methods (spec 125)
///
/// Identifies simple accessor and getter methods that should be classified as
/// IOWrapper instead of PureLogic to reduce their priority score.
///
/// # Detection Strategy
///
/// 1. Check name matches accessor patterns (id, name, get_*, is_*, etc.)
/// 2. Verify low complexity (cyclomatic ≤ 2, cognitive ≤ 1)
/// 3. Check function is short (< 10 lines, nesting ≤ 1)
/// 4. If AST available, verify body is simple accessor pattern
///
/// # Detected Patterns
///
/// **Simple accessors** (classified as IOWrapper):
/// - Direct field access: `id()`, `name()` returning field values
/// - Boolean checks: `is_active()`, `has_permission()` with simple conditions
/// - Type conversions: `as_str()`, `to_string()` with minimal logic
/// - Uses immutable `&self` reference only
/// - Very low complexity (cyclomatic ≤ 2, cognitive ≤ 1)
/// - Short length (< 10 lines, nesting ≤ 1)
///
/// **Complex methods** (NOT detected, remain PureLogic):
/// - Methods with calculations, iterations, or aggregations
/// - Methods calling other business logic functions
/// - Methods with complex control flow or multiple branches
fn is_accessor_method(func: &FunctionMetrics, syn_func: Option<&syn::ItemFn>) -> bool {
    let config = crate::config::get_accessor_detection_config();

    // Check if accessor detection is enabled
    if !config.enabled {
        return false;
    }

    // Check name matches accessor pattern
    if !matches_accessor_name(&func.name, &config) {
        return false;
    }

    // Check complexity is minimal
    if func.cyclomatic > config.max_cyclomatic
        || func.cognitive > config.max_cognitive
        || func.length >= config.max_length
        || func.nesting > config.max_nesting
    {
        return false;
    }

    // If AST available, verify body is simple
    if let Some(syn_func) = syn_func {
        if !is_simple_accessor_body(syn_func) {
            return false;
        }
    }

    true
}

pub fn get_role_multiplier(role: FunctionRole) -> f64 {
    // Get multipliers from configuration
    let config = crate::config::get_role_multipliers();

    match role {
        FunctionRole::PureLogic => config.pure_logic,
        FunctionRole::Orchestrator => config.orchestrator,
        FunctionRole::IOWrapper => config.io_wrapper,
        FunctionRole::EntryPoint => config.entry_point,
        FunctionRole::PatternMatch => config.pattern_match,
        FunctionRole::Debug => config.debug,
        FunctionRole::Unknown => config.unknown,
    }
}

// Semantic priority calculation removed per spec 58
// Role multipliers now provide the only role-based adjustment to avoid double penalties

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::FunctionMetrics;
    use crate::priority::call_graph::{CallGraph, CallType, FunctionCall, FunctionId};
    use std::path::PathBuf;

    fn create_test_metrics(
        name: &str,
        cyclomatic: u32,
        cognitive: u32,
        lines: usize,
    ) -> FunctionMetrics {
        FunctionMetrics {
            file: PathBuf::from("test.rs"),
            name: name.to_string(),
            line: 1,
            length: lines,
            cyclomatic,
            cognitive,
            nesting: 0,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        }
    }

    #[test]
    fn test_entry_point_classification() {
        let graph = CallGraph::new();
        let func = create_test_metrics("main", 5, 8, 50);
        let func_id = FunctionId::new(PathBuf::from("main.rs"), "main".to_string(), 1);

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(role, FunctionRole::EntryPoint);
    }

    #[test]
    fn test_orchestrator_classification() {
        let mut graph = CallGraph::new();
        let func = create_test_metrics("coordinate_tasks", 2, 3, 15);
        let func_id = FunctionId::new(
            PathBuf::from("coord.rs"),
            "coordinate_tasks".to_string(),
            10,
        );

        // Add the orchestrator function
        graph.add_function(func_id.clone(), false, false, 2, 15);

        // Add some worker functions it calls
        for i in 0..3 {
            let worker_id =
                FunctionId::new(PathBuf::from("worker.rs"), format!("worker_{i}"), i * 10);
            graph.add_function(worker_id.clone(), false, false, 8, 40);
            graph.add_call(crate::priority::call_graph::FunctionCall {
                caller: func_id.clone(),
                callee: worker_id,
                call_type: crate::priority::call_graph::CallType::Delegate,
            });
        }

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(role, FunctionRole::Orchestrator);
    }

    #[test]
    fn test_io_wrapper_classification() {
        let graph = CallGraph::new();
        let func = create_test_metrics("read_file", 1, 2, 10);
        let func_id = FunctionId::new(PathBuf::from("io.rs"), "read_file".to_string(), 5);

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(role, FunctionRole::IOWrapper);
    }

    #[test]
    fn test_io_orchestration_classification() {
        let graph = CallGraph::new();

        // Test case similar to output_unified_priorities:
        // - Has "output_" prefix (strong I/O pattern)
        // - 38 lines (within the 50 line limit)
        // - Cyclomatic 12 (from format branching)
        // - Nesting 3 (not deeply nested)
        let mut func = create_test_metrics("output_unified_priorities", 12, 19, 38);
        func.nesting = 3;

        let func_id = FunctionId::new(
            PathBuf::from("main.rs"),
            "output_unified_priorities".to_string(),
            861,
        );

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(role, FunctionRole::IOWrapper);

        // Test that high nesting disqualifies I/O orchestration
        func.nesting = 4;
        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(role, FunctionRole::PureLogic);
    }

    #[test]
    fn test_pure_logic_classification() {
        let graph = CallGraph::new();
        let func = create_test_metrics("calculate_risk", 8, 12, 60);
        let func_id = FunctionId::new(PathBuf::from("calc.rs"), "calculate_risk".to_string(), 20);

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(role, FunctionRole::PureLogic);
    }

    #[test]
    fn test_role_multipliers() {
        // Test with updated configuration values (BUG-001 fix: PureLogic now 0.7)
        assert_eq!(get_role_multiplier(FunctionRole::PureLogic), 0.7);
        assert_eq!(get_role_multiplier(FunctionRole::Orchestrator), 0.8);
        assert_eq!(get_role_multiplier(FunctionRole::IOWrapper), 0.7);
        assert_eq!(get_role_multiplier(FunctionRole::EntryPoint), 0.9);
        assert_eq!(get_role_multiplier(FunctionRole::PatternMatch), 0.6);
        assert_eq!(get_role_multiplier(FunctionRole::Unknown), 1.0);
    }

    #[test]
    fn test_formatting_function_not_orchestrator() {
        let mut graph = CallGraph::new();

        // Create a function like format_recommendation_box_header
        let func = create_test_metrics("format_recommendation_box_header", 1, 0, 9);
        let func_id = FunctionId::new(
            PathBuf::from("insights.rs"),
            "format_recommendation_box_header".to_string(),
            142,
        );

        // Add the function to the graph
        graph.add_function(func_id.clone(), false, false, 1, 9);

        // Add callees: calculate_dash_count and format (from macro)
        let callee1 = FunctionId::new(
            PathBuf::from("insights.rs"),
            "calculate_dash_count".to_string(),
            138,
        );
        let callee2 = FunctionId::new(PathBuf::from("std"), "format".to_string(), 1);

        graph.add_function(callee1.clone(), false, false, 1, 3);
        graph.add_function(callee2.clone(), false, false, 1, 1);

        graph.add_call(FunctionCall {
            caller: func_id.clone(),
            callee: callee1,
            call_type: CallType::Direct,
        });
        graph.add_call(FunctionCall {
            caller: func_id.clone(),
            callee: callee2,
            call_type: CallType::Direct,
        });

        // Test that it's not classified as orchestrator
        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::PureLogic,
            "Formatting function should be PureLogic, not Orchestrator"
        );

        // Verify it doesn't match delegation pattern
        assert!(
            !delegates_to_tested_functions(&func_id, &graph, 0.8),
            "Should not be considered delegation when calling std functions"
        );
    }

    #[test]
    fn test_actual_orchestrator_with_meaningful_callees() {
        let mut graph = CallGraph::new();

        // Create an actual orchestrator function
        let func = create_test_metrics("coordinate_workflow", 2, 3, 15);
        let func_id = FunctionId::new(
            PathBuf::from("workflow.rs"),
            "coordinate_workflow".to_string(),
            10,
        );

        graph.add_function(func_id.clone(), false, false, 2, 15);

        // Add meaningful callees (not std library)
        // Need at least 3 for the current config settings
        let callee1 = FunctionId::new(
            PathBuf::from("workflow.rs"),
            "process_step_one".to_string(),
            50,
        );
        let callee2 = FunctionId::new(
            PathBuf::from("workflow.rs"),
            "process_step_two".to_string(),
            100,
        );
        let callee3 = FunctionId::new(
            PathBuf::from("workflow.rs"),
            "process_step_three".to_string(),
            150,
        );

        graph.add_function(callee1.clone(), false, false, 5, 30);
        graph.add_function(callee2.clone(), false, false, 5, 30);
        graph.add_function(callee3.clone(), false, false, 5, 30);

        graph.add_call(FunctionCall {
            caller: func_id.clone(),
            callee: callee1,
            call_type: CallType::Direct,
        });
        graph.add_call(FunctionCall {
            caller: func_id.clone(),
            callee: callee2,
            call_type: CallType::Direct,
        });
        graph.add_call(FunctionCall {
            caller: func_id.clone(),
            callee: callee3,
            call_type: CallType::Direct,
        });

        // This should be classified as orchestrator
        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::Orchestrator,
            "Function coordinating multiple steps should be Orchestrator"
        );
    }

    #[test]
    fn test_orchestrator_with_error_handling_complexity_5() {
        let mut graph = CallGraph::new();

        // Function with complexity 5 from Result handling (spec 117)
        let func = create_test_metrics("coordinate_tasks", 5, 3, 20);
        let func_id = FunctionId::new(
            PathBuf::from("tasks.rs"),
            "coordinate_tasks".to_string(),
            10,
        );

        graph.add_function(func_id.clone(), false, false, 5, 20);

        // Add 4 meaningful callees (20% of 20 lines = 4 calls for delegation ratio)
        for i in 0..4 {
            let callee_id = FunctionId::new(
                PathBuf::from("worker.rs"),
                format!("worker_task_{}", i),
                i * 20,
            );
            graph.add_function(callee_id.clone(), false, false, 8, 40);
            graph.add_call(FunctionCall {
                caller: func_id.clone(),
                callee: callee_id,
                call_type: CallType::Direct,
            });
        }

        // Should be classified as orchestrator despite higher complexity
        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::Orchestrator,
            "Function with complexity 5 and good delegation ratio should be Orchestrator"
        );
    }

    #[test]
    fn test_delegation_ratio_calculation() {
        let func = create_test_metrics("orchestrator", 4, 2, 20);

        // Create test callees - 4 calls in 20 lines = 20% ratio
        let callees_vec: Vec<FunctionId> = (0..4)
            .map(|i| FunctionId::new(PathBuf::from("test.rs"), format!("callee_{}", i), i * 10))
            .collect();

        let callees: Vec<&FunctionId> = callees_vec.iter().collect();

        let ratio = calculate_delegation_ratio(&func, &callees);
        assert!(
            (ratio - 0.2).abs() < 0.01,
            "Expected delegation ratio of 0.2, got {}",
            ratio
        );
    }

    #[test]
    fn test_high_complexity_not_orchestrator() {
        let mut graph = CallGraph::new();

        // Function with complexity > 5 should not be orchestrator
        let func = create_test_metrics("complex_logic", 8, 10, 30);
        let func_id = FunctionId::new(PathBuf::from("logic.rs"), "complex_logic".to_string(), 10);

        graph.add_function(func_id.clone(), false, false, 8, 30);

        // Even with callees, complexity > 5 means not orchestrator
        for i in 0..3 {
            let callee_id =
                FunctionId::new(PathBuf::from("worker.rs"), format!("worker_{}", i), i * 20);
            graph.add_function(callee_id.clone(), false, false, 5, 20);
            graph.add_call(FunctionCall {
                caller: func_id.clone(),
                callee: callee_id,
                call_type: CallType::Direct,
            });
        }

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::PureLogic,
            "Function with complexity > 5 should be PureLogic, not Orchestrator"
        );
    }

    #[test]
    fn test_simple_constructor_detection() {
        // Test: ContextMatcher::any() case (spec 117)
        let func = create_test_metrics("any", 1, 0, 9);
        assert!(
            is_simple_constructor(&func),
            "any() should be detected as constructor"
        );

        // Test: Standard new() constructor
        let func = create_test_metrics("new", 1, 0, 5);
        assert!(
            is_simple_constructor(&func),
            "new() should be detected as constructor"
        );

        // Test: from_* constructor
        let func = create_test_metrics("from_config", 1, 0, 8);
        assert!(
            is_simple_constructor(&func),
            "from_config() should be detected as constructor"
        );

        // Test: with_* constructor
        let func = create_test_metrics("with_defaults", 2, 1, 12);
        assert!(
            is_simple_constructor(&func),
            "with_defaults() should be detected as constructor"
        );

        // Test: Complex factory should NOT match
        let func = create_test_metrics("create_complex", 8, 12, 50);
        assert!(
            !is_simple_constructor(&func),
            "Complex function should NOT be detected as constructor"
        );

        // Test: Long function should NOT match
        let func = create_test_metrics("new_complex", 2, 2, 25);
        assert!(
            !is_simple_constructor(&func),
            "Long function should NOT be detected as constructor"
        );

        // Test: High cognitive complexity should NOT match
        let func = create_test_metrics("new_with_logic", 2, 8, 10);
        assert!(
            !is_simple_constructor(&func),
            "High cognitive complexity should NOT be detected as constructor"
        );
    }

    #[test]
    fn test_constructor_classification_precedence() {
        let graph = CallGraph::new();
        let func = create_test_metrics("any", 1, 0, 9);
        let func_id = FunctionId::new(PathBuf::from("context/rules.rs"), "any".to_string(), 52);

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::IOWrapper,
            "Simple constructor should be classified as IOWrapper, not PureLogic"
        );
    }

    #[test]
    fn test_constructor_name_patterns() {
        // Test exact matches
        assert!(is_simple_constructor(&create_test_metrics("new", 1, 0, 5)));
        assert!(is_simple_constructor(&create_test_metrics(
            "default", 1, 0, 5
        )));
        assert!(is_simple_constructor(&create_test_metrics(
            "empty", 1, 0, 5
        )));
        assert!(is_simple_constructor(&create_test_metrics("zero", 1, 0, 5)));

        // Test prefix matches
        assert!(is_simple_constructor(&create_test_metrics(
            "from_str", 1, 0, 8
        )));
        assert!(is_simple_constructor(&create_test_metrics(
            "with_capacity",
            2,
            1,
            10
        )));
        assert!(is_simple_constructor(&create_test_metrics(
            "create_default",
            1,
            0,
            7
        )));
        assert!(is_simple_constructor(&create_test_metrics(
            "make_instance",
            1,
            0,
            6
        )));
        assert!(is_simple_constructor(&create_test_metrics(
            "build_config",
            2,
            2,
            12
        )));

        // Test non-constructor names
        let func = create_test_metrics("calculate_score", 1, 0, 5);
        assert!(
            !is_simple_constructor(&func),
            "Non-constructor name should not match"
        );
    }

    #[test]
    fn test_constructor_complexity_thresholds() {
        // Test at threshold boundaries
        let func = create_test_metrics("new", 2, 3, 14);
        assert!(
            is_simple_constructor(&func),
            "At threshold limits should match"
        );

        // Test just over cyclomatic threshold
        let func = create_test_metrics("new", 3, 2, 10);
        assert!(
            !is_simple_constructor(&func),
            "Over cyclomatic threshold should not match"
        );

        // Test just over cognitive threshold
        let func = create_test_metrics("new", 1, 4, 10);
        assert!(
            !is_simple_constructor(&func),
            "Over cognitive threshold should not match"
        );

        // Test just over length threshold
        let func = create_test_metrics("new", 1, 2, 15);
        assert!(
            !is_simple_constructor(&func),
            "Over length threshold should not match"
        );

        // Test nesting threshold
        let mut func = create_test_metrics("new", 1, 2, 10);
        func.nesting = 2;
        assert!(
            !is_simple_constructor(&func),
            "Over nesting threshold should not match"
        );
    }

    #[test]
    fn test_ast_detects_non_standard_constructor() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn create_default_client() -> Self {
                Self {
                    timeout: Duration::from_secs(30),
                    retries: 3,
                }
            }
        };

        let func = create_test_metrics("create_default_client", 1, 0, 5);

        // With AST: should be detected as constructor
        assert!(
            is_constructor_enhanced(&func, Some(&source)),
            "AST should detect non-standard constructor name"
        );

        // Without AST: fallback to name-based (should also match due to create_ prefix)
        assert!(
            is_constructor_enhanced(&func, None),
            "Should fallback to name-based detection"
        );
    }

    #[test]
    fn test_ast_detects_result_self_constructor() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn try_new(value: i32) -> Result<Self, Error> {
                if value > 0 {
                    Ok(Self { value })
                } else {
                    Err(Error::InvalidValue)
                }
            }
        };

        let func = create_test_metrics("try_new", 2, 1, 8);

        // With AST: should be detected as constructor (Result<Self>)
        assert!(
            is_constructor_enhanced(&func, Some(&source)),
            "AST should detect Result<Self> constructor"
        );
    }

    #[test]
    fn test_ast_rejects_loop_in_constructor() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn process_items() -> Self {
                let mut result = Self::new();
                for item in items {
                    result.add(item);
                }
                result
            }
        };

        let func = create_test_metrics("process_items", 2, 3, 8);

        // Should NOT be detected as constructor due to loop
        assert!(
            !is_constructor_enhanced(&func, Some(&source)),
            "AST should reject constructors with loops"
        );
    }

    #[test]
    fn test_ast_fallback_when_not_returning_self() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn calculate_value() -> i32 {
                42
            }
        };

        let func = create_test_metrics("calculate_value", 1, 0, 3);

        // Should fallback to name-based (which will reject non-constructor name)
        assert!(
            !is_constructor_enhanced(&func, Some(&source)),
            "AST should fallback when not returning Self"
        );
    }

    #[test]
    fn test_enum_converter_framework_type_name() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn name(&self) -> &'static str {
                match self {
                    FrameworkType::Django => "Django",
                    FrameworkType::Flask => "Flask",
                    FrameworkType::PyQt => "PyQt",
                }
            }
        };

        let func = create_test_metrics("name", 3, 0, 7);

        // Should be detected as enum converter
        assert!(
            is_enum_converter_enhanced(&func, &source),
            "FrameworkType::name should be detected as enum converter"
        );
    }

    #[test]
    fn test_enum_converter_builtin_exception_as_str() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            fn as_str(&self) -> &str {
                match self {
                    Self::BaseException => "BaseException",
                    Self::ValueError => "ValueError",
                    Self::TypeError => "TypeError",
                }
            }
        };

        let func = create_test_metrics("as_str", 3, 0, 7);

        // Should be detected as enum converter
        assert!(
            is_enum_converter_enhanced(&func, &source),
            "BuiltinException::as_str should be detected as enum converter"
        );
    }

    #[test]
    fn test_enum_converter_with_function_calls_not_detected() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn process(&self) -> String {
                match self {
                    Variant::A => format!("A"),
                    Variant::B => format!("B"),
                }
            }
        };

        let func = create_test_metrics("process", 2, 1, 7);

        // Should NOT be detected (has function calls)
        assert!(
            !is_enum_converter_enhanced(&func, &source),
            "Converter with function calls should NOT be detected"
        );
    }

    #[test]
    fn test_enum_converter_high_cognitive_complexity_rejected() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn name(&self) -> &'static str {
                match self {
                    Type::A => "A",
                    Type::B => "B",
                }
            }
        };

        let func = create_test_metrics("name", 2, 5, 7); // cognitive = 5

        // Should be rejected due to high cognitive complexity
        assert!(
            !is_enum_converter_enhanced(&func, &source),
            "High cognitive complexity should be rejected"
        );
    }

    #[test]
    fn test_enum_converter_classification_precedence() {
        use syn::parse_quote;

        let graph = CallGraph::new();

        let source: syn::ItemFn = parse_quote! {
            pub fn name(&self) -> &'static str {
                match self {
                    FrameworkType::Django => "Django",
                    FrameworkType::Flask => "Flask",
                }
            }
        };

        let func = create_test_metrics("name", 2, 0, 7);
        let func_id = FunctionId::new(PathBuf::from("framework.rs"), "name".to_string(), 10);

        let role = classify_by_rules(&func, &func_id, &graph, Some(&source));
        assert_eq!(
            role,
            Some(FunctionRole::IOWrapper),
            "Enum converter should be classified as IOWrapper"
        );
    }

    #[test]
    fn test_ast_detection_can_be_disabled() {
        use syn::parse_quote;

        let source: syn::ItemFn = parse_quote! {
            pub fn create_default_client() -> Self {
                Self { field: 0 }
            }
        };

        let func = create_test_metrics("create_default_client", 1, 0, 5);

        // When AST detection is disabled via config, should use name-based only
        // NOTE: This test assumes config can be set, which currently uses a static global
        // In a real implementation, we'd inject config or use a test-specific config

        // With AST enabled (default), should detect
        assert!(
            is_constructor_enhanced(&func, Some(&source)),
            "Should detect with AST when enabled"
        );

        // Without AST parameter (None), should fallback to name-based
        assert!(
            is_constructor_enhanced(&func, None),
            "Should fallback to name-based when AST unavailable"
        );
    }

    // Accessor detection tests (spec 125)

    #[test]
    fn test_simple_field_accessor_detected() {
        let metrics = create_test_metrics("id", 1, 0, 3);
        assert!(
            is_accessor_method(&metrics, None),
            "id() should be detected as accessor"
        );

        let metrics = create_test_metrics("get_name", 1, 0, 5);
        assert!(
            is_accessor_method(&metrics, None),
            "get_name() should be detected as accessor"
        );
    }

    #[test]
    fn test_bool_accessor_detected() {
        let metrics = create_test_metrics("is_active", 2, 1, 8);
        assert!(
            is_accessor_method(&metrics, None),
            "is_active() should be detected as accessor"
        );

        let metrics = create_test_metrics("has_permission", 2, 0, 5);
        assert!(
            is_accessor_method(&metrics, None),
            "has_permission() should be detected as accessor"
        );
    }

    #[test]
    fn test_converter_method_detected() {
        let metrics = create_test_metrics("as_str", 1, 0, 3);
        assert!(
            is_accessor_method(&metrics, None),
            "as_str() should be detected as accessor"
        );

        let metrics = create_test_metrics("to_string", 1, 0, 4);
        assert!(
            is_accessor_method(&metrics, None),
            "to_string() should be detected as accessor"
        );
    }

    #[test]
    fn test_complex_method_not_detected_as_accessor() {
        // High complexity despite accessor name
        let metrics = create_test_metrics("get_value", 5, 3, 20);
        assert!(
            !is_accessor_method(&metrics, None),
            "Complex method should not be detected as accessor"
        );
    }

    #[test]
    fn test_business_logic_not_misclassified_as_accessor() {
        // Business logic method
        let metrics = create_test_metrics("calculate_total", 4, 2, 15);
        assert!(
            !is_accessor_method(&metrics, None),
            "Business logic should not be detected as accessor"
        );
    }

    #[test]
    fn test_ast_body_validation_for_accessor() {
        use syn::parse_quote;

        let code: syn::ItemFn = parse_quote! {
            pub fn id(&self) -> u32 {
                self.id
            }
        };

        assert!(
            is_simple_accessor_body(&code),
            "Simple field access should be valid accessor body"
        );
    }

    #[test]
    fn test_accessor_side_effect_rejected() {
        use syn::parse_quote;

        let code: syn::ItemFn = parse_quote! {
            pub fn get_value(&self) -> i32 {
                self.counter.fetch_add(1, Ordering::SeqCst);
                self.value
            }
        };

        assert!(
            !is_simple_accessor_body(&code),
            "Accessor with side effects should be rejected"
        );
    }

    #[test]
    fn test_accessor_classification_integration() {
        let graph = CallGraph::new();

        // Simple accessor should be IOWrapper
        let func = create_test_metrics("id", 1, 0, 3);
        let func_id = FunctionId::new(PathBuf::from("user.rs"), "id".to_string(), 10);

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::IOWrapper,
            "Simple accessor should be classified as IOWrapper"
        );
    }

    #[test]
    fn test_accessor_with_reference_return() {
        use syn::parse_quote;

        let code: syn::ItemFn = parse_quote! {
            pub fn name(&self) -> &str {
                &self.name
            }
        };

        assert!(
            is_simple_accessor_body(&code),
            "Reference to field should be valid accessor body"
        );
    }

    #[test]
    fn test_accessor_with_method_call() {
        use syn::parse_quote;

        let code: syn::ItemFn = parse_quote! {
            pub fn name(&self) -> String {
                self.name.clone()
            }
        };

        assert!(
            is_simple_accessor_body(&code),
            "Field with .clone() should be valid accessor body"
        );
    }

    #[test]
    fn test_accessor_single_word_patterns() {
        // Test all single-word patterns
        for name in &[
            "id", "name", "value", "kind", "type", "status", "code", "key", "index",
        ] {
            let metrics = create_test_metrics(name, 1, 0, 3);
            assert!(
                is_accessor_method(&metrics, None),
                "{} should be detected as accessor",
                name
            );
        }
    }

    #[test]
    fn test_accessor_prefix_patterns() {
        // Test all prefix patterns
        for (name, expected) in &[
            ("get_value", true),
            ("is_active", true),
            ("has_data", true),
            ("can_execute", true),
            ("should_run", true),
            ("as_str", true),
            ("to_string", true),
            ("into_iter", true),
        ] {
            let metrics = create_test_metrics(name, 1, 0, 5);
            assert_eq!(
                is_accessor_method(&metrics, None),
                *expected,
                "{} accessor detection mismatch",
                name
            );
        }
    }

    #[test]
    fn test_accessor_complexity_thresholds() {
        // At threshold (should pass)
        let metrics = create_test_metrics("get_value", 2, 1, 9);
        assert!(
            is_accessor_method(&metrics, None),
            "At threshold should be detected"
        );

        // Over cyclomatic threshold (should fail)
        let metrics = create_test_metrics("get_value", 3, 1, 9);
        assert!(
            !is_accessor_method(&metrics, None),
            "Over cyclomatic threshold should not be detected"
        );

        // Over cognitive threshold (should fail)
        let metrics = create_test_metrics("get_value", 2, 2, 9);
        assert!(
            !is_accessor_method(&metrics, None),
            "Over cognitive threshold should not be detected"
        );

        // Over length threshold (should fail)
        let metrics = create_test_metrics("get_value", 2, 1, 10);
        assert!(
            !is_accessor_method(&metrics, None),
            "At or over length threshold should not be detected"
        );
    }

    #[test]
    fn test_accessor_requires_immutable_self() {
        use syn::parse_quote;

        // Immutable self - should pass
        let code: syn::ItemFn = parse_quote! {
            pub fn value(&self) -> i32 {
                self.value
            }
        };

        assert!(
            is_simple_accessor_body(&code),
            "Immutable self should be valid"
        );

        // Mutable self - should fail
        let code: syn::ItemFn = parse_quote! {
            pub fn value(&mut self) -> i32 {
                self.value
            }
        };

        assert!(
            !is_simple_accessor_body(&code),
            "Mutable self should be rejected"
        );
    }

    #[test]
    fn test_accessor_precedence_in_classification() {
        use syn::parse_quote;

        let graph = CallGraph::new();

        let code: syn::ItemFn = parse_quote! {
            pub fn id(&self) -> u32 {
                self.id
            }
        };

        let func = create_test_metrics("id", 1, 0, 3);
        let func_id = FunctionId::new(PathBuf::from("test.rs"), "id".to_string(), 10);

        let role = classify_by_rules(&func, &func_id, &graph, Some(&code));
        assert_eq!(
            role,
            Some(FunctionRole::IOWrapper),
            "Accessor should be classified as IOWrapper"
        );
    }

    // Debug role detection tests (spec 119)

    #[test]
    fn test_debug_function_with_diagnostics_suffix() {
        let func = create_test_metrics("handle_call_graph_diagnostics", 5, 3, 20);
        assert!(
            is_debug_function(&func),
            "Function with _diagnostics suffix should be detected as debug"
        );
    }

    #[test]
    fn test_debug_function_with_debug_prefix() {
        let func = create_test_metrics("debug_print_info", 3, 2, 15);
        assert!(
            is_debug_function(&func),
            "Function with debug_ prefix should be detected as debug"
        );
    }

    #[test]
    fn test_print_function_detected_as_debug() {
        let func = create_test_metrics("print_statistics", 4, 3, 18);
        assert!(
            is_debug_function(&func),
            "Function with print_ prefix should be detected as debug"
        );
    }

    #[test]
    fn test_dump_function_detected_as_debug() {
        let func = create_test_metrics("dump_state", 2, 1, 10);
        assert!(
            is_debug_function(&func),
            "Function with dump_ prefix should be detected as debug"
        );
    }

    #[test]
    fn test_trace_function_detected_as_debug() {
        let func = create_test_metrics("trace_execution", 3, 2, 12);
        assert!(
            is_debug_function(&func),
            "Function with trace_ prefix should be detected as debug"
        );
    }

    #[test]
    fn test_high_complexity_debug_name_not_debug() {
        // High complexity should prevent misclassification
        let func = create_test_metrics("debug_complex_algorithm", 15, 12, 50);
        assert!(
            !is_debug_function(&func),
            "High complexity function should not be classified as debug even with debug name"
        );
    }

    #[test]
    fn test_debug_stats_function() {
        let func = create_test_metrics("calculate_stats", 4, 3, 20);
        assert!(
            is_debug_function(&func),
            "Function ending with _stats should be detected as debug"
        );
    }

    #[test]
    fn test_debug_classification_integration() {
        let graph = CallGraph::new();
        // Use a function that clearly matches debug pattern without entry point pattern
        let func = create_test_metrics("print_call_graph_diagnostics", 5, 3, 20);
        let func_id = FunctionId::new(
            PathBuf::from("commands/analyze.rs"),
            "print_call_graph_diagnostics".to_string(),
            396,
        );

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::Debug,
            "Diagnostic function should be classified as Debug role"
        );
    }

    #[test]
    fn test_entry_point_takes_precedence_over_debug() {
        let graph = CallGraph::new();
        // Function with both entry point and debug patterns - entry point wins
        let func = create_test_metrics("handle_diagnostics", 5, 3, 20);
        let func_id = FunctionId::new(
            PathBuf::from("commands/analyze.rs"),
            "handle_diagnostics".to_string(),
            396,
        );

        let role = classify_function_role(&func, &func_id, &graph);
        assert_eq!(
            role,
            FunctionRole::EntryPoint,
            "Entry point pattern should take precedence over debug pattern"
        );
    }

    #[test]
    fn test_business_logic_not_misclassified_as_debug() {
        let func = create_test_metrics("calculate_complexity", 8, 5, 30);
        assert!(
            !is_debug_function(&func),
            "Business logic function should not be detected as debug"
        );
    }

    #[test]
    fn test_debug_role_multiplier() {
        let multiplier = get_role_multiplier(FunctionRole::Debug);
        assert_eq!(
            multiplier, 0.3,
            "Debug role should have lowest multiplier (0.3)"
        );
    }

    #[test]
    fn test_matches_debug_pattern() {
        assert!(matches_debug_pattern("debug_foo"));
        assert!(matches_debug_pattern("print_bar"));
        assert!(matches_debug_pattern("dump_state"));
        assert!(matches_debug_pattern("trace_execution"));
        assert!(matches_debug_pattern("foo_diagnostics"));
        assert!(matches_debug_pattern("bar_debug"));
        assert!(matches_debug_pattern("baz_stats"));
        assert!(matches_debug_pattern("test_diagnostics_helper"));

        // Should not match
        assert!(!matches_debug_pattern("calculate"));
        assert!(!matches_debug_pattern("process"));
        assert!(!matches_debug_pattern("validate"));
    }

    #[test]
    fn test_diagnostic_characteristics() {
        // Should match: simple output function
        let func = create_test_metrics("print_output", 3, 2, 15);
        assert!(
            has_diagnostic_characteristics(&func),
            "Simple print function should have diagnostic characteristics"
        );

        // Should not match: complex function
        let func = create_test_metrics("print_complex", 10, 8, 40);
        assert!(
            !has_diagnostic_characteristics(&func),
            "Complex function should not have diagnostic characteristics"
        );

        // Should not match: no output I/O pattern
        let func = create_test_metrics("calculate_total", 3, 2, 15);
        assert!(
            !has_diagnostic_characteristics(&func),
            "Non-output function should not have diagnostic characteristics"
        );

        // Should not match: read/write operations (not diagnostic output)
        let func = create_test_metrics("read_file", 3, 2, 15);
        assert!(
            !has_diagnostic_characteristics(&func),
            "Read/write operations should not have diagnostic characteristics"
        );
    }
}