features-cli 0.12.0

A CLI tool for discovering the features in a folder
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
use anyhow::{Context, Result};
use git2::Repository;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::dependency_resolver::{
    build_file_to_feature_map, collect_feature_info, resolve_feature_dependencies,
};
use crate::feature_metadata_detector::{self, FeatureMetadataMap};
use crate::features_toml_parser::{find_features_toml, read_features_toml};
use crate::git_helper::get_all_commits_by_path;
use crate::import_detector::{ImportStatement, build_file_map, scan_file_for_imports};
use crate::models::{Change, Feature, Stats};
use crate::readme_parser::read_readme_info;

fn is_documentation_directory(dir_path: &Path) -> bool {
    let dir_name = dir_path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("");

    // Common documentation directory names
    let doc_dirs = ["docs", "__docs__", ".docs"];

    doc_dirs.contains(&dir_name.to_lowercase().as_str())
}

fn is_inside_documentation_directory(dir_path: &Path) -> bool {
    // Check if any parent directory is a documentation directory
    for ancestor in dir_path.ancestors().skip(1) {
        if is_documentation_directory(ancestor) {
            return true;
        }
    }
    false
}

fn is_direct_subfolder_of_features(dir_path: &Path) -> bool {
    if let Some(parent) = dir_path.parent()
        && let Some(parent_name) = parent.file_name().and_then(|name| name.to_str())
    {
        return parent_name == "features";
    }
    false
}

/// Check if a directory is ignored, i.e. matches (or is nested inside) one of the
/// paths passed via `--ignore-path`. Ignored directories and all their subfolders
/// are excluded from feature detection entirely.
fn is_ignored_path(dir_path: &Path, ignore_paths: &[PathBuf]) -> bool {
    let Ok(canonical) = fs::canonicalize(dir_path) else {
        return false;
    };

    ignore_paths
        .iter()
        .any(|ignored| canonical.starts_with(ignored))
}

fn find_readme_file(dir_path: &Path) -> Option<std::path::PathBuf> {
    let readme_candidates = ["README.md", "README.mdx"];

    for candidate in &readme_candidates {
        let readme_path = dir_path.join(candidate);
        if readme_path.exists() {
            return Some(readme_path);
        }
    }

    None
}

/// Read the `feature` boolean from a directory's README front matter, if present.
fn feature_flag_in_readme(dir_path: &Path) -> Option<bool> {
    let readme_path = find_readme_file(dir_path)?;
    let content = fs::read_to_string(&readme_path).ok()?;

    // Check if content starts with YAML front matter (---)
    let stripped = content.strip_prefix("---\n")?;
    let end_pos = stripped.find("\n---\n")?;
    let yaml_content = &stripped[..end_pos];

    // Parse YAML front matter
    let yaml_value = serde_yaml::from_str::<serde_yaml::Value>(yaml_content).ok()?;
    let mapping = yaml_value.as_mapping()?;
    let feature_value = mapping.get(serde_yaml::Value::String("feature".to_string()))?;

    feature_value.as_bool()
}

/// Check if a directory has a README with `feature: true` in front matter
fn has_feature_flag_in_readme(dir_path: &Path) -> bool {
    feature_flag_in_readme(dir_path) == Some(true)
}

/// Check if a directory has a README with `feature: false` in front matter.
/// This is used to explicitly skip a directory from being treated as a feature,
/// even when it would otherwise qualify (e.g. a direct subfolder of `features`).
fn has_feature_false_in_readme(dir_path: &Path) -> bool {
    feature_flag_in_readme(dir_path) == Some(false)
}

/// Check if a directory should be treated as a feature
fn is_feature_directory(dir_path: &Path) -> bool {
    // Skip documentation directories
    if is_documentation_directory(dir_path) || is_inside_documentation_directory(dir_path) {
        return false;
    }

    // An explicit `feature: false` in the README always skips this directory
    // from being a feature itself, even if it would otherwise qualify (e.g. a
    // direct subfolder of `features`). Its own subfolders are still scanned
    // normally, so any nested features it contains are kept.
    if has_feature_false_in_readme(dir_path) {
        return false;
    }

    // Check if it's a direct subfolder of "features" (existing behavior)
    if is_direct_subfolder_of_features(dir_path) {
        return true;
    }

    // Check if the directory has a README with feature: true
    has_feature_flag_in_readme(dir_path)
}

pub fn list_files_recursive(dir: &Path, ignore_paths: &[PathBuf]) -> Result<Vec<Feature>> {
    // Scan entire base_path for feature metadata once
    let feature_metadata =
        feature_metadata_detector::scan_directory_for_feature_metadata(dir).unwrap_or_default();

    // First pass: build feature structure without dependencies
    let mut features =
        list_files_recursive_impl(dir, dir, None, None, &feature_metadata, ignore_paths)?;

    // Second pass: scan for imports and resolve dependencies
    populate_dependencies(&mut features, dir)?;

    Ok(features)
}

