gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
//! CLI mode (non-interactive mode) module
//!
//! Provides a non-interactive mode for retrieving statistics directly
//! from AI development environments such as Claude Code
//!
//! ## Security Considerations
//!
//! - Input validation: validates command-line argument values
//! - Resource limits: caps the number of records loaded (DoS prevention)
//! - Error messages: uses generic messages that do not expose internal details

use std::env;

use anyhow::Result;
use git2::Repository;

use crate::config::LanguageConfig;
use crate::event::GitEvent;
use crate::export::{
    bus_factor_to_json, coupling_to_json, health_to_json, health_to_markdown, heatmap_to_json,
    impact_to_json, log_to_json, ownership_to_json, quality_to_json, stats_to_json,
    tech_debt_to_json, timeline_to_json,
};
use crate::git::{get_commit_files, load_events};
use crate::insights::{
    actions_to_markdown, build_context_pack, build_context_summary, build_handoff_context,
    build_next_actions, build_review_pack, explain_recommendation, handoff_to_markdown,
    pack_to_markdown, review_pack_to_markdown, summary_to_markdown, verify_patch_risk,
};
use crate::stats::{
    calculate_activity_timeline, calculate_bus_factor, calculate_change_coupling,
    calculate_file_heatmap, calculate_impact_scores, calculate_ownership, calculate_project_health,
    calculate_quality_scores, calculate_stats, calculate_tech_debt,
};
use crate::{
    clear_analysis_cache, load_metrics, load_or_compute_with_repo, record_quick_action_usage,
    reset_metrics,
};
use crate::{load_cached_review_pack, save_cached_review_pack};

/// Maximum number of log entries to output (security: prevents resource exhaustion)
const MAX_LOG_LIMIT: usize = 10000;

/// Default number of log entries to output
const DEFAULT_LOG_LIMIT: usize = 10;

/// Maximum number of events to load for statistics calculation
const MAX_EVENTS_FOR_STATS: usize = 2000;
/// Analysis cache TTL (in hours)
const ANALYSIS_CACHE_TTL_HOURS: u64 = 24;

// Compile-time security checks
const _: () = {
    assert!(MAX_LOG_LIMIT <= 10000, "MAX_LOG_LIMIT must be reasonable");
    assert!(MAX_LOG_LIMIT > 0, "MAX_LOG_LIMIT must be positive");
    assert!(
        DEFAULT_LOG_LIMIT <= MAX_LOG_LIMIT,
        "DEFAULT must not exceed MAX"
    );
    assert!(
        MAX_EVENTS_FOR_STATS <= 10000,
        "MAX_EVENTS_FOR_STATS must be reasonable"
    );
    assert!(
        MAX_EVENTS_FOR_STATS > 0,
        "MAX_EVENTS_FOR_STATS must be positive"
    );
};

/// Output format
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
    #[default]
    Json,
    Markdown,
}

impl OutputFormat {
    fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "json" => Some(OutputFormat::Json),
            "md" | "markdown" => Some(OutputFormat::Markdown),
            _ => None,
        }
    }
}

/// CLI command
#[derive(Debug, Clone, PartialEq)]
pub enum CliCommand {
    /// Benchmark mode
    Benchmark,
    /// Output author statistics
    Stats { format: OutputFormat },
    /// Output file heatmap
    Heatmap { format: OutputFormat },
    /// Output Impact Score
    Impact { format: OutputFormat },
    /// Output Change Coupling
    Coupling { format: OutputFormat },
    /// Output code ownership
    Ownership { format: OutputFormat },
    /// Output commit quality score
    Quality { format: OutputFormat },
    /// Output activity timeline
    Timeline { format: OutputFormat },
    /// Output bus factor analysis
    BusFactor { format: OutputFormat },
    /// Output technical debt score
    TechDebt { format: OutputFormat },
    /// Output project health dashboard
    Health { format: OutputFormat },
    /// Output current context summary
    Summary { format: OutputFormat },
    /// Output AI insight pack
    Pack { format: OutputFormat },
    /// Output AI review pack
    ReviewPack { format: OutputFormat },
    /// Output recommended next actions
    NextActions { format: OutputFormat },
    /// Output recommendation rationale
    Why { id: String, format: OutputFormat },
    /// Output risk verification results
    Verify { format: OutputFormat },
    /// Execute a quick action
    QuickAction {
        id: String,
        compact: bool,
        format: OutputFormat,
    },
    /// Output handoff context for the target AI
    Handoff {
        target: String,
        format: OutputFormat,
    },
    /// Output the latest N log entries
    Log { limit: usize, format: OutputFormat },
    /// Clear analysis cache
    ClearCache,
    /// Display local metrics
    Metrics { scope: String, format: OutputFormat },
    /// Clear local metrics
    MetricsReset,
    /// Display help
    Help,
    /// Display version
    Version,
}

/// TUI startup focus target
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TuiFocusTarget {
    Risk,
    Review,
    History,
    Files,
}

impl TuiFocusTarget {
    fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "risk" => Some(Self::Risk),
            "review" => Some(Self::Review),
            "history" => Some(Self::History),
            "files" => Some(Self::Files),
            _ => None,
        }
    }
}

/// TUI startup options
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TuiOptions {
    pub focus: Option<TuiFocusTarget>,
}