pub fn list_files_recursive_with_changes(
    dir: &Path,
    ignore_paths: &[PathBuf],
) -> Result<Vec<Feature>> {
    // Get all commits once at the beginning for efficiency
    let all_commits = get_all_commits_by_path(dir).unwrap_or_default();
    // Scan entire base_path for feature metadata once
    let feature_metadata =
        feature_metadata_detector::scan_directory_for_feature_metadata(dir).unwrap_or_default();

    // First pass: build feature structure without dependencies
    let mut features = list_files_recursive_impl(
        dir,
        dir,
        Some(&all_commits),
        None,
        &feature_metadata,
        ignore_paths,
    )?;

    // Second pass: scan for imports and resolve dependencies
    populate_dependencies(&mut features, dir)?;

    Ok(features)
}

/// Populate dependencies for all features by scanning imports
fn populate_dependencies(features: &mut [Feature], base_path: &Path) -> Result<()> {
    // Build file map for quick path resolution
    let file_map = build_file_map(base_path);

    // Collect all feature info (flat list with paths)
    let mut feature_info_list = Vec::new();
    collect_feature_info(features, None, &mut feature_info_list);

    // Build file-to-feature mapping
    let file_to_feature_map = build_file_to_feature_map(&feature_info_list, base_path);

    // Build feature path to name mapping (path is the unique identifier)
    let mut feature_path_to_name_map = HashMap::new();
    for info in &feature_info_list {
        feature_path_to_name_map.insert(info.path.to_string_lossy().to_string(), info.name.clone());
    }

    // Scan all files in each feature for imports
    let mut feature_imports: HashMap<String, Vec<ImportStatement>> = HashMap::new();

    for feature_info in &feature_info_list {
        let feature_path = base_path.join(&feature_info.path);
        let imports = scan_feature_directory_for_imports(&feature_path);
        // Use feature path as key instead of name to handle features with duplicate names
        feature_imports.insert(feature_info.path.to_string_lossy().to_string(), imports);
    }

    // Now populate dependencies in the feature tree
    populate_dependencies_recursive(
        features,
        base_path,
        &feature_imports,
        &file_to_feature_map,
        &feature_path_to_name_map,
        &file_map,
    );

    Ok(())
}

/// Scan a feature directory for all import statements
fn scan_feature_directory_for_imports(feature_path: &Path) -> Vec<ImportStatement> {
    let mut all_imports = Vec::new();

    if let Ok(entries) = fs::read_dir(feature_path) {
        // Collect and sort entries alphabetically by filename
        let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
        paths.sort_by(|a, b| {
            let name_a = a.file_name().unwrap_or_default().to_string_lossy();
            let name_b = b.file_name().unwrap_or_default().to_string_lossy();
            name_a.cmp(&name_b)
        });

        for path in paths {
            // Skip documentation directories
            if is_documentation_directory(&path) {
                continue;
            }

            if path.is_file() {
                if let Ok(imports) = scan_file_for_imports(&path) {
                    all_imports.extend(imports);
                }
            } else if path.is_dir() {
                // Skip 'features' subdirectory (contains nested features)
                let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if dir_name == "features" {
                    continue;
                }

                // Skip nested feature directories (check if it's a direct child of "features" directory with README)
                if is_feature_directory(&path) {
                    continue;
                }

                // Recursively scan subdirectories
                let nested_imports = scan_feature_directory_for_imports(&path);
                all_imports.extend(nested_imports);
            }
        }
    }

    all_imports
}

/// Recursively populate dependencies in the feature tree
fn populate_dependencies_recursive(
    features: &mut [Feature],
    base_path: &Path,
    feature_imports: &HashMap<String, Vec<ImportStatement>>,
    file_to_feature_map: &HashMap<std::path::PathBuf, String>,
    feature_path_to_name_map: &HashMap<String, String>,
    file_map: &HashMap<String, std::path::PathBuf>,
) {
    for feature in features {
        // Get imports for this feature using path as key (not name, since multiple features can have same name)
        if let Some(imports) = feature_imports.get(&feature.path) {
            let feature_path = std::path::PathBuf::from(&feature.path);

            // Resolve dependencies
            let dependencies = resolve_feature_dependencies(
                &feature.name,
                &feature_path,
                base_path,
                imports,
                file_to_feature_map,
                feature_path_to_name_map,
                file_map,
            );

            feature.dependencies = dependencies;
        }

        // Recursively process nested features
        if !feature.features.is_empty() {
            populate_dependencies_recursive(
                &mut feature.features,
                base_path,
                feature_imports,
                file_to_feature_map,
                feature_path_to_name_map,
                file_map,
            );
        }
    }
}

fn read_decision_files(feature_path: &Path) -> Result<Vec<String>> {
    let mut decisions = Vec::new();

    // Check both "decision" and "decisions" folder names
    let decision_paths = [
        feature_path.join(".docs").join("decisions"),
        feature_path.join("__docs__").join("decisions"),
    ];

    for decisions_dir in &decision_paths {
        if decisions_dir.exists() && decisions_dir.is_dir() {
            let entries = fs::read_dir(decisions_dir).with_context(|| {
                format!(
                    "could not read decisions directory `{}`",
                    decisions_dir.display()
                )
            })?;

            // Collect all decision file paths first
            let mut decision_paths_vec = Vec::new();

            for entry in entries {
                let entry = entry?;
                let path = entry.path();

                // Skip README.md files and only process .md files
                if path.is_file()
                    && let Some(file_name) = path.file_name()
                {
                    let file_name_str = file_name.to_string_lossy();
                    if file_name_str.ends_with(".md") && file_name_str != "README.md" {
                        decision_paths_vec.push(path);
                    }
                }
            }

            // Sort decision files alphabetically by filename
            decision_paths_vec.sort_by(|a, b| {
                let name_a = a.file_name().unwrap_or_default().to_string_lossy();
                let name_b = b.file_name().unwrap_or_default().to_string_lossy();
                name_a.cmp(&name_b)
            });

            // Read the sorted files
            for path in decision_paths_vec {
                let content = fs::read_to_string(&path).with_context(|| {
                    format!("could not read decision file `{}`", path.display())
                })?;
                decisions.push(content);
            }

            break; // If we found one of the directories, don't check the other
        }
    }

    Ok(decisions)
}

/// Count the number of files in a feature directory (excluding documentation)
fn count_files(feature_path: &Path, nested_feature_paths: &[String]) -> usize {
    let mut file_count = 0;

    if let Ok(entries) = fs::read_dir(feature_path) {
        // Collect and sort entries alphabetically by filename
        let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
        paths.sort_by(|a, b| {
            let name_a = a.file_name().unwrap_or_default().to_string_lossy();
            let name_b = b.file_name().unwrap_or_default().to_string_lossy();
            name_a.cmp(&name_b)
        });

        for path in paths {
            let path_str = path.to_string_lossy().to_string();

            // Skip documentation directories
            if is_documentation_directory(&path) {
                continue;
            }

            // Skip nested feature directories
            if nested_feature_paths
                .iter()
                .any(|nfp| path_str.starts_with(nfp))
            {
                continue;
            }

            if path.is_file() {
                file_count += 1;
            } else if path.is_dir() {
                // Recursively count files in subdirectories
                file_count += count_files(&path, nested_feature_paths);
            }
        }
    }

    file_count
}

/// Count the total number of lines in all files in a feature directory (excluding documentation)
fn count_lines(feature_path: &Path, nested_feature_paths: &[String]) -> usize {
    let mut line_count = 0;

    if let Ok(entries) = fs::read_dir(feature_path) {
        // Collect and sort entries alphabetically by filename
        let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
        paths.sort_by(|a, b| {
            let name_a = a.file_name().unwrap_or_default().to_string_lossy();
            let name_b = b.file_name().unwrap_or_default().to_string_lossy();
            name_a.cmp(&name_b)
        });

        for path in paths {
            let path_str = path.to_string_lossy().to_string();

            // Skip documentation directories
            if is_documentation_directory(&path) {
                continue;
            }

            // Skip nested feature directories
            if nested_feature_paths
                .iter()
                .any(|nfp| path_str.starts_with(nfp))
            {
                continue;
            }

            if path.is_file() {
                // Try to read the file and count lines
                if let Ok(content) = fs::read_to_string(&path) {
                    line_count += content.lines().count();
                }
            } else if path.is_dir() {
                // Recursively count lines in subdirectories
                line_count += count_lines(&path, nested_feature_paths);
            }
        }
    }

    line_count
}

/// Count the total number of TODO comments in all files in a feature directory (excluding documentation)
fn count_todos(feature_path: &Path, nested_feature_paths: &[String]) -> usize {
    let mut todo_count = 0;

    if let Ok(entries) = fs::read_dir(feature_path) {
        // Collect and sort entries alphabetically by filename
        let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
        paths.sort_by(|a, b| {
            let name_a = a.file_name().unwrap_or_default().to_string_lossy();
            let name_b = b.file_name().unwrap_or_default().to_string_lossy();
            name_a.cmp(&name_b)
        });

        for path in paths {
            let path_str = path.to_string_lossy().to_string();

            // Skip documentation directories
            if is_documentation_directory(&path) {
                continue;
            }

            // Skip nested feature directories
            if nested_feature_paths
                .iter()
                .any(|nfp| path_str.starts_with(nfp))
            {
                continue;
            }

            if path.is_file() {
                // Try to read the file and count TODO comments
                if let Ok(content) = fs::read_to_string(&path) {
                    for line in content.lines() {
                        // Look for TODO in comments (case-insensitive)
                        let line_upper = line.to_uppercase();
                        if line_upper.contains("TODO") {
                            todo_count += 1;
                        }
                    }
                }
            } else if path.is_dir() {
                // Recursively count TODOs in subdirectories
                todo_count += count_todos(&path, nested_feature_paths);
            }
        }
    }

    todo_count
}