/// Parse command-line arguments and return a CliCommand
///
/// Returns None if no CLI command is specified (launches TUI mode)
///
/// ## Security
///
/// - The N in `--log -n N` is capped to not exceed `MAX_LOG_LIMIT`
/// - Invalid input values fall back to defaults
pub fn parse_cli_args() -> Option<CliCommand> {
    let args: Vec<String> = env::args().collect();

    // TUI mode when there is at most one argument (program name only)
    if args.len() <= 1 {
        return None;
    }

    // Look for the --format option
    let format = find_format_option(&args);

    // Check each argument
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--benchmark" => return Some(CliCommand::Benchmark),
            "--stats" => return Some(CliCommand::Stats { format }),
            "--heatmap" => return Some(CliCommand::Heatmap { format }),
            "--impact" => return Some(CliCommand::Impact { format }),
            "--coupling" => return Some(CliCommand::Coupling { format }),
            "--ownership" => return Some(CliCommand::Ownership { format }),
            "--quality" => return Some(CliCommand::Quality { format }),
            "--timeline" => return Some(CliCommand::Timeline { format }),
            "--bus-factor" => return Some(CliCommand::BusFactor { format }),
            "--tech-debt" => return Some(CliCommand::TechDebt { format }),
            "--health" => return Some(CliCommand::Health { format }),
            "--summary" => return Some(CliCommand::Summary { format }),
            "--pack" => return Some(CliCommand::Pack { format }),
            "--review-pack" => return Some(CliCommand::ReviewPack { format }),
            "--next-actions" => return Some(CliCommand::NextActions { format }),
            "--verify" => return Some(CliCommand::Verify { format }),
            "--quick-action" => {
                return Some(parse_quick_action_option(&args, i, format));
            }
            "--why" => {
                let id = args
                    .get(i + 1)
                    .filter(|s| !s.starts_with('-'))
                    .cloned()
                    .unwrap_or_else(|| "act-ship".to_string());
                return Some(CliCommand::Why { id, format });
            }
            "--handoff" => {
                let target = if i + 2 < args.len() && args[i + 1] == "--target" {
                    args[i + 2].clone()
                } else {
                    "claude".to_string()
                };
                return Some(CliCommand::Handoff { target, format });
            }
            "--clear-cache" => return Some(CliCommand::ClearCache),
            "--metrics" => {
                let scope = args
                    .get(i + 1)
                    .filter(|s| !s.starts_with('-'))
                    .cloned()
                    .unwrap_or_else(|| "quick-actions".to_string());
                return Some(CliCommand::Metrics { scope, format });
            }
            "--metrics-reset" => return Some(CliCommand::MetricsReset),
            "--log" => {
                return Some(parse_log_option(&args, i, format));
            }
            "--help" | "-h" => return Some(CliCommand::Help),
            "--version" | "-V" => return Some(CliCommand::Version),
            _ => {}
        }
        i += 1;
    }

    None
}