/// Get the paths affected by a specific commit
fn get_commit_affected_paths(repo: &Repository, commit_hash: &str) -> Vec<String> {
    let Ok(oid) = git2::Oid::from_str(commit_hash) else {
        return Vec::new();
    };

    let Ok(commit) = repo.find_commit(oid) else {
        return Vec::new();
    };

    let mut paths = Vec::new();

    // For the first commit (no parents), get all files in the tree
    if commit.parent_count() == 0 {
        if let Ok(tree) = commit.tree() {
            collect_all_tree_paths(repo, &tree, "", &mut paths);
        }
        return paths;
    }

    // For commits with parents, check the diff
    let Ok(tree) = commit.tree() else {
        return Vec::new();
    };

    let Ok(parent) = commit.parent(0) else {
        return Vec::new();
    };

    let Ok(parent_tree) = parent.tree() else {
        return Vec::new();
    };

    if let Ok(diff) = repo.diff_tree_to_tree(Some(&parent_tree), Some(&tree), None) {
        let _ = diff.foreach(
            &mut |delta, _| {
                if let Some(path) = delta.new_file().path()
                    && let Some(path_str) = path.to_str()
                {
                    paths.push(path_str.to_string());
                }
                if let Some(path) = delta.old_file().path()
                    && let Some(path_str) = path.to_str()
                    && !paths.contains(&path_str.to_string())
                {
                    paths.push(path_str.to_string());
                }
                true
            },
            None,
            None,
            None,
        );
    }

    paths
}

/// Collect all file paths in a tree (helper for get_commit_affected_paths)
fn collect_all_tree_paths(
    repo: &Repository,
    tree: &git2::Tree,
    prefix: &str,
    paths: &mut Vec<String>,
) {
    for entry in tree.iter() {
        if let Some(name) = entry.name() {
            let path = if prefix.is_empty() {
                name.to_string()
            } else {
                format!("{}/{}", prefix, name)
            };

            paths.push(path.clone());

            if entry.kind() == Some(git2::ObjectType::Tree)
                && let Ok(obj) = entry.to_object(repo)
                && let Ok(subtree) = obj.peel_to_tree()
            {
                collect_all_tree_paths(repo, &subtree, &path, paths);
            }
        }
    }
}

/// Compute statistics from changes for a feature
fn compute_stats_from_changes(
    changes: &[Change],
    feature_path: &Path,
    nested_features: &[Feature],
) -> Option<Stats> {
    if changes.is_empty() {
        return None;
    }

    // Collect paths of nested features to exclude from commit counts
    let nested_feature_paths: Vec<String> =
        nested_features.iter().map(|f| f.path.clone()).collect();

    // Get repository to check commit details
    let repo = Repository::discover(feature_path).ok();

    // Get the feature's relative path from repo root
    let feature_relative_path = if let Some(ref r) = repo {
        if let Ok(canonical_path) = std::fs::canonicalize(feature_path) {
            if let Some(workdir) = r.workdir() {
                canonical_path
                    .strip_prefix(workdir)
                    .ok()
                    .map(|p| p.to_string_lossy().to_string())
            } else {
                None
            }
        } else {
            None
        }
    } else {
        None
    };

    // Filter changes to only include those that affect files in this feature
    // (not exclusively in nested features)
    let filtered_changes: Vec<&Change> = changes
        .iter()
        .filter(|change| {
            // If we don't have repo access, include all changes
            let Some(ref r) = repo else {
                return true;
            };

            let Some(ref feature_rel_path) = feature_relative_path else {
                return true;
            };

            // Get the files affected by this commit
            let affected_files = get_commit_affected_paths(r, &change.hash);

            // Check if any affected file is in this feature but not in a nested feature
            affected_files.iter().any(|file_path| {
                // File must be in this feature
                let in_feature = file_path.starts_with(feature_rel_path);

                // File must not be exclusively in a nested feature
                let in_nested = nested_feature_paths.iter().any(|nested_path| {
                    // Convert nested absolute path to relative path
                    if let Ok(nested_canonical) = std::fs::canonicalize(nested_path)
                        && let Some(workdir) = r.workdir()
                        && let Ok(nested_rel) = nested_canonical.strip_prefix(workdir)
                    {
                        let nested_rel_str = nested_rel.to_string_lossy();
                        return file_path.starts_with(nested_rel_str.as_ref());
                    }
                    false
                });

                in_feature && !in_nested
            })
        })
        .collect();

    let mut commits = std::collections::BTreeMap::new();

    // Add total commit count
    commits.insert(
        "total_commits".to_string(),
        serde_json::json!(filtered_changes.len()),
    );

    // Count commits by author
    let mut authors_count: HashMap<String, usize> = HashMap::new();
    for change in &filtered_changes {
        *authors_count.entry(change.author_name.clone()).or_insert(0) += 1;
    }
    commits.insert(
        "authors_count".to_string(),
        serde_json::json!(authors_count),
    );

    // Count commits by conventional commit type
    let mut count_by_type: HashMap<String, usize> = HashMap::new();
    for change in &filtered_changes {
        let commit_type = extract_commit_type(&change.title);
        *count_by_type.entry(commit_type).or_insert(0) += 1;
    }
    commits.insert(
        "count_by_type".to_string(),
        serde_json::json!(count_by_type),
    );

    // Get first and last commit dates
    if let Some(first) = filtered_changes.first() {
        commits.insert(
            "first_commit_date".to_string(),
            serde_json::json!(first.date.clone()),
        );
    }
    if let Some(last) = filtered_changes.last() {
        commits.insert(
            "last_commit_date".to_string(),
            serde_json::json!(last.date.clone()),
        );
    }

    // Count files and lines in the feature directory (excluding nested features)
    let files_count = count_files(feature_path, &nested_feature_paths);
    let lines_count = count_lines(feature_path, &nested_feature_paths);
    let todos_count = count_todos(feature_path, &nested_feature_paths);

    Some(Stats {
        files_count: Some(files_count),
        lines_count: Some(lines_count),
        todos_count: Some(todos_count),
        commits,
        coverage: None,
    })
}

/// Extract the commit type from a conventional commit title
fn extract_commit_type(title: &str) -> String {
    // Common conventional commit types
    let known_types = [
        "feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore",
        "revert",
    ];

    // Check if the title follows conventional commit format (type: description or type(scope): description)
    if let Some(colon_pos) = title.find(':') {
        let prefix = &title[..colon_pos];

        // Remove scope if present (e.g., "feat(auth)" -> "feat")
        let type_part = if let Some(paren_pos) = prefix.find('(') {
            &prefix[..paren_pos]
        } else {
            prefix
        };

        let type_part = type_part.trim().to_lowercase();

        // Check if it's a known conventional commit type
        if known_types.contains(&type_part.as_str()) {
            return type_part;
        }
    }

    // If not a conventional commit, return "other"
    "other".to_string()
}