/// Parse TUI-specific options
///
/// Invalid values are ignored and defaults are preserved.
pub fn parse_tui_options(args: &[String]) -> TuiOptions {
    let mut options = TuiOptions::default();
    let mut i = 1;

    while i < args.len() {
        match args[i].as_str() {
            "--layout" | "--pane-width" => {
                // Backward compatibility: skip the argument
                if args.get(i + 1).is_some() {
                    i += 1;
                }
            }
            "--focus" => {
                if let Some(value) = args.get(i + 1) {
                    options.focus = TuiFocusTarget::from_str(value);
                    i += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }

    options
}

/// Look for the --format option
fn find_format_option(args: &[String]) -> OutputFormat {
    for i in 0..args.len() {
        if args[i] == "--format" && i + 1 < args.len() {
            if let Some(fmt) = OutputFormat::from_str(&args[i + 1]) {
                return fmt;
            }
        }
    }
    OutputFormat::default()
}

fn find_quick_action_format(args: &[String]) -> Option<&str> {
    for i in 0..args.len() {
        if args[i] == "--quick-action-format" && i + 1 < args.len() {
            let value = args[i + 1].as_str();
            if value == "compact" || value == "full" {
                return Some(value);
            }
        }
    }
    None
}

/// Parse the --log option
///
/// Validates the value of `-n N` and falls back to the default or maximum if out of range.
fn parse_log_option(args: &[String], index: usize, format: OutputFormat) -> CliCommand {
    // Look for the -n option
    let limit = if index + 2 < args.len() && args[index + 1] == "-n" {
        // Security: input value validation
        match args[index + 2].parse::<usize>() {
            Ok(n) if n > 0 && n <= MAX_LOG_LIMIT => n,
            Ok(n) if n > MAX_LOG_LIMIT => {
                eprintln!(
                    "Warning: limit {} exceeds maximum ({}), using maximum",
                    n, MAX_LOG_LIMIT
                );
                MAX_LOG_LIMIT
            }
            _ => {
                eprintln!(
                    "Warning: invalid limit value, using default ({})",
                    DEFAULT_LOG_LIMIT
                );
                DEFAULT_LOG_LIMIT
            }
        }
    } else {
        DEFAULT_LOG_LIMIT
    };
    CliCommand::Log { limit, format }
}

/// Parse the --quick-action option
///
/// Parses the action ID and display format (compact/full).
fn parse_quick_action_option(args: &[String], index: usize, format: OutputFormat) -> CliCommand {
    let id = args
        .get(index + 1)
        .filter(|s| !s.starts_with('-'))
        .cloned()
        .unwrap_or_else(|| "risk-summary".to_string());
    let compact = find_quick_action_format(args)
        .map(|s| s == "compact")
        .unwrap_or(true);
    CliCommand::QuickAction {
        id,
        compact,
        format,
    }
}

/// Run CLI mode
pub fn run_cli_mode(command: CliCommand) -> Result<()> {
    match command {
        CliCommand::Benchmark => {
            // Benchmark mode is handled in main.rs
            // Should not reach here, but just in case
            Ok(())
        }
        CliCommand::ClearCache => run_clear_cache(),
        CliCommand::Metrics { scope, format } => run_metrics(scope, format),
        CliCommand::MetricsReset => run_metrics_reset(),
        CliCommand::Help => run_help(),
        CliCommand::Version => run_version(),
        _ => {
            // Commands requiring git operations discover the repository once and share it
            let repo = Repository::discover(".").map_err(|_| {
                anyhow::anyhow!("Error: Not a git repository (or any of the parent directories)")
            })?;
            run_cli_mode_with_repo(command, &repo)
        }
    }
}

/// Execute a CLI command with the given repository
fn run_cli_mode_with_repo(command: CliCommand, repo: &Repository) -> Result<()> {
    match command {
        CliCommand::Stats { format } => run_stats(repo, format),
        CliCommand::Heatmap { format } => run_heatmap(repo, format),
        CliCommand::Impact { format } => run_impact(repo, format),
        CliCommand::Coupling { format } => run_coupling(repo, format),
        CliCommand::Ownership { format } => run_ownership(repo, format),
        CliCommand::Quality { format } => run_quality(repo, format),
        CliCommand::Timeline { format } => run_timeline(repo, format),
        CliCommand::BusFactor { format } => run_bus_factor(repo, format),
        CliCommand::TechDebt { format } => run_tech_debt(repo, format),
        CliCommand::Health { format } => run_health(repo, format),
        CliCommand::Summary { format } => run_summary(repo, format),
        CliCommand::Pack { format } => run_pack(repo, format),
        CliCommand::ReviewPack { format } => run_review_pack(repo, format),
        CliCommand::NextActions { format } => run_next_actions(repo, format),
        CliCommand::Why { id, format } => run_why(repo, id, format),
        CliCommand::Verify { format } => run_verify(repo, format),
        CliCommand::QuickAction {
            id,
            compact,
            format,
        } => run_quick_action(repo, id, compact, format),
        CliCommand::Handoff { target, format } => run_handoff(repo, target, format),
        CliCommand::Log { limit, format } => run_log(repo, limit, format),
        // These commands are already handled in run_cli_mode
        CliCommand::Benchmark
        | CliCommand::ClearCache
        | CliCommand::Metrics { .. }
        | CliCommand::MetricsReset
        | CliCommand::Help
        | CliCommand::Version => unreachable!(),
    }
}

/// Output author statistics
fn run_stats(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("stats_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let stats = calculate_stats(&event_refs);
            match format {
                OutputFormat::Json => stats_to_json(&stats),
                OutputFormat::Markdown => Ok(stats_to_markdown(&stats)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output file heatmap
fn run_heatmap(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("heatmap_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let heatmap = calculate_file_heatmap(&event_refs, |hash| get_commit_files(hash).ok());
            match format {
                OutputFormat::Json => heatmap_to_json(&heatmap),
                OutputFormat::Markdown => Ok(heatmap_to_markdown(&heatmap)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output Impact Score
fn run_impact(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("impact_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let heatmap = calculate_file_heatmap(&event_refs, |hash| get_commit_files(hash).ok());
            let analysis =
                calculate_impact_scores(&event_refs, |hash| get_commit_files(hash).ok(), &heatmap);
            match format {
                OutputFormat::Json => impact_to_json(&analysis),
                OutputFormat::Markdown => Ok(impact_to_markdown(&analysis)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output Change Coupling
fn run_coupling(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("coupling_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let analysis = calculate_change_coupling(
                &event_refs,
                |hash| get_commit_files(hash).ok(),
                5,   // min_commits
                0.3, // min_coupling
            );
            match format {
                OutputFormat::Json => coupling_to_json(&analysis),
                OutputFormat::Markdown => Ok(coupling_to_markdown(&analysis)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output code ownership
fn run_ownership(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("ownership_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let ownership = calculate_ownership(&event_refs, |hash| get_commit_files(hash).ok());
            match format {
                OutputFormat::Json => ownership_to_json(&ownership),
                OutputFormat::Markdown => Ok(ownership_to_markdown(&ownership)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output commit quality score
fn run_quality(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("quality_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let coupling =
                calculate_change_coupling(&event_refs, |hash| get_commit_files(hash).ok(), 5, 0.3);
            let analysis = calculate_quality_scores(
                &event_refs,
                |hash| get_commit_files(hash).ok(),
                &coupling,
            );
            match format {
                OutputFormat::Json => quality_to_json(&analysis),
                OutputFormat::Markdown => Ok(quality_to_markdown(&analysis)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output activity timeline
fn run_timeline(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("timeline_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let timeline = calculate_activity_timeline(&event_refs);
            match format {
                OutputFormat::Json => timeline_to_json(&timeline),
                OutputFormat::Markdown => Ok(timeline_to_markdown(&timeline)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output bus factor analysis
fn run_bus_factor(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("bus_factor_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let analysis = calculate_bus_factor(&event_refs, |hash| get_commit_files(hash).ok(), 5);
            match format {
                OutputFormat::Json => bus_factor_to_json(&analysis),
                OutputFormat::Markdown => Ok(bus_factor_to_markdown(&analysis)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output technical debt score
fn run_tech_debt(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("tech_debt_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let analysis = calculate_tech_debt(&event_refs, |hash| get_commit_files(hash).ok(), 3);
            match format {
                OutputFormat::Json => tech_debt_to_json(&analysis),
                OutputFormat::Markdown => Ok(tech_debt_to_markdown(&analysis)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output project health dashboard
fn run_health(repo: &Repository, format: OutputFormat) -> Result<()> {
    let cache_key = format!("health_{:?}", format);
    let output =
        load_or_compute_with_repo(Some(repo), &cache_key, ANALYSIS_CACHE_TTL_HOURS, || {
            let events = load_events_or_error()?;
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let heatmap = calculate_file_heatmap(&event_refs, |hash| get_commit_files(hash).ok());
            let coupling =
                calculate_change_coupling(&event_refs, |hash| get_commit_files(hash).ok(), 5, 0.3);
            let quality = calculate_quality_scores(
                &event_refs,
                |hash| get_commit_files(hash).ok(),
                &coupling,
            );
            let bus_factor =
                calculate_bus_factor(&event_refs, |hash| get_commit_files(hash).ok(), 5);
            let tech_debt = calculate_tech_debt(&event_refs, |hash| get_commit_files(hash).ok(), 3);
            let health = calculate_project_health(
                &event_refs,
                |hash| get_commit_files(hash).ok(),
                Some(&quality),
                Some(&bus_factor),
                Some(&tech_debt),
                &heatmap,
            );
            match format {
                OutputFormat::Json => health_to_json(&health),
                OutputFormat::Markdown => Ok(health_to_markdown(&health)),
            }
        })?;
    println!("{}", output);
    Ok(())
}

/// Output current context summary
fn run_summary(repo: &Repository, format: OutputFormat) -> Result<()> {
    let events = load_events_or_error()?;
    let event_refs: Vec<&GitEvent> = events.iter().collect();
    let hot_path = calculate_file_heatmap(&event_refs, |hash| get_commit_files(hash).ok())
        .files
        .first()
        .map(|f| f.path.clone());
    let selected = events.first().map(|e| e.short_hash.clone());
    let summary = build_context_summary(Some(repo), hot_path, selected);

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&summary)?,
        OutputFormat::Markdown => summary_to_markdown(&summary),
    };
    println!("{}", output);
    Ok(())
}

/// Output AI insight pack
fn run_pack(repo: &Repository, format: OutputFormat) -> Result<()> {
    let events = load_events_or_error()?;
    let event_refs: Vec<&GitEvent> = events.iter().collect();
    let selected = events.first().map(|e| e.short_hash.as_str());
    let pack = build_context_pack(Some(repo), &event_refs, selected)?;

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&pack)?,
        OutputFormat::Markdown => pack_to_markdown(&pack),
    };
    println!("{}", output);
    Ok(())
}

/// Output AI Review Pack
fn run_review_pack(repo: &Repository, format: OutputFormat) -> Result<()> {
    let review_pack = load_or_build_review_pack(repo)?;

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&review_pack)?,
        OutputFormat::Markdown => review_pack_to_markdown(&review_pack),
    };
    println!("{}", output);
    Ok(())
}

/// Output recommended next actions
fn run_next_actions(repo: &Repository, format: OutputFormat) -> Result<()> {
    let review_pack = load_or_build_review_pack(repo)?;
    let actions = build_next_actions(&review_pack);

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&actions)?,
        OutputFormat::Markdown => actions_to_markdown(&actions),
    };
    println!("{}", output);
    Ok(())
}

/// Output recommendation rationale
fn run_why(repo: &Repository, id: String, format: OutputFormat) -> Result<()> {
    let review_pack = load_or_build_review_pack(repo)?;
    let explanation = explain_recommendation(&review_pack, &id)
        .unwrap_or_else(|| format!("No recommendation found for id: {}", id));

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(
            &serde_json::json!({ "id": id, "explanation": explanation }),
        )?,
        OutputFormat::Markdown => format!("# Why\n\n- `{}`: {}\n", id, explanation),
    };
    println!("{}", output);
    Ok(())
}

/// Output risk verification results
fn run_verify(repo: &Repository, format: OutputFormat) -> Result<()> {
    let review_pack = load_or_build_review_pack(repo)?;
    let verification = verify_patch_risk(&review_pack);

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&verification)?,
        OutputFormat::Markdown => format!(
            "# Verify\n\n- **Verdict**: {}\n- **Risk Score**: {:.2}\n- **Confidence**: {:.2}\n",
            verification
                .get("verdict")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown"),
            verification
                .get("risk_score")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
            verification
                .get("confidence")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
        ),
    };
    println!("{}", output);
    Ok(())
}

/// Output handoff context for the target AI
fn run_handoff(repo: &Repository, target: String, format: OutputFormat) -> Result<()> {
    let review_pack = load_or_build_review_pack(repo)?;
    let handoff = build_handoff_context(&review_pack, &target);

    let output = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&handoff)?,
        OutputFormat::Markdown => handoff_to_markdown(&handoff),
    };
    println!("{}", output);
    Ok(())
}

fn run_quick_action(
    repo: &Repository,
    id: String,
    compact: bool,
    format: OutputFormat,
) -> Result<()> {
    let review_pack = load_or_build_review_pack(repo)?;
    let output_value = match id.as_str() {
        "risk-summary" => {
            let verdict = verify_patch_risk(&review_pack);
            serde_json::json!({
                "id": id,
                "risk_score": review_pack.risk_score,
                "confidence": review_pack.confidence,
                "verdict": verdict.get("verdict").and_then(|v| v.as_str()).unwrap_or("unknown"),
                "top_risks": review_pack.top_risks.iter().take(3).map(|r| r.title.clone()).collect::<Vec<_>>(),
            })
        }
        "review-pack" => {
            if compact {
                compact_review_pack_json(&review_pack)
            } else {
                serde_json::to_value(&review_pack)?
            }
        }
        "next-actions" => {
            let actions = build_next_actions(&review_pack);
            if compact {
                serde_json::json!({
                    "id": id,
                    "items": actions.iter().take(5).map(|a| serde_json::json!({"id": a.id, "priority": a.priority, "title": a.title})).collect::<Vec<_>>()
                })
            } else {
                serde_json::to_value(actions)?
            }
        }
        "verify" => verify_patch_risk(&review_pack),
        "handoff-claude" => serde_json::to_value(build_handoff_context(&review_pack, "claude"))?,
        "handoff-codex" => serde_json::to_value(build_handoff_context(&review_pack, "codex"))?,
        "handoff-copilot" => serde_json::to_value(build_handoff_context(&review_pack, "copilot"))?,
        _ => {
            anyhow::bail!(
                "Unknown quick action id: {} (supported: risk-summary, review-pack, next-actions, verify, handoff-claude, handoff-codex, handoff-copilot)",
                id
            )
        }
    };

    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&output_value)?);
        }
        OutputFormat::Markdown => {
            if id == "next-actions" {
                let actions = build_next_actions(&review_pack);
                println!("{}", actions_to_markdown(&actions));
            } else if id == "review-pack" {
                println!("{}", review_pack_to_markdown(&review_pack));
            } else if id.starts_with("handoff-") {
                let target = id.trim_start_matches("handoff-");
                let handoff = build_handoff_context(&review_pack, target);
                println!("{}", handoff_to_markdown(&handoff));
            } else {
                println!(
                    "```json\n{}\n```",
                    serde_json::to_string_pretty(&output_value)?
                );
            }
        }
    }
    let _ = record_quick_action_usage(&id);
    Ok(())
}

fn run_metrics(scope: String, format: OutputFormat) -> Result<()> {
    if scope != "quick-actions" {
        anyhow::bail!(
            "Unknown metrics scope: {} (supported: quick-actions)",
            scope
        );
    }
    let metrics = load_metrics();
    let mut rows: Vec<_> = metrics.quick_actions.into_iter().collect();
    rows.sort_by(|a, b| b.1.count.cmp(&a.1.count));

    match format {
        OutputFormat::Json => {
            let value = serde_json::json!({
                "scope": "quick-actions",
                "items": rows.into_iter().map(|(id, entry)| serde_json::json!({
                    "id": id,
                    "count": entry.count,
                    "last_used_at": entry.last_used_at
                })).collect::<Vec<_>>()
            });
            println!("{}", serde_json::to_string_pretty(&value)?);
        }
        OutputFormat::Markdown => {
            println!("# Quick Action Metrics\n");
            println!("| Action | Count | Last Used |");
            println!("|---|---:|---|");
            for (id, entry) in rows {
                println!("| `{}` | {} | {} |", id, entry.count, entry.last_used_at);
            }
        }
    }
    Ok(())
}

fn run_metrics_reset() -> Result<()> {
    reset_metrics()?;
    let lang = LanguageConfig::load().language;
    println!("{}", lang.cli_metrics_reset());
    Ok(())
}

fn compact_review_pack_json(review_pack: &crate::insights::ReviewPack) -> serde_json::Value {
    serde_json::json!({
        "repo": review_pack.repo,
        "branch": review_pack.branch,
        "head": review_pack.head,
        "risk_score": review_pack.risk_score,
        "confidence": review_pack.confidence,
        "summary": review_pack.summary,
        "top_risks": review_pack.top_risks.iter().take(3).map(|r| serde_json::json!({"title": r.title, "severity": r.severity})).collect::<Vec<_>>(),
        "recommended_actions": review_pack.recommended_actions.iter().take(5).map(|a| serde_json::json!({"id": a.id, "priority": a.priority, "title": a.title})).collect::<Vec<_>>()
    })
}

fn load_or_build_review_pack(repo: &Repository) -> Result<crate::insights::ReviewPack> {
    let events = load_events_or_error()?;
    let selected = events.first().map(|e| e.short_hash.as_str());
    if let Some(pack) = load_cached_review_pack(selected) {
        return Ok(pack);
    }
    let event_refs: Vec<&GitEvent> = events.iter().collect();
    let review_pack = build_review_pack(Some(repo), &event_refs, selected)?;
    let _ = save_cached_review_pack(selected, &review_pack);
    Ok(review_pack)
}

/// Output the latest N log entries
fn run_log(_repo: &Repository, limit: usize, format: OutputFormat) -> Result<()> {
    let events = load_events_limited(limit)?;

    let output = match format {
        OutputFormat::Json => log_to_json(&events)?,
        OutputFormat::Markdown => log_to_markdown(&events),
    };
    println!("{}", output);
    Ok(())
}

/// Clear analysis cache
fn run_clear_cache() -> Result<()> {
    clear_analysis_cache()?;
    let lang = LanguageConfig::load().language;
    println!("{}", lang.cli_analysis_cache_cleared());
    Ok(())
}

/// Display help
fn run_help() -> Result<()> {
    let lang = LanguageConfig::load().language;
    let help = format!(
        r#"{title}

{usage}
    gitstack [OPTIONS]

{analysis}
    --stats       Output author statistics
    --heatmap     Output file change heatmap
    --impact      Output Impact Score (commit influence)
    --coupling    Output Change Coupling (file co-change)
    --ownership   Output Code Ownership
    --quality     Output Commit Quality Score
    --timeline    Output Activity Timeline
    --bus-factor  Output Bus Factor analysis (knowledge risk)
    --tech-debt   Output Technical Debt Score
    --health      Output Project Health dashboard
    --summary     Output current narrow-pane context summary
    --pack        Output AI-ready insight pack
    --review-pack Output AI review decision pack
    --next-actions Output prioritized next actions
    --why ID      Explain a recommendation (e.g. act-add-tests)
    --verify      Verify current patch risk and confidence
    --quick-action ID Execute one AI quick action
    --handoff [--target claude|codex|copilot]  Build handoff context for AI
    --log -n N    Output latest N commits (default: {default_limit}, max: {max_limit})
    --metrics quick-actions  Show local quick-action usage metrics
    --metrics-reset          Clear local metrics cache
    --clear-cache Clear analysis cache files

{format}
    --format json     Output as JSON (default)
    --format md       Output as Markdown

{tui}
    --focus risk|review|history|files
                               Startup focus preset for interactive mode
    --quick-action-format compact|full
                               Output density for --quick-action (default: compact)

{general}
    --help, -h        Show this help message
    --version, -V     Show version information

{no_options}

{examples}
    gitstack --stats                      # JSON output
    gitstack --stats --format md          # Markdown output
    gitstack --bus-factor --format json   # Bus factor analysis
    gitstack --tech-debt --format md      # Tech debt as Markdown
    gitstack --summary --format md        # Context summary
    gitstack --pack --format json         # AI-ready insight pack
    gitstack --review-pack --format md    # Review decision pack
    gitstack --next-actions               # Prioritized actions
    gitstack --why act-add-tests          # Explain recommendation
    gitstack --verify                     # Risk verdict
    gitstack --quick-action risk-summary # Compact risk decision signal
    gitstack --metrics quick-actions     # Local quick-action usage
    gitstack --handoff --target codex     # AI handoff context
    gitstack --log -n 5 | jq .            # Latest 5 commits
    gitstack --focus risk                  # Risk-focused view
    gitstack --focus files                # File-status focused view

For more information, visit: https://github.com/Hiro-Chiba/gitstack"#,
        title = lang.cli_help_title(),
        usage = lang.cli_help_usage(),
        analysis = lang.cli_help_analysis_options(),
        format = lang.cli_help_format_options(),
        tui = lang.cli_help_tui_options(),
        general = lang.cli_help_general_options(),
        no_options = lang.cli_help_no_options(),
        examples = lang.cli_help_examples(),
        default_limit = DEFAULT_LOG_LIMIT,
        max_limit = MAX_LOG_LIMIT,
    );

    println!("{}", help);
    Ok(())
}

/// Display version information
fn run_version() -> Result<()> {
    println!("gitstack {}", env!("CARGO_PKG_VERSION"));
    Ok(())
}

/// Load events (outputs to stderr on error and returns an error)
fn load_events_or_error() -> Result<Vec<GitEvent>> {
    load_events(MAX_EVENTS_FOR_STATS)
        .map_err(|_| anyhow::anyhow!("Error: Failed to load git history"))
}

/// Load a specified number of events
fn load_events_limited(limit: usize) -> Result<Vec<GitEvent>> {
    let safe_limit = limit.min(MAX_LOG_LIMIT);

    load_events(safe_limit).map_err(|_| anyhow::anyhow!("Error: Failed to load git history"))
}

// ============================================================
// Markdown output functions
// ============================================================

use crate::stats::{
    ActivityTimeline, BusFactorAnalysis, ChangeCouplingAnalysis, CodeOwnership,
    CommitImpactAnalysis, CommitQualityAnalysis, FileHeatmap, RepoStats, TechDebtAnalysis,
};

fn stats_to_markdown(stats: &RepoStats) -> String {
    let mut md = String::new();
    md.push_str("# Author Statistics\n\n");
    md.push_str(&format!("- **Total Commits**: {}\n", stats.total_commits));
    md.push_str(&format!(
        "- **Total Insertions**: {}\n",
        stats.total_insertions
    ));
    md.push_str(&format!(
        "- **Total Deletions**: {}\n",
        stats.total_deletions
    ));
    md.push_str(&format!("- **Authors**: {}\n\n", stats.author_count()));

    md.push_str("## Top Contributors\n\n");
    md.push_str("| Author | Commits | Lines (+/-) | % |\n");
    md.push_str("|--------|--------:|------------:|--:|\n");
    for author in stats.authors.iter().take(20) {
        md.push_str(&format!(
            "| {} | {} | +{} / -{} | {:.1}% |\n",
            author.name,
            author.commit_count,
            author.insertions,
            author.deletions,
            author.commit_percentage(stats.total_commits)
        ));
    }
    md
}

fn heatmap_to_markdown(heatmap: &FileHeatmap) -> String {
    let mut md = String::new();
    md.push_str("# File Heatmap\n\n");
    md.push_str(&format!("**Total Files**: {}\n\n", heatmap.total_files));

    md.push_str("## Hot Files (Most Changed)\n\n");
    md.push_str("| File | Changes | Heat |\n");
    md.push_str("|------|--------:|:----:|\n");
    for file in heatmap.files.iter().take(30) {
        let heat_bar = file.heat_bar();
        md.push_str(&format!(
            "| `{}` | {} | {} |\n",
            file.path, file.change_count, heat_bar
        ));
    }
    md
}

fn impact_to_markdown(analysis: &CommitImpactAnalysis) -> String {
    let mut md = String::new();
    md.push_str("# Impact Score Analysis\n\n");
    md.push_str(&format!(
        "- **Total Commits**: {}\n",
        analysis.total_commits
    ));
    md.push_str(&format!("- **Average Score**: {:.2}\n", analysis.avg_score));
    md.push_str(&format!(
        "- **High Impact Commits**: {}\n\n",
        analysis.high_impact_count
    ));

    md.push_str("## High Impact Commits\n\n");
    md.push_str("| Hash | Author | Score | Files | Message |\n");
    md.push_str("|------|--------|------:|------:|--------|\n");
    for commit in analysis.commits.iter().take(20) {
        let msg = if commit.commit_message.chars().count() > 40 {
            let truncated: String = commit.commit_message.chars().take(37).collect();
            format!("{truncated}...")
        } else {
            commit.commit_message.clone()
        };
        md.push_str(&format!(
            "| `{}` | {} | {:.2} | {} | {} |\n",
            commit.commit_hash, commit.author, commit.score, commit.files_changed, msg
        ));
    }
    md
}

fn coupling_to_markdown(analysis: &ChangeCouplingAnalysis) -> String {
    let mut md = String::new();
    md.push_str("# Change Coupling Analysis\n\n");
    md.push_str(&format!(
        "- **Total Couplings**: {}\n",
        analysis.couplings.len()
    ));
    md.push_str(&format!(
        "- **High Coupling (>70%)**: {}\n\n",
        analysis.high_coupling_count
    ));

    md.push_str("## File Couplings\n\n");
    md.push_str("| File | Coupled With | Coupling | Co-Changes |\n");
    md.push_str("|------|--------------|----------|------------|\n");
    for coupling in analysis.couplings.iter().take(30) {
        md.push_str(&format!(
            "| `{}` | `{}` | {:.1}% | {} |\n",
            coupling.file,
            coupling.coupled_file,
            coupling.coupling_percent * 100.0,
            coupling.co_change_count
        ));
    }
    md
}

fn ownership_to_markdown(ownership: &CodeOwnership) -> String {
    let mut md = String::new();
    md.push_str("# Code Ownership\n\n");
    md.push_str(&format!("**Total Files**: {}\n\n", ownership.total_files));

    md.push_str("## Directory Ownership\n\n");
    md.push_str("| Path | Primary Owner | Ownership | Commits |\n");
    md.push_str("|------|---------------|-----------|--------:|\n");
    for entry in ownership.entries.iter().filter(|e| e.is_directory).take(30) {
        md.push_str(&format!(
            "| `{}/` | {} | {:.1}% | {} |\n",
            entry.path,
            entry.primary_author,
            entry.ownership_percentage(),
            entry.total_commits
        ));
    }
    md
}

fn quality_to_markdown(analysis: &CommitQualityAnalysis) -> String {
    let mut md = String::new();
    md.push_str("# Commit Quality Analysis\n\n");
    md.push_str(&format!(
        "- **Total Commits**: {}\n",
        analysis.total_commits
    ));
    md.push_str(&format!("- **Average Score**: {:.2}\n", analysis.avg_score));
    md.push_str(&format!(
        "- **High Quality (>0.6)**: {}\n",
        analysis.high_quality_count
    ));
    md.push_str(&format!(
        "- **Low Quality (<0.4)**: {}\n\n",
        analysis.low_quality_count
    ));

    md.push_str("## Quality Breakdown\n\n");
    md.push_str("| Hash | Author | Score | Level | Message |\n");
    md.push_str("|------|--------|------:|-------|--------|\n");
    for commit in analysis.commits.iter().take(20) {
        let msg = if commit.commit_message.chars().count() > 40 {
            let truncated: String = commit.commit_message.chars().take(37).collect();
            format!("{truncated}...")
        } else {
            commit.commit_message.clone()
        };
        md.push_str(&format!(
            "| `{}` | {} | {:.2} | {} | {} |\n",
            commit.commit_hash,
            commit.author,
            commit.score,
            commit.quality_level(),
            msg
        ));
    }
    md
}

fn timeline_to_markdown(timeline: &ActivityTimeline) -> String {
    let mut md = String::new();
    md.push_str("# Activity Timeline\n\n");
    md.push_str(&format!(
        "- **Total Commits**: {}\n",
        timeline.total_commits
    ));
    md.push_str(&format!("- **Peak Time**: {}\n\n", timeline.peak_summary()));

    md.push_str("## Weekly Activity Heatmap\n\n");
    md.push_str("```\n");
    md.push_str("Hour:  00 03 06 09 12 15 18 21\n");
    md.push_str("       ┌──────────────────────────\n");
    for day in 0..7 {
        md.push_str(&format!(" {}", ActivityTimeline::day_name(day)));
        for hour in (0..24).step_by(3) {
            let level = timeline.heat_level(day, hour);
            md.push_str(ActivityTimeline::heat_char(level));
            md.push(' ');
        }
        md.push('\n');
    }
    md.push_str("```\n");
    md
}

fn bus_factor_to_markdown(analysis: &BusFactorAnalysis) -> String {
    let mut md = String::new();
    md.push_str("# Bus Factor Analysis\n\n");
    md.push_str(&format!(
        "- **Paths Analyzed**: {}\n",
        analysis.total_paths_analyzed
    ));
    md.push_str(&format!(
        "- **High Risk (Bus Factor = 1)**: {}\n",
        analysis.high_risk_count
    ));
    md.push_str(&format!(
        "- **Medium Risk (Bus Factor = 2)**: {}\n\n",
        analysis.medium_risk_count
    ));

    if analysis.high_risk_count > 0 {
        md.push_str("## ⚠️ High Risk Areas\n\n");
        md.push_str("These areas have only **1 person** with significant knowledge:\n\n");
        md.push_str("| Path | Bus Factor | Primary Contributor | Ownership |\n");
        md.push_str("|------|:----------:|---------------------|----------:|\n");
        for entry in analysis
            .entries
            .iter()
            .filter(|e| e.bus_factor == 1)
            .take(20)
        {
            if let Some(c) = entry.contributors.first() {
                md.push_str(&format!(
                    "| `{}/` | {} | {} | {:.1}% |\n",
                    entry.path, entry.bus_factor, c.name, c.contribution_percent
                ));
            }
        }
        md.push('\n');
    }

    md.push_str("## All Areas by Risk\n\n");
    md.push_str("| Path | Bus Factor | Risk | Top Contributors |\n");
    md.push_str("|------|:----------:|------|------------------|\n");
    for entry in analysis.entries.iter().take(30) {
        let contributors: Vec<String> = entry
            .contributors
            .iter()
            .take(3)
            .map(|c| format!("{} ({:.0}%)", c.name, c.contribution_percent))
            .collect();
        md.push_str(&format!(
            "| `{}/` | {} | {} | {} |\n",
            entry.path,
            entry.bus_factor,
            entry.risk_level.display_name(),
            contributors.join(", ")
        ));
    }
    md
}

fn tech_debt_to_markdown(analysis: &TechDebtAnalysis) -> String {
    let mut md = String::new();
    md.push_str("# Technical Debt Analysis\n\n");
    md.push_str(&format!(
        "- **Files Analyzed**: {}\n",
        analysis.total_files_analyzed
    ));
    md.push_str(&format!("- **Average Score**: {:.2}\n", analysis.avg_score));
    md.push_str(&format!(
        "- **High Debt Files**: {}\n\n",
        analysis.high_debt_count
    ));

    if analysis.high_debt_count > 0 {
        md.push_str("## ⚠️ High Debt Files\n\n");
        md.push_str("These files have high churn and complexity:\n\n");
        md.push_str("| File | Score | Churn | Complexity | Changes |\n");
        md.push_str("|------|------:|------:|-----------:|--------:|\n");
        for entry in analysis
            .entries
            .iter()
            .filter(|e| e.debt_level == crate::stats::TechDebtLevel::High)
            .take(20)
        {
            md.push_str(&format!(
                "| `{}` | {:.2} | {:.2} | {:.2} | {} |\n",
                entry.path,
                entry.score,
                entry.churn_score,
                entry.complexity_score,
                entry.change_count
            ));
        }
        md.push('\n');
    }

    md.push_str("## All Files by Debt Score\n\n");
    md.push_str("| File | Score | Level | Changes | Total Lines |\n");
    md.push_str("|------|------:|-------|--------:|------------:|\n");
    for entry in analysis.entries.iter().take(30) {
        md.push_str(&format!(
            "| `{}` | {:.2} | {} | {} | {} |\n",
            entry.path,
            entry.score,
            entry.debt_level.display_name(),
            entry.change_count,
            entry.total_changes
        ));
    }
    md
}

fn log_to_markdown(events: &[GitEvent]) -> String {
    let mut md = String::new();
    md.push_str("# Recent Commits\n\n");
    md.push_str(&format!("**Showing**: {} commits\n\n", events.len()));

    md.push_str("| Hash | Author | Date | Message |\n");
    md.push_str("|------|--------|------|--------|\n");
    for event in events {
        let date = event.timestamp.format("%Y-%m-%d");
        let msg = if event.message.chars().count() > 50 {
            let truncated: String = event.message.chars().take(47).collect();
            format!("{truncated}...")
        } else {
            event.message.clone()
        };
        md.push_str(&format!(
            "| `{}` | {} | {} | {} |\n",
            event.short_hash, event.author, date, msg
        ));
    }
    md
}

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

    #[test]
    fn test_parse_cli_args_stats() {
        assert_eq!(
            CliCommand::Stats {
                format: OutputFormat::Json
            },
            CliCommand::Stats {
                format: OutputFormat::Json
            }
        );
    }

    #[test]
    fn test_parse_cli_args_help() {
        assert_eq!(CliCommand::Help, CliCommand::Help);
    }

    #[test]
    fn test_parse_cli_args_version() {
        assert_eq!(CliCommand::Version, CliCommand::Version);
    }

    #[test]
    fn test_parse_cli_args_log_default() {
        let log = CliCommand::Log {
            limit: 10,
            format: OutputFormat::Json,
        };
        if let CliCommand::Log { limit, .. } = log {
            assert_eq!(limit, 10);
        }
    }

    #[test]
    fn test_output_format_from_str() {
        assert_eq!(OutputFormat::from_str("json"), Some(OutputFormat::Json));
        assert_eq!(OutputFormat::from_str("JSON"), Some(OutputFormat::Json));
        assert_eq!(OutputFormat::from_str("md"), Some(OutputFormat::Markdown));
        assert_eq!(
            OutputFormat::from_str("markdown"),
            Some(OutputFormat::Markdown)
        );
        assert_eq!(OutputFormat::from_str("invalid"), None);
    }

    #[test]
    fn test_parse_tui_options_defaults() {
        let args = vec!["gitstack".to_string()];
        let opts = parse_tui_options(&args);
        assert_eq!(opts.focus, None);
    }

    #[test]
    fn test_parse_tui_options_valid_focus() {
        let args = vec![
            "gitstack".to_string(),
            "--focus".to_string(),
            "risk".to_string(),
        ];
        let opts = parse_tui_options(&args);
        assert_eq!(opts.focus, Some(TuiFocusTarget::Risk));
    }

    #[test]
    fn test_parse_tui_options_legacy_layout_ignored() {
        let args = vec![
            "gitstack".to_string(),
            "--layout".to_string(),
            "micro".to_string(),
            "--focus".to_string(),
            "review".to_string(),
        ];
        let opts = parse_tui_options(&args);
        // --layout is ignored, --focus still works
        assert_eq!(opts.focus, Some(TuiFocusTarget::Review));
    }

    #[test]
    fn test_parse_quick_action_defaults_compact() {
        let args = vec![
            "gitstack".to_string(),
            "--quick-action".to_string(),
            "verify".to_string(),
        ];
        let cmd = parse_cli_args_from(&args).expect("command");
        match cmd {
            CliCommand::QuickAction { id, compact, .. } => {
                assert_eq!(id, "verify");
                assert!(compact);
            }
            _ => panic!("expected quick action"),
        }
    }

    #[test]
    fn test_parse_quick_action_full_mode() {
        let args = vec![
            "gitstack".to_string(),
            "--quick-action".to_string(),
            "review-pack".to_string(),
            "--quick-action-format".to_string(),
            "full".to_string(),
        ];
        let cmd = parse_cli_args_from(&args).expect("command");
        match cmd {
            CliCommand::QuickAction { compact, .. } => assert!(!compact),
            _ => panic!("expected quick action"),
        }
    }

    #[test]
    fn test_parse_metrics_command() {
        let args = vec![
            "gitstack".to_string(),
            "--metrics".to_string(),
            "quick-actions".to_string(),
        ];
        let cmd = parse_metrics_args_from(&args).expect("metrics command");
        match cmd {
            CliCommand::Metrics { scope, .. } => assert_eq!(scope, "quick-actions"),
            _ => panic!("expected metrics command"),
        }
    }

    fn parse_cli_args_from(args: &[String]) -> Option<CliCommand> {
        // For testing: runs the equivalent of parse_cli_args with specified arguments
        let format = super::find_format_option(args);
        let mut i = 1;
        while i < args.len() {
            if args[i].as_str() == "--quick-action" {
                let id = args
                    .get(i + 1)
                    .filter(|s| !s.starts_with('-'))
                    .cloned()
                    .unwrap_or_else(|| "risk-summary".to_string());
                let compact = super::find_quick_action_format(args)
                    .map(|s| s == "compact")
                    .unwrap_or(true);
                return Some(CliCommand::QuickAction {
                    id,
                    compact,
                    format,
                });
            }
            i += 1;
        }
        None
    }

    fn parse_metrics_args_from(args: &[String]) -> Option<CliCommand> {
        let format = super::find_format_option(args);
        let mut i = 1;
        while i < args.len() {
            if args[i].as_str() == "--metrics" {
                let scope = args
                    .get(i + 1)
                    .filter(|s| !s.starts_with('-'))
                    .cloned()
                    .unwrap_or_else(|| "quick-actions".to_string());
                return Some(CliCommand::Metrics { scope, format });
            }
            i += 1;
        }
        None
    }
}