fn process_feature_directory(
    path: &Path,
    base_path: &Path,
    name: &str,
    changes_map: Option<&HashMap<String, Vec<Change>>>,
    parent_owner: Option<&str>,
    feature_metadata_map: &FeatureMetadataMap,
    ignore_paths: &[PathBuf],
) -> Result<Feature> {
    // First try to find and read FEATURES.toml file
    let (title, owner, description, mut meta) = if let Some(toml_path) = find_features_toml(path) {
        if let Ok(toml_data) = read_features_toml(&toml_path) {
            (
                toml_data.name,
                toml_data.owner.unwrap_or_default(),
                toml_data.description.unwrap_or_default(),
                toml_data.meta,
            )
        } else {
            (
                None,
                String::new(),
                String::new(),
                std::collections::BTreeMap::new(),
            )
        }
    } else {
        // Fall back to README file if FEATURES.toml not found
        let readme_info = if let Some(readme_path) = find_readme_file(path) {
            read_readme_info(&readme_path)?
        } else {
            use crate::readme_parser::ReadmeInfo;
            ReadmeInfo {
                title: None,
                owner: "".to_string(),
                description: "".to_string(),
                meta: std::collections::BTreeMap::new(),
            }
        };
        (
            readme_info.title,
            readme_info.owner,
            readme_info.description,
            readme_info.meta,
        )
    };

    // Remove the 'feature' key from meta if it exists (it's redundant since we know it's a feature)
    meta.remove("feature");

    // Get the relative path to this feature directory for metadata lookup
    let relative_path = path
        .strip_prefix(base_path)
        .unwrap_or(path)
        .to_string_lossy()
        .to_string();

    // Check if this feature has any metadata from the global scan (matched by feature path)
    if let Some(metadata_map) = feature_metadata_map.get(&relative_path) {
        // Iterate through each metadata key (e.g., "feature-flag", "feature-experiment")
        for (metadata_key, flags) in metadata_map {
            // Convert Vec<HashMap<String, String>> to JSON array
            let flags_json: Vec<serde_json::Value> = flags
                .iter()
                .map(|flag_map| {
                    let json_map: serde_json::Map<String, serde_json::Value> = flag_map
                        .iter()
                        .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                        .collect();
                    serde_json::Value::Object(json_map)
                })
                .collect();

            // Check if this metadata key already exists, append if it does
            meta.entry(metadata_key.clone())
                .and_modify(|existing| {
                    if let serde_json::Value::Array(arr) = existing {
                        arr.extend(flags_json.clone());
                    }
                })
                .or_insert_with(|| serde_json::Value::Array(flags_json));
        }
    }

    let changes = if let Some(map) = changes_map {
        // Convert the absolute path to a repo-relative path and look up changes
        get_changes_for_path(path, map).unwrap_or_default()
    } else {
        Vec::new()
    };

    // Always include decisions regardless of include_changes flag
    let decisions = read_decision_files(path).unwrap_or_default();

    // Determine the actual owner and whether it's inherited
    let (actual_owner, is_owner_inherited) = if owner.is_empty() {
        if let Some(parent) = parent_owner {
            (parent.to_string(), true)
        } else {
            ("".to_string(), false)
        }
    } else {
        (owner.clone(), false)
    };

    // Check if this feature has nested features in a 'features' subdirectory
    let nested_features_path = path.join("features");
    let mut nested_features = if nested_features_path.exists()
        && nested_features_path.is_dir()
        && !is_ignored_path(&nested_features_path, ignore_paths)
    {
        list_files_recursive_impl(
            &nested_features_path,
            base_path,
            changes_map,
            Some(&actual_owner),
            feature_metadata_map,
            ignore_paths,
        )
        .unwrap_or_default()
    } else {
        Vec::new()
    };

    // Also check for nested features marked with feature: true in subdirectories
    let entries = fs::read_dir(path)
        .with_context(|| format!("could not read directory `{}`", path.display()))?;

    let mut entries: Vec<_> = entries.collect::<Result<_, _>>()?;
    entries.sort_by_key(|entry| entry.path());

    for entry in entries {
        let entry_path = entry.path();
        let entry_name = entry_path.file_name().unwrap().to_string_lossy();

        if entry_path.is_dir()
            && entry_name != "features" // Don't process 'features' folder twice
            && !is_documentation_directory(&entry_path)
            && !is_ignored_path(&entry_path, ignore_paths)
        {
            if has_feature_flag_in_readme(&entry_path) {
                // This directory is a feature itself
                let nested_feature = process_feature_directory(
                    &entry_path,
                    base_path,
                    &entry_name,
                    changes_map,
                    Some(&actual_owner),
                    feature_metadata_map,
                    ignore_paths,
                )?;
                nested_features.push(nested_feature);
            } else {
                // This directory is not a feature, but might contain features
                // Recursively search for features inside it
                let deeper_features = list_files_recursive_impl(
                    &entry_path,
                    base_path,
                    changes_map,
                    Some(&actual_owner),
                    feature_metadata_map,
                    ignore_paths,
                )?;
                nested_features.extend(deeper_features);
            }
        }
    }

    // Collect paths of nested features to exclude from file/line counts
    let nested_feature_paths: Vec<String> =
        nested_features.iter().map(|f| f.path.clone()).collect();

    // Always compute file, line, and TODO counts
    let files_count = count_files(path, &nested_feature_paths);
    let lines_count = count_lines(path, &nested_feature_paths);
    let todos_count = count_todos(path, &nested_feature_paths);

    // Compute stats from changes if available, otherwise create basic stats
    let stats =
        if let Some(change_stats) = compute_stats_from_changes(&changes, path, &nested_features) {
            // If we have change stats, they already include files/lines/todos counts
            Some(change_stats)
        } else {
            // No changes, but we still want to include file/line/todo counts
            Some(Stats {
                files_count: Some(files_count),
                lines_count: Some(lines_count),
                todos_count: Some(todos_count),
                commits: std::collections::BTreeMap::new(),
                coverage: None,
            })
        };

    // Make path relative to base_path
    let relative_path = path
        .strip_prefix(base_path)
        .unwrap_or(path)
        .to_string_lossy()
        .to_string();

    Ok(Feature {
        name: title.unwrap_or_else(|| name.to_string()),
        description,
        owner: actual_owner,
        is_owner_inherited,
        path: relative_path,
        features: nested_features,
        meta,
        changes,
        decisions,
        stats,
        dependencies: Vec::new(), // Will be populated in second pass
    })
}

fn list_files_recursive_impl(
    dir: &Path,
    base_path: &Path,
    changes_map: Option<&HashMap<String, Vec<Change>>>,
    parent_owner: Option<&str>,
    feature_metadata_map: &FeatureMetadataMap,
    ignore_paths: &[PathBuf],
) -> Result<Vec<Feature>> {
    let entries = fs::read_dir(dir)
        .with_context(|| format!("could not read directory `{}`", dir.display()))?;

    let mut entries: Vec<_> = entries.collect::<Result<_, _>>()?;
    entries.sort_by_key(|entry| entry.path());

    let mut features: Vec<Feature> = Vec::new();

    for entry in entries {
        let path = entry.path();
        let name = path.file_name().unwrap().to_string_lossy();

        if path.is_dir() {
            if is_ignored_path(&path, ignore_paths) {
                continue;
            }

            if is_feature_directory(&path) {
                let feature = process_feature_directory(
                    &path,
                    base_path,
                    &name,
                    changes_map,
                    parent_owner,
                    feature_metadata_map,
                    ignore_paths,
                )?;
                features.push(feature);
            } else if !is_documentation_directory(&path)
                && !is_inside_documentation_directory(&path)
            {
                // Recursively search for features in non-documentation subdirectories
                let new_features = list_files_recursive_impl(
                    &path,
                    base_path,
                    changes_map,
                    parent_owner,
                    feature_metadata_map,
                    ignore_paths,
                )?;
                features.extend(new_features);
            }
        }
    }

    Ok(features)
}

/// Get changes for a specific path from the pre-computed changes map
fn get_changes_for_path(
    path: &Path,
    changes_map: &HashMap<String, Vec<Change>>,
) -> Result<Vec<Change>> {
    // Canonicalize the path
    let canonical_path = std::fs::canonicalize(path)?;

    // Find the repository and get the working directory
    let repo = Repository::discover(path)?;
    let repo_workdir = repo
        .workdir()
        .context("repository has no working directory")?;

    // Convert to relative path from repo root
    let relative_path = canonical_path
        .strip_prefix(repo_workdir)
        .context("path is not within repository")?;

    let relative_path_str = relative_path.to_string_lossy().to_string();

    // Look up the changes in the map
    Ok(changes_map
        .get(&relative_path_str)
        .cloned()
        .unwrap_or_default())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_commit_type() {
        // Test standard conventional commit types
        assert_eq!(extract_commit_type("feat: add new feature"), "feat");
        assert_eq!(extract_commit_type("fix: resolve bug"), "fix");
        assert_eq!(extract_commit_type("docs: update README"), "docs");
        assert_eq!(extract_commit_type("style: format code"), "style");
        assert_eq!(
            extract_commit_type("refactor: improve structure"),
            "refactor"
        );
        assert_eq!(extract_commit_type("perf: optimize performance"), "perf");
        assert_eq!(extract_commit_type("test: add unit tests"), "test");
        assert_eq!(extract_commit_type("build: update dependencies"), "build");
        assert_eq!(extract_commit_type("ci: fix CI pipeline"), "ci");
        assert_eq!(extract_commit_type("chore: update gitignore"), "chore");
        assert_eq!(
            extract_commit_type("revert: undo previous commit"),
            "revert"
        );

        // Test with scope
        assert_eq!(extract_commit_type("feat(auth): add login"), "feat");
        assert_eq!(
            extract_commit_type("fix(api): resolve endpoint issue"),
            "fix"
        );
        assert_eq!(
            extract_commit_type("docs(readme): update instructions"),
            "docs"
        );

        // Test case insensitivity
        assert_eq!(extract_commit_type("FEAT: uppercase type"), "feat");
        assert_eq!(extract_commit_type("Fix: mixed case"), "fix");
        assert_eq!(extract_commit_type("DOCS: all caps"), "docs");

        // Test non-conventional commits
        assert_eq!(extract_commit_type("random commit message"), "other");
        assert_eq!(extract_commit_type("update: not conventional"), "other");
        assert_eq!(
            extract_commit_type("feature: close but not standard"),
            "other"
        );
        assert_eq!(extract_commit_type("no colon here"), "other");
        assert_eq!(extract_commit_type(""), "other");

        // Test edge cases
        assert_eq!(extract_commit_type("feat:no space after colon"), "feat");
        assert_eq!(extract_commit_type("feat  : extra spaces"), "feat");
        assert_eq!(
            extract_commit_type("feat(scope)(weird): nested parens"),
            "feat"
        );
    }

    fn write_readme(dir: &Path, content: &str) {
        fs::write(dir.join("README.md"), content).unwrap();
    }

    #[test]
    fn test_feature_flag_in_readme_true() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        write_readme(temp_dir.path(), "---\nfeature: true\n---\n\n# Feature\n");

        assert_eq!(feature_flag_in_readme(temp_dir.path()), Some(true));
        assert!(has_feature_flag_in_readme(temp_dir.path()));
        assert!(!has_feature_false_in_readme(temp_dir.path()));
    }

    #[test]
    fn test_feature_flag_in_readme_false() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        write_readme(temp_dir.path(), "---\nfeature: false\n---\n\n# Feature\n");

        assert_eq!(feature_flag_in_readme(temp_dir.path()), Some(false));
        assert!(!has_feature_flag_in_readme(temp_dir.path()));
        assert!(has_feature_false_in_readme(temp_dir.path()));
    }

    #[test]
    fn test_feature_flag_in_readme_missing() {
        let temp_dir = tempfile::TempDir::new().unwrap();

        // No README at all
        assert_eq!(feature_flag_in_readme(temp_dir.path()), None);
        assert!(!has_feature_flag_in_readme(temp_dir.path()));
        assert!(!has_feature_false_in_readme(temp_dir.path()));

        // README without a `feature` property
        write_readme(temp_dir.path(), "---\nowner: team\n---\n\n# Feature\n");
        assert_eq!(feature_flag_in_readme(temp_dir.path()), None);
        assert!(!has_feature_flag_in_readme(temp_dir.path()));
        assert!(!has_feature_false_in_readme(temp_dir.path()));
    }

    #[test]
    fn test_is_feature_directory_direct_subfolder_of_features() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let features_dir = temp_dir.path().join("features");
        let feature_dir = features_dir.join("my-feature");
        fs::create_dir_all(&feature_dir).unwrap();

        // No README needed: a direct subfolder of `features` is a feature by default
        assert!(is_feature_directory(&feature_dir));
    }

    #[test]
    fn test_is_feature_directory_skips_when_feature_false_even_under_features_folder() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let features_dir = temp_dir.path().join("features");
        let feature_dir = features_dir.join("my-feature");
        fs::create_dir_all(&feature_dir).unwrap();
        write_readme(&feature_dir, "---\nfeature: false\n---\n\n# My Feature\n");

        // Explicit `feature: false` overrides the "direct subfolder of `features`" rule
        assert!(!is_feature_directory(&feature_dir));
    }

    #[test]
    fn test_is_feature_directory_readme_feature_true_outside_features_folder() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let feature_dir = temp_dir.path().join("some-dir");
        fs::create_dir_all(&feature_dir).unwrap();
        write_readme(&feature_dir, "---\nfeature: true\n---\n\n# Some Dir\n");

        assert!(is_feature_directory(&feature_dir));
    }

    #[test]
    fn test_is_feature_directory_readme_feature_false_outside_features_folder() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let feature_dir = temp_dir.path().join("some-dir");
        fs::create_dir_all(&feature_dir).unwrap();
        write_readme(&feature_dir, "---\nfeature: false\n---\n\n# Some Dir\n");

        assert!(!is_feature_directory(&feature_dir));
    }

    /// Skipping a feature via `feature: false` must keep its sub-children discoverable:
    /// both a nested `features/` folder and a subfolder with its own `feature: true` README.
    #[test]
    fn test_list_files_recursive_skips_feature_but_keeps_sub_children() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let base = temp_dir.path();

        let features_dir = base.join("features");
        let skipped_dir = features_dir.join("skipped-feature");
        fs::create_dir_all(&skipped_dir).unwrap();
        write_readme(
            &skipped_dir,
            "---\nfeature: false\nowner: skipped-owner\n---\n\n# Skipped Feature\n",
        );

        // A nested `features` folder inside the skipped directory.
        let nested_via_features_folder = skipped_dir.join("features").join("child-a");
        fs::create_dir_all(&nested_via_features_folder).unwrap();

        // A subfolder marked as a feature via its own README.
        let nested_via_readme = skipped_dir.join("child-b");
        fs::create_dir_all(&nested_via_readme).unwrap();
        write_readme(
            &nested_via_readme,
            "---\nfeature: true\nowner: child-b-owner\n---\n\n# Child B\n",
        );

        let features = list_files_recursive(base, &[]).unwrap();

        // The skipped feature itself must not appear anywhere in the tree.
        fn collect_names(features: &[Feature], out: &mut Vec<String>) {
            for feature in features {
                out.push(feature.name.clone());
                collect_names(&feature.features, out);
            }
        }
        let mut names = Vec::new();
        collect_names(&features, &mut names);
        assert!(!names.contains(&"skipped-feature".to_string()));
        assert!(!names.contains(&"Skipped Feature".to_string()));

        // Both sub-children are still discovered, as top-level features (since their
        // skipped parent no longer exists as a node in the tree).
        assert!(names.contains(&"child-a".to_string()));
        let child_b = features
            .iter()
            .find(|f| f.name == "Child B")
            .expect("child-b feature should be present");
        assert_eq!(child_b.owner, "child-b-owner");
    }
}