cargo-coupling 0.3.7

A coupling analysis tool for Rust projects - measuring the 'right distance' in your code
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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
//! Text and Markdown report rendering for coupling analysis.
//!
//! This module translates balance scores, issue lists, volatility signals, and
//! blind-spot manifests into CLI-facing summaries and full reports.

use std::io::{self, Write};

use crate::balance::action::RefactoringAction;
use crate::balance::coupling::is_crate_root_facade;
use crate::balance::grade::{HealthGrade, ProjectBalanceReport};
use crate::balance::issue::CouplingIssue;
use crate::balance::issue_type::IssueType;
use crate::balance::project::analyze_project_balance_with_thresholds;
use crate::balance::score::{BalanceInterpretation, BalanceScore, IssueThresholds};
use crate::balance::severity::Severity;
use crate::manifest::{AnalysisManifest, ManifestContext, build_manifest};
use crate::metrics::dimensions::{Distance, IntegrationStrength};
use crate::metrics::project::ProjectMetrics;

const DEFAULT_STRONG_TEMPORAL_LIMIT: usize = 5;

// ===== Report Options =====

/// Options for the default human-readable text report.
#[derive(Debug, Clone, Copy, Default)]
pub struct TextReportOptions {
    /// Include the full structural blind-spot descriptions instead of a pointer.
    pub show_structural_blind_spots: bool,
    /// Include all temporal-coupling pairs instead of the concise default.
    pub show_all_temporal_couplings: bool,
}

// ===== Summary Report =====

/// Generate a summary report to the given writer
pub fn generate_summary<W: Write>(metrics: &ProjectMetrics, writer: &mut W) -> io::Result<()> {
    let manifest = default_manifest();
    generate_summary_with_thresholds(metrics, &IssueThresholds::default(), &manifest, writer)
}

/// Generate a summary report with custom thresholds
pub fn generate_summary_with_thresholds<W: Write>(
    metrics: &ProjectMetrics,
    thresholds: &IssueThresholds,
    manifest: &AnalysisManifest,
    writer: &mut W,
) -> io::Result<()> {
    generate_summary_with_options(metrics, thresholds, manifest, false, writer)
}

/// Generate a summary report with custom thresholds and blind-spot detail.
pub fn generate_summary_with_options<W: Write>(
    metrics: &ProjectMetrics,
    thresholds: &IssueThresholds,
    manifest: &AnalysisManifest,
    show_structural_blind_spots: bool,
    writer: &mut W,
) -> io::Result<()> {
    let report = analyze_project_balance_with_thresholds(metrics, thresholds);
    let dimension_stats = metrics.calculate_dimension_stats();
    let jp = thresholds.japanese;

    let project_name = metrics.workspace_name.as_deref().unwrap_or("project");

    if jp {
        writeln!(writer, "カップリング分析: {}", project_name)?;
        writeln!(writer, "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "評価: {} | スコア: {:.2}/1.00 | モジュール数: {}",
            report.health_grade,
            report.average_score,
            metrics.module_count()
        )?;
        writeln!(writer, "理由: {}", report.grade_rationale.summary)?;
    } else {
        writeln!(writer, "Balanced Coupling Analysis: {}", project_name)?;
        writeln!(writer, "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "Grade: {} | Score: {:.2}/1.00 | Modules: {}",
            report.health_grade,
            report.average_score,
            metrics.module_count()
        )?;
        writeln!(writer, "Why this grade: {}", report.grade_rationale.summary)?;
    }
    writeln!(writer)?;

    // 3-Dimensional Analysis
    if !metrics.couplings.is_empty() {
        // Strength distribution
        let (intr_pct, func_pct, model_pct, contract_pct) = dimension_stats.strength_percentages();
        // Distance distribution
        let (same_pct, diff_pct, ext_pct) = dimension_stats.distance_percentages();
        // Volatility distribution
        let (low_pct, med_pct, high_pct) = dimension_stats.volatility_percentages();

        if jp {
            writeln!(writer, "3次元分析:")?;
            writeln!(
                writer,
                "  結合強度: Contract {:.0}% / Model {:.0}% / Functional {:.0}% / Intrusive {:.0}%",
                contract_pct, model_pct, func_pct, intr_pct
            )?;
            writeln!(
                writer,
                "           (トレイト)   (型)      (関数)        (内部アクセス)"
            )?;
            writeln!(
                writer,
                "  距離:     同一モジュール {:.0}% / 別モジュール {:.0}% / 外部 {:.0}%",
                same_pct, diff_pct, ext_pct
            )?;
            writeln!(
                writer,
                "  変更頻度: 低 {:.0}% / 中 {:.0}% / 高 {:.0}%",
                low_pct, med_pct, high_pct
            )?;
        } else {
            writeln!(writer, "3-Dimensional Analysis:")?;
            writeln!(
                writer,
                "  Strength:   Contract {:.0}% / Model {:.0}% / Functional {:.0}% / Intrusive {:.0}%",
                contract_pct, model_pct, func_pct, intr_pct
            )?;
            writeln!(
                writer,
                "  Distance:   Same {:.0}% / Different {:.0}% / External {:.0}%",
                same_pct, diff_pct, ext_pct
            )?;
            writeln!(
                writer,
                "  Volatility: Low {:.0}% / Medium {:.0}% / High {:.0}%",
                low_pct, med_pct, high_pct
            )?;
        }
        writeln!(writer)?;

        // Balance Classification
        if jp {
            writeln!(writer, "バランス状態:")?;
        } else {
            writeln!(writer, "Balance State:")?;
        }
        let bc = &dimension_stats.balance_counts;
        let total = dimension_stats.total();
        if bc.high_cohesion > 0 {
            if jp {
                writeln!(
                    writer,
                    "  ✅ 高凝集 (強い結合 + 近い距離): {} ({:.0}%) ← 理想的",
                    bc.high_cohesion,
                    bc.high_cohesion as f64 / total as f64 * 100.0
                )?;
            } else {
                writeln!(
                    writer,
                    "  ✅ High Cohesion (strong+close): {} ({:.0}%)",
                    bc.high_cohesion,
                    bc.high_cohesion as f64 / total as f64 * 100.0
                )?;
            }
        }
        if bc.loose_coupling > 0 {
            if jp {
                writeln!(
                    writer,
                    "  ✅ 疎結合 (弱い結合 + 遠い距離): {} ({:.0}%) ← 理想的",
                    bc.loose_coupling,
                    bc.loose_coupling as f64 / total as f64 * 100.0
                )?;
            } else {
                writeln!(
                    writer,
                    "  ✅ Loose Coupling (weak+far): {} ({:.0}%)",
                    bc.loose_coupling,
                    bc.loose_coupling as f64 / total as f64 * 100.0
                )?;
            }
        }
        if bc.acceptable > 0 {
            if jp {
                writeln!(
                    writer,
                    "  🤔 許容可能 (強い結合 + 遠い距離 + 安定): {} ({:.0}%)",
                    bc.acceptable,
                    bc.acceptable as f64 / total as f64 * 100.0
                )?;
            } else {
                writeln!(
                    writer,
                    "  🤔 Acceptable (strong+far+stable): {} ({:.0}%)",
                    bc.acceptable,
                    bc.acceptable as f64 / total as f64 * 100.0
                )?;
            }
        }
        if bc.pain > 0 {
            if jp {
                writeln!(
                    writer,
                    "  ❌ ペインゾーン (強い結合 + 遠い距離 + 頻繁に変更): {} ({:.0}%)",
                    bc.pain,
                    bc.pain as f64 / total as f64 * 100.0
                )?;
            } else {
                writeln!(
                    writer,
                    "  ❌ Pain Zone (strong+far+volatile): {} ({:.0}%)",
                    bc.pain,
                    bc.pain as f64 / total as f64 * 100.0
                )?;
            }
        }
        if bc.local_complexity > 0 {
            if jp {
                writeln!(
                    writer,
                    "  🔍 局所的複雑性 (弱い結合 + 近い距離): {} ({:.0}%)",
                    bc.local_complexity,
                    bc.local_complexity as f64 / total as f64 * 100.0
                )?;
            } else {
                writeln!(
                    writer,
                    "  🔍 Local Complexity (weak+close): {} ({:.0}%)",
                    bc.local_complexity,
                    bc.local_complexity as f64 / total as f64 * 100.0
                )?;
            }
        }
        writeln!(writer)?;
    }

    // Issue breakdown
    let critical = *report
        .issues_by_severity
        .get(&Severity::Critical)
        .unwrap_or(&0);
    let high = *report.issues_by_severity.get(&Severity::High).unwrap_or(&0);
    let medium = *report
        .issues_by_severity
        .get(&Severity::Medium)
        .unwrap_or(&0);
    let low = *report.issues_by_severity.get(&Severity::Low).unwrap_or(&0);

    if critical > 0 || high > 0 || medium > 0 || low > 0 {
        if jp {
            writeln!(writer, "検出された問題:")?;
            if critical > 0 {
                writeln!(writer, "  🔴 緊急: {} 件 (すぐに修正が必要)", critical)?;
            }
            if high > 0 {
                writeln!(writer, "  🟠 高: {} 件 (早めに対処)", high)?;
            }
            if medium > 0 {
                writeln!(writer, "  🟡 中: {}", medium)?;
            }
            if low > 0 {
                writeln!(writer, "  ⚪ 低: {}", low)?;
            }
        } else {
            writeln!(writer, "Detected Issues:")?;
            if critical > 0 {
                writeln!(writer, "  🔴 Critical: {} (must fix)", critical)?;
            }
            if high > 0 {
                writeln!(writer, "  🟠 High: {} (should fix)", high)?;
            }
            if medium > 0 {
                writeln!(writer, "  🟡 Medium: {}", medium)?;
            }
            if low > 0 {
                writeln!(writer, "  ⚪ Low: {}", low)?;
            }
        }
        writeln!(writer)?;
    } else if thresholds.strict_mode {
        if jp {
            writeln!(writer, "検出された問題: なし (--all で低優先度も表示)\n")?;
        } else {
            writeln!(
                writer,
                "Detected Issues: None (use --all to see Low severity)\n"
            )?;
        }
    }

    // Top priority if any
    if !report.top_priorities.is_empty() {
        if jp {
            writeln!(writer, "優先的に対処すべき問題:")?;
            for issue in report.top_priorities.iter().take(3) {
                let issue_jp = issue_type_japanese(issue.issue_type);
                writeln!(writer, "  - {} | {}", issue_jp, issue.source)?;
                writeln!(
                    writer,
                    "{}",
                    refactoring_action_japanese(&issue.refactoring)
                )?;
            }
        } else {
            writeln!(writer, "Top Priorities:")?;
            for issue in report.top_priorities.iter().take(3) {
                writeln!(
                    writer,
                    "  - [{}] {}{}",
                    issue.severity, issue.source, issue.target
                )?;
            }
        }
        writeln!(writer)?;
    }

    // Rust Design Quality (newtype usage)
    let newtype_count = metrics.total_newtype_count();
    let type_count = metrics.total_type_count();
    if type_count > 0 {
        let newtype_ratio = metrics.newtype_ratio() * 100.0;
        if jp {
            let quality = if newtype_ratio >= 20.0 {
                "✅ 良好"
            } else if newtype_ratio >= 10.0 {
                "🤔 増やすことを検討"
            } else {
                "⚠️ 少ない"
            };
            writeln!(
                writer,
                "Rustパターン: newtype使用率 {}/{} ({:.0}%) - {}",
                newtype_count, type_count, newtype_ratio, quality
            )?;
        } else {
            let quality = if newtype_ratio >= 20.0 {
                "✅ Good"
            } else if newtype_ratio >= 10.0 {
                "🤔 Consider more"
            } else {
                "⚠️ Low usage"
            };
            writeln!(
                writer,
                "Rust Patterns: Newtype usage: {}/{} ({:.0}%) - {}",
                newtype_count, type_count, newtype_ratio, quality
            )?;
        }
        writeln!(writer)?;
    }

    // Circular dependencies
    let circular = metrics.circular_dependency_summary();
    if circular.total_cycles > 0 {
        if jp {
            writeln!(
                writer,
                "⚠️ 循環依存: {} サイクル ({} モジュール)",
                circular.total_cycles, circular.affected_modules
            )?;
        } else {
            writeln!(
                writer,
                "⚠️ Circular Dependencies: {} cycles ({} modules)",
                circular.total_cycles, circular.affected_modules
            )?;
        }
    }

    // Design decision guide (Japanese only, for educational purposes)
    if jp {
        writeln!(writer)?;
        writeln!(writer, "設計判断ガイド (Khononov):")?;
        writeln!(writer, "  ✅ 強い結合 + 近い距離 → 高凝集 (理想的)")?;
        writeln!(writer, "  ✅ 弱い結合 + 遠い距離 → 疎結合 (理想的)")?;
        writeln!(writer, "  🤔 強い結合 + 遠い距離 + 安定 → 許容可能")?;
        writeln!(
            writer,
            "  ❌ 強い結合 + 遠い距離 + 頻繁に変更 → 要リファクタリング"
        )?;
    }

    write_manifest_summary_section(manifest, jp, show_structural_blind_spots, writer)?;

    Ok(())
}

// ===== Localization Helpers =====

/// Get Japanese translation for issue type
fn issue_type_japanese(issue_type: IssueType) -> &'static str {
    use IssueType;
    match issue_type {
        IssueType::GlobalComplexity => "グローバル複雑性 (遠距離への強い依存)",
        IssueType::CascadingChangeRisk => "変更波及リスク (頻繁に変わるものへの依存)",
        IssueType::InappropriateIntimacy => "不適切な親密さ (内部実装への依存)",
        IssueType::HighEfferentCoupling => "出力依存過多 (多くのモジュールに依存)",
        IssueType::HighAfferentCoupling => "入力依存過多 (多くのモジュールから依存される)",
        IssueType::UnnecessaryAbstraction => "過剰な抽象化",
        IssueType::CircularDependency => "循環依存",
        IssueType::HiddenCoupling => "隠れた結合 (共変更のみで発見)",
        IssueType::AccidentalVolatility => "偶発的な変更頻度",
        IssueType::ScatteredExternalCoupling => "外部クレート結合の分散",
        IssueType::ShallowModule => "浅いモジュール",
        IssueType::PassThroughMethod => "パススルーメソッド",
        IssueType::HighCognitiveLoad => "高認知負荷",
        IssueType::GodModule => "神モジュール (責務が多すぎる)",
        IssueType::PublicFieldExposure => "公開フィールド (getterを検討)",
        IssueType::PrimitiveObsession => "プリミティブ過多 (newtypeを検討)",
    }
}

/// Get Japanese translation for refactoring action
fn refactoring_action_japanese(action: &RefactoringAction) -> String {
    use RefactoringAction;
    match action {
        RefactoringAction::IntroduceTrait { suggested_name, .. } => {
            format!("トレイト `{}` を導入して抽象化する", suggested_name)
        }
        RefactoringAction::MoveCloser { target_location } => {
            format!("`{}` に移動して距離を縮める", target_location)
        }
        RefactoringAction::ExtractAdapter { adapter_name, .. } => {
            format!("アダプタ `{}` を抽出する", adapter_name)
        }
        RefactoringAction::SplitModule { suggested_modules } => {
            format!("モジュールを分割: {}", suggested_modules.join(", "))
        }
        RefactoringAction::SimplifyAbstraction { .. } => "抽象化を簡素化する".to_string(),
        RefactoringAction::BreakCycle {
            suggested_direction,
        } => {
            format!("循環を断つ: {}", suggested_direction)
        }
        RefactoringAction::StabilizeInterface { interface_name } => {
            format!("安定したインターフェース `{}` を追加", interface_name)
        }
        RefactoringAction::General { action } => {
            if action.starts_with("Introduce a `") && action.contains("` facade/wrapper module") {
                let facade = action.split('`').nth(1).unwrap_or("facade");
                format!("`{}` モジュールを導入し、直接利用をそこに集約する", facade)
            } else if action == "Extract a shared abstraction or make the dependency explicit" {
                "共有された抽象化を抽出するか、依存関係を明示する".to_string()
            } else {
                action.clone()
            }
        }
        RefactoringAction::AddGetters { .. } => "getterメソッドを追加する".to_string(),
        RefactoringAction::IntroduceNewtype {
            suggested_name,
            wrapped_type,
        } => {
            format!(
                "newtype `struct {}({})` を導入",
                suggested_name, wrapped_type
            )
        }
    }
}

fn issue_instance_description_japanese(issue: &CouplingIssue) -> String {
    use IssueType;
    match issue.issue_type {
        IssueType::HiddenCoupling => {
            "明示的なコード依存はありませんが、ファイルが頻繁に一緒に変更されています。暗黙の知識や不足した抽象化を示している可能性があります。"
                .to_string()
        }
        IssueType::AccidentalVolatility => {
            "安定しているはずのサブドメインが頻繁に変更されています。本質的な業務変化ではなく、設計や所有権の問題によるチャーンの可能性があります。"
                .to_string()
        }
        IssueType::ScatteredExternalCoupling => {
            format!(
                "{} は複数の内部モジュールから直接使われています。サードパーティ更新時のリスクがコードベース全体に広がっています。",
                issue.target
            )
        }
        _ => issue.description.clone(),
    }
}

// ===== Full Markdown Report =====

/// Generate a full Markdown report with refactoring suggestions
pub fn generate_report<W: Write>(metrics: &ProjectMetrics, writer: &mut W) -> io::Result<()> {
    let manifest = default_manifest();
    generate_report_with_thresholds(metrics, &IssueThresholds::default(), &manifest, writer)
}

/// Generate a full Markdown report with custom thresholds
pub fn generate_report_with_thresholds<W: Write>(
    metrics: &ProjectMetrics,
    thresholds: &IssueThresholds,
    manifest: &AnalysisManifest,
    writer: &mut W,
) -> io::Result<()> {
    generate_report_with_options(
        metrics,
        thresholds,
        manifest,
        TextReportOptions::default(),
        writer,
    )
}

/// Generate a full Markdown report with custom thresholds and text options.
pub fn generate_report_with_options<W: Write>(
    metrics: &ProjectMetrics,
    thresholds: &IssueThresholds,
    manifest: &AnalysisManifest,
    options: TextReportOptions,
    writer: &mut W,
) -> io::Result<()> {
    let report = analyze_project_balance_with_thresholds(metrics, thresholds);

    writeln!(writer, "# Coupling Analysis Report\n")?;

    // Executive Summary
    let jp = thresholds.japanese;
    write_executive_summary(metrics, &report, jp, writer)?;

    // Refactoring Priorities (if any issues)
    if !report.issues.is_empty() {
        write_refactoring_priorities(&report, jp, writer)?;
    }

    // Detailed Issues by Type
    write_issues_by_type(&report, jp, writer)?;

    // Coupling details
    write_coupling_section(metrics, writer)?;

    // Module analysis
    write_module_section(metrics, writer)?;

    // Volatility section
    write_volatility_section(metrics, writer)?;

    // Temporal coupling section
    write_temporal_coupling_section(metrics, options.show_all_temporal_couplings, writer)?;

    // Circular dependency section
    write_circular_dependencies_section(metrics, writer)?;

    // Best practices
    write_best_practices(writer)?;

    // Declared analysis blind spots
    write_manifest_markdown_section(manifest, options.show_structural_blind_spots, jp, writer)?;

    Ok(())
}

fn write_executive_summary<W: Write>(
    metrics: &ProjectMetrics,
    report: &ProjectBalanceReport,
    japanese: bool,
    writer: &mut W,
) -> io::Result<()> {
    writeln!(writer, "## Executive Summary\n")?;

    // Health Grade with emoji
    let grade_emoji = match report.health_grade {
        HealthGrade::S => "⚠️",
        HealthGrade::A => "🟢",
        HealthGrade::B => "🟢",
        HealthGrade::C => "🟡",
        HealthGrade::D => "🟠",
        HealthGrade::F => "🔴",
    };

    writeln!(
        writer,
        "**Health Grade**: {} {}\n",
        grade_emoji, report.health_grade
    )?;
    if japanese {
        writeln!(
            writer,
            "**このグレードの理由**: {}\n",
            report.grade_rationale.summary
        )?;
    } else {
        writeln!(
            writer,
            "**Why this grade**: {}\n",
            report.grade_rationale.summary
        )?;
    }

    writeln!(writer, "| Metric | Value |")?;
    writeln!(writer, "|--------|-------|")?;
    writeln!(writer, "| Files Analyzed | {} |", metrics.total_files)?;
    writeln!(writer, "| Total Modules | {} |", metrics.module_count())?;
    writeln!(writer, "| Total Couplings | {} |", report.total_couplings)?;
    writeln!(
        writer,
        "| Balance Score | {:.2}/1.00 |",
        report.average_score
    )?;
    writeln!(
        writer,
        "| Balanced | {} ({:.0}%) |",
        report.balanced_count,
        if report.total_couplings > 0 {
            (report.balanced_count as f64 / report.total_couplings as f64) * 100.0
        } else {
            100.0
        }
    )?;
    // This headline count mirrors `report.issues`/JSON `issues`; balance buckets
    // such as Pain Zone are separate coupling classifications, not surfaced issues.
    writeln!(writer, "| Issues Surfaced | {} |", report.issues.len())?;
    writeln!(writer)?;

    // Issue counts
    let critical = *report
        .issues_by_severity
        .get(&Severity::Critical)
        .unwrap_or(&0);
    let high = *report.issues_by_severity.get(&Severity::High).unwrap_or(&0);
    let medium = *report
        .issues_by_severity
        .get(&Severity::Medium)
        .unwrap_or(&0);
    let low = *report.issues_by_severity.get(&Severity::Low).unwrap_or(&0);

    if critical > 0 || high > 0 {
        writeln!(writer, "**⚠️ Action Required**\n")?;
        if critical > 0 {
            writeln!(
                writer,
                "- 🔴 **{} Critical** issues must be fixed immediately",
                critical
            )?;
        }
        if high > 0 {
            writeln!(
                writer,
                "- 🟠 **{} High** priority issues should be addressed soon",
                high
            )?;
        }
        if medium > 0 {
            writeln!(writer, "- 🟡 {} Medium priority issues to review", medium)?;
        }
        if low > 0 {
            writeln!(writer, "- {} Low priority suggestions", low)?;
        }
        writeln!(writer)?;
    } else if medium > 0 {
        writeln!(
            writer,
            "**ℹ️ Review Suggested**: {} issues to consider.\n",
            medium + low
        )?;
    } else {
        writeln!(
            writer,
            "**✅ Good Health**: No significant coupling issues detected.\n"
        )?;
    }

    Ok(())
}

fn write_refactoring_priorities<W: Write>(
    report: &ProjectBalanceReport,
    japanese: bool,
    writer: &mut W,
) -> io::Result<()> {
    writeln!(writer, "## 🔧 Refactoring Priorities\n")?;

    // Show top 5 priority issues with concrete actions
    writeln!(writer, "### Immediate Actions\n")?;

    // Deduplicate by (type, source, target): several couplings between the same
    // module pair otherwise fill the list with identical "Immediate Actions".
    let mut seen_priorities = std::collections::HashSet::new();
    let priority_issues: Vec<_> = report
        .issues
        .iter()
        .filter(|i| i.severity >= Severity::Medium)
        .filter(|i| seen_priorities.insert((i.issue_type, i.source.clone(), i.target.clone())))
        .take(5)
        .collect();

    if priority_issues.is_empty() {
        writeln!(writer, "No immediate refactoring actions required.\n")?;
        return Ok(());
    }

    for (i, issue) in priority_issues.iter().enumerate() {
        let severity_icon = match issue.severity {
            Severity::Critical => "🔴",
            Severity::High => "🟠",
            Severity::Medium => "🟡",
            Severity::Low => "",
        };

        writeln!(
            writer,
            "**{}. {} `{}` → `{}`**\n",
            i + 1,
            severity_icon,
            issue.source,
            issue.target
        )?;

        let issue_label = if japanese {
            issue_type_japanese(issue.issue_type).to_string()
        } else {
            issue.issue_type.to_string()
        };
        let issue_description = if japanese {
            issue_instance_description_japanese(issue)
        } else {
            issue.description.clone()
        };
        writeln!(
            writer,
            "- **Issue**: {} - {}",
            issue_label, issue_description
        )?;
        if japanese {
            writeln!(
                writer,
                "- **Why**: {}",
                issue.issue_type.description_japanese()
            )?;
            writeln!(
                writer,
                "- **Action**: {}",
                refactoring_action_japanese(&issue.refactoring)
            )?;
        } else {
            writeln!(writer, "- **Why**: {}", issue.issue_type.description())?;
            writeln!(writer, "- **Action**: {}", issue.refactoring)?;
        }
        writeln!(writer, "- **Balance Score**: {:.2}\n", issue.balance_score)?;
    }

    Ok(())
}

/// Whether an issue is driven by volatility/churn (may settle) rather than structure.
fn issue_is_volatility_driven(issue: &CouplingIssue) -> bool {
    match issue.issue_type {
        IssueType::AccidentalVolatility => true,
        IssueType::CascadingChangeRisk => issue.description.contains("accidental volatility"),
        _ => false,
    }
}

/// Triage surfaced issues by nature: structural (act now) vs volatility-driven
/// (may settle). Expected-by-design patterns are downgraded elsewhere and omitted.
fn write_issue_triage<W: Write>(
    report: &ProjectBalanceReport,
    japanese: bool,
    writer: &mut W,
) -> io::Result<()> {
    let (volatility, structural): (Vec<_>, Vec<_>) = report
        .issues
        .iter()
        .partition(|i| issue_is_volatility_driven(i));

    let label = |i: &CouplingIssue| -> String {
        let name = if japanese {
            issue_type_japanese(i.issue_type)
        } else {
            // IssueType Display is English.
            return format!("**{}** `{}` → `{}`", i.issue_type, i.source, i.target);
        };
        format!("**{}** `{}` → `{}`", name, i.source, i.target)
    };

    if japanese {
        writeln!(writer, "## 課題のトリアージ\n")?;
        writeln!(
            writer,
            "### 構造的な課題 — 今すぐ対応 ({} 件)\n",
            structural.len()
        )?;
        for i in &structural {
            writeln!(writer, "- {}", label(i))?;
        }
        writeln!(
            writer,
            "\n### 変更頻度由来 — 落ち着く可能性あり ({} 件)\n",
            volatility.len()
        )?;
        for i in &volatility {
            writeln!(writer, "- {}", label(i))?;
        }
        writeln!(
            writer,
            "\n> エントリポイントの広い依存や安定した中心モジュールなど、設計上想定される項目は重大度を下げて一覧から除外しています。\n"
        )?;
    } else {
        writeln!(writer, "## Issue Triage\n")?;
        writeln!(writer, "### Structural — act now ({})\n", structural.len())?;
        for i in &structural {
            writeln!(writer, "- {}", label(i))?;
        }
        writeln!(
            writer,
            "\n### Volatility-driven — may settle ({})\n",
            volatility.len()
        )?;
        for i in &volatility {
            writeln!(writer, "- {}", label(i))?;
        }
        writeln!(
            writer,
            "\n> Expected-by-design patterns (entrypoint fan-out, stable central abstractions) are downgraded and omitted here.\n"
        )?;
    }

    Ok(())
}

fn write_issues_by_type<W: Write>(
    report: &ProjectBalanceReport,
    japanese: bool,
    writer: &mut W,
) -> io::Result<()> {
    if report.issues.is_empty() {
        return Ok(());
    }

    write_issue_triage(report, japanese, writer)?;

    writeln!(writer, "## Issues by Category\n")?;

    let grouped = report.issues_grouped_by_type();

    // Order by severity of issues in each group
    let mut issue_types: Vec<_> = grouped.keys().collect();
    issue_types.sort_by(|a, b| {
        let a_max = grouped
            .get(a)
            .and_then(|v| v.iter().map(|i| i.severity).max());
        let b_max = grouped
            .get(b)
            .and_then(|v| v.iter().map(|i| i.severity).max());
        b_max.cmp(&a_max)
    });

    for issue_type in issue_types {
        if let Some(issues) = grouped.get(issue_type) {
            let count = issues.len();

            let issue_label = if japanese {
                issue_type_japanese(*issue_type)
            } else {
                ""
            };
            if japanese {
                writeln!(writer, "### {} ({} 件)\n", issue_label, count)?;
                writeln!(writer, "> {}\n", issue_type.description_japanese())?;
            } else {
                writeln!(writer, "### {} ({} instances)\n", issue_type, count)?;
                writeln!(writer, "> {}\n", issue_type.description())?;
            }

            // Show up to 5 examples
            writeln!(writer, "| Severity | Source | Target | Action |")?;
            writeln!(writer, "|----------|--------|--------|--------|")?;

            for issue in issues.iter().take(5) {
                let action_short = if japanese {
                    refactoring_action_japanese(&issue.refactoring)
                } else {
                    issue.refactoring.to_string()
                };
                let action_truncated = truncate_chars(&action_short, 40);
                writeln!(
                    writer,
                    "| {} | `{}` | `{}` | {} |",
                    issue.severity,
                    truncate_path(&issue.source, 25),
                    truncate_path(&issue.target, 25),
                    action_truncated
                )?;
            }

            if count > 5 {
                writeln!(writer, "\n*...and {} more instances*", count - 5)?;
            }
            writeln!(writer)?;
        }
    }

    Ok(())
}

fn write_coupling_section<W: Write>(metrics: &ProjectMetrics, writer: &mut W) -> io::Result<()> {
    if metrics.couplings.is_empty() {
        return Ok(());
    }

    writeln!(writer, "## Coupling Distribution\n")?;

    // Strength distribution
    writeln!(writer, "### By Integration Strength\n")?;
    writeln!(writer, "| Strength | Count | % | Description |")?;
    writeln!(writer, "|----------|-------|---|-------------|")?;

    let total = metrics.couplings.len() as f64;
    for (strength, label, desc) in [
        (
            IntegrationStrength::Contract,
            "Contract",
            "Depends on traits/interfaces only",
        ),
        (
            IntegrationStrength::Model,
            "Model",
            "Uses data types/structs",
        ),
        (
            IntegrationStrength::Functional,
            "Functional",
            "Calls specific functions",
        ),
        (
            IntegrationStrength::Intrusive,
            "Intrusive",
            "Accesses internal details",
        ),
    ] {
        let count = metrics
            .couplings
            .iter()
            .filter(|c| c.strength == strength)
            .count();
        let pct = (count as f64 / total) * 100.0;
        writeln!(writer, "| {} | {} | {:.0}% | {} |", label, count, pct, desc)?;
    }
    writeln!(writer)?;

    // Distance distribution
    writeln!(writer, "### By Distance\n")?;
    writeln!(writer, "| Distance | Count | % |")?;
    writeln!(writer, "|----------|-------|---|")?;

    for (distance, label) in [
        (Distance::SameModule, "Same Module (close)"),
        (Distance::DifferentModule, "Different Module"),
        (Distance::DifferentCrate, "External Crate (far)"),
    ] {
        let count = metrics
            .couplings
            .iter()
            .filter(|c| c.distance == distance)
            .count();
        let pct = (count as f64 / total) * 100.0;
        writeln!(writer, "| {} | {} | {:.0}% |", label, count, pct)?;
    }
    writeln!(writer)?;

    // Volatility distribution (only for internal couplings where we have git data)
    let internal_couplings: Vec<_> = metrics
        .couplings
        .iter()
        .filter(|c| c.distance != Distance::DifferentCrate)
        .collect();

    if !internal_couplings.is_empty() {
        let internal_total = internal_couplings.len() as f64;
        writeln!(writer, "### By Volatility (Internal Couplings)\n")?;
        writeln!(writer, "| Volatility | Count | % | Impact on Balance |")?;
        writeln!(writer, "|------------|-------|---|-------------------|")?;

        for (volatility, label, impact) in [
            (
                crate::volatility::Volatility::Low,
                "Low (rarely changes)",
                "No penalty",
            ),
            (
                crate::volatility::Volatility::Medium,
                "Medium (sometimes changes)",
                "Moderate penalty",
            ),
            (
                crate::volatility::Volatility::High,
                "High (frequently changes)",
                "Significant penalty",
            ),
        ] {
            let count = internal_couplings
                .iter()
                .filter(|c| c.volatility == volatility)
                .count();
            let pct = (count as f64 / internal_total) * 100.0;
            writeln!(
                writer,
                "| {} | {} | {:.0}% | {} |",
                label, count, pct, impact
            )?;
        }
        writeln!(writer)?;
    }

    // Worst balanced couplings
    writeln!(writer, "### Worst Balanced Couplings\n")?;

    // External (DifferentCrate) couplings are outside our control and are excluded
    // from issue detection everywhere else; the crate-root re-export facade is a
    // stable Contract. Exclude both, and dedupe by (source, target), so this shows
    // distinct, actionable internal couplings.
    let mut seen_worst = std::collections::HashSet::new();
    let mut couplings_with_scores: Vec<_> = metrics
        .couplings
        .iter()
        .filter(|c| c.distance != Distance::DifferentCrate)
        .filter(|c| !is_crate_root_facade(&c.target))
        .filter(|c| seen_worst.insert((c.source.clone(), c.target.clone())))
        .map(|c| (c, BalanceScore::calculate(c)))
        .collect();

    couplings_with_scores.sort_by(|a, b| {
        a.1.score
            .partial_cmp(&b.1.score)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    writeln!(
        writer,
        "| Source | Target | Strength | Distance | Volatility | Score | Status |"
    )?;
    writeln!(
        writer,
        "|--------|--------|----------|----------|------------|-------|--------|"
    )?;

    for (coupling, score) in couplings_with_scores.iter().take(15) {
        let strength_str = match coupling.strength {
            IntegrationStrength::Contract => "Contract",
            IntegrationStrength::Model => "Model",
            IntegrationStrength::Functional => "Functional",
            IntegrationStrength::Intrusive => "Intrusive",
        };
        let distance_str = match coupling.distance {
            Distance::SameFunction => "Same Fn",
            Distance::SameModule => "Same Mod",
            Distance::DifferentModule => "Diff Mod",
            Distance::DifferentCrate => "External",
        };
        let volatility_str = match coupling.volatility {
            crate::volatility::Volatility::Low => "Low",
            crate::volatility::Volatility::Medium => "Med",
            crate::volatility::Volatility::High => "High",
        };
        let status = match score.interpretation {
            BalanceInterpretation::Balanced => "✅ Balanced",
            BalanceInterpretation::Acceptable => "✅ OK",
            BalanceInterpretation::NeedsReview => "🟡 Review",
            BalanceInterpretation::NeedsRefactoring => "🟠 Refactor",
            BalanceInterpretation::Critical => "🔴 Critical",
        };

        writeln!(
            writer,
            "| `{}` | `{}` | {} | {} | {} | {:.2} | {} |",
            truncate_path(&coupling.source, 20),
            truncate_path(&coupling.target, 20),
            strength_str,
            distance_str,
            volatility_str,
            score.score,
            status
        )?;
    }

    if couplings_with_scores.len() > 15 {
        writeln!(
            writer,
            "\n*Showing 15 of {} couplings*",
            couplings_with_scores.len()
        )?;
    }
    writeln!(writer)?;

    Ok(())
}

fn write_module_section<W: Write>(metrics: &ProjectMetrics, writer: &mut W) -> io::Result<()> {
    if metrics.modules.is_empty() {
        return Ok(());
    }

    writeln!(writer, "## Module Statistics\n")?;

    let show_subdomain = metrics
        .modules
        .values()
        .any(|module| module.subdomain.is_some());
    if show_subdomain {
        writeln!(
            writer,
            "| Module | Subdomain | Trait Impl | Inherent Impl | Internal Deps | External Deps |"
        )?;
        writeln!(
            writer,
            "|--------|-----------|------------|---------------|---------------|---------------|"
        )?;
    } else {
        writeln!(
            writer,
            "| Module | Trait Impl | Inherent Impl | Internal Deps | External Deps |"
        )?;
        writeln!(
            writer,
            "|--------|------------|---------------|---------------|---------------|"
        )?;
    }

    let mut modules: Vec<_> = metrics.modules.iter().collect();
    modules.sort_by(|a, b| {
        let a_deps = a.1.internal_deps.len() + a.1.external_deps.len();
        let b_deps = b.1.internal_deps.len() + b.1.external_deps.len();
        b_deps.cmp(&a_deps)
    });

    for (name, module) in modules.iter().take(20) {
        if show_subdomain {
            writeln!(
                writer,
                "| `{}` | {} | {} | {} | {} | {} |",
                truncate_path(name, 30),
                module
                    .subdomain
                    .map(|subdomain| subdomain.to_string())
                    .unwrap_or_else(|| "-".to_string()),
                module.trait_impl_count,
                module.inherent_impl_count,
                module.internal_deps.len(),
                module.external_deps.len()
            )?;
        } else {
            writeln!(
                writer,
                "| `{}` | {} | {} | {} | {} |",
                truncate_path(name, 30),
                module.trait_impl_count,
                module.inherent_impl_count,
                module.internal_deps.len(),
                module.external_deps.len()
            )?;
        }
    }

    if modules.len() > 20 {
        writeln!(writer, "\n*Showing top 20 of {} modules*", modules.len())?;
    }
    writeln!(writer)?;

    Ok(())
}

fn write_volatility_section<W: Write>(metrics: &ProjectMetrics, writer: &mut W) -> io::Result<()> {
    writeln!(writer, "## Volatility Analysis\n")?;

    if metrics.file_changes.is_empty() {
        writeln!(
            writer,
            "*Git history analysis not available. Run in a git repository for volatility data.*\n"
        )?;
        return Ok(());
    }

    let mut high_vol: Vec<_> = metrics
        .file_changes
        .iter()
        .filter(|&(_, count)| *count > 10)
        .collect();

    high_vol.sort_by(|a, b| b.1.cmp(a.1));

    if high_vol.is_empty() {
        writeln!(
            writer,
            "No high volatility files detected (threshold: >10 changes).\n"
        )?;
    } else {
        writeln!(writer, "### High Volatility Files\n")?;
        writeln!(
            writer,
            "⚠️ Strong coupling to these files increases cascading change risk.\n"
        )?;
        writeln!(writer, "| File | Changes |")?;
        writeln!(writer, "|------|---------|")?;
        for (file, count) in high_vol.iter().take(10) {
            writeln!(writer, "| `{}` | {} |", file, count)?;
        }
        writeln!(writer)?;
    }

    Ok(())
}

fn write_temporal_coupling_section<W: Write>(
    metrics: &ProjectMetrics,
    show_all: bool,
    writer: &mut W,
) -> io::Result<()> {
    if metrics.temporal_couplings.is_empty() {
        return Ok(());
    }

    let mut strong: Vec<_> = metrics
        .temporal_couplings
        .iter()
        .filter(|tc| tc.is_strong())
        .collect();
    strong.sort_by(|a, b| {
        b.coupling_ratio
            .partial_cmp(&a.coupling_ratio)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    if !show_all && strong.is_empty() {
        return Ok(());
    }

    writeln!(writer, "## Temporal Coupling (Co-Change Analysis)\n")?;
    writeln!(
        writer,
        "Files that frequently change together in git commits, indicating implicit coupling"
    )?;
    writeln!(writer, "beyond what code structure reveals.\n")?;

    if !strong.is_empty() {
        writeln!(
            writer,
            "### Strong Temporal Coupling (>50% co-change ratio)\n"
        )?;
        writeln!(
            writer,
            "⚠️ These pairs may share implicit knowledge (business logic, assumptions, data formats).\n"
        )?;
        writeln!(writer, "| File A | File B | Co-changes | Ratio |")?;
        writeln!(writer, "|--------|--------|------------|-------|")?;
        let strong_limit = if show_all {
            strong.len()
        } else {
            DEFAULT_STRONG_TEMPORAL_LIMIT
        };
        for tc in strong.iter().take(strong_limit) {
            writeln!(
                writer,
                "| `{}` | `{}` | {} | {:.0}% |",
                tc.file_a,
                tc.file_b,
                tc.co_change_count,
                tc.coupling_ratio * 100.0
            )?;
        }
        if !show_all && strong.len() > strong_limit {
            writeln!(
                writer,
                "\n*... and {} more (use --all)*",
                strong.len() - strong_limit
            )?;
        }
        writeln!(writer)?;
    }

    if !show_all {
        return Ok(());
    }

    let moderate: Vec<_> = metrics
        .temporal_couplings
        .iter()
        .filter(|tc| !tc.is_strong())
        .collect();

    if !moderate.is_empty() {
        writeln!(writer, "### Moderate Temporal Coupling\n")?;
        writeln!(writer, "| File A | File B | Co-changes | Ratio |")?;
        writeln!(writer, "|--------|--------|------------|-------|")?;
        for tc in moderate {
            writeln!(
                writer,
                "| `{}` | `{}` | {} | {:.0}% |",
                tc.file_a,
                tc.file_b,
                tc.co_change_count,
                tc.coupling_ratio * 100.0
            )?;
        }
        writeln!(writer)?;
    }

    Ok(())
}

fn write_circular_dependencies_section<W: Write>(
    metrics: &ProjectMetrics,
    writer: &mut W,
) -> io::Result<()> {
    let summary = metrics.circular_dependency_summary();

    if summary.total_cycles == 0 {
        writeln!(writer, "## Circular Dependencies\n")?;
        writeln!(writer, "✅ No circular dependencies detected.\n")?;
        return Ok(());
    }

    writeln!(writer, "## ⚠️ Circular Dependencies\n")?;
    writeln!(
        writer,
        "Found **{} circular dependency cycle(s)** involving **{} modules**.\n",
        summary.total_cycles, summary.affected_modules
    )?;

    writeln!(
        writer,
        "Circular dependencies make code harder to understand, test, and maintain."
    )?;
    writeln!(writer, "Consider breaking cycles by:\n")?;
    writeln!(writer, "1. Extracting shared types into a separate module")?;
    writeln!(writer, "2. Inverting dependencies using traits/interfaces")?;
    writeln!(writer, "3. Moving functionality to reduce coupling\n")?;

    writeln!(writer, "### Detected Cycles\n")?;

    for (i, cycle) in summary.cycles.iter().take(10).enumerate() {
        let cycle_str = cycle.join("");
        writeln!(
            writer,
            "{}. `{}` → `{}`",
            i + 1,
            cycle_str,
            cycle.first().unwrap_or(&"?".to_string())
        )?;
    }

    if summary.cycles.len() > 10 {
        writeln!(
            writer,
            "\n*...and {} more cycles*",
            summary.cycles.len() - 10
        )?;
    }
    writeln!(writer)?;

    Ok(())
}

fn write_best_practices<W: Write>(writer: &mut W) -> io::Result<()> {
    writeln!(writer, "## Balance Guidelines\n")?;

    writeln!(
        writer,
        "The goal is **balanced coupling**, not zero coupling.\n"
    )?;

    writeln!(writer, "### Ideal Patterns ✅\n")?;
    writeln!(writer, "| Pattern | Example | Why It Works |")?;
    writeln!(writer, "|---------|---------|--------------|")?;
    writeln!(
        writer,
        "| Strong + Close | `impl` blocks in same module | Cohesion within boundaries |"
    )?;
    writeln!(
        writer,
        "| Weak + Far | Trait impl for external crate | Loose coupling across boundaries |"
    )?;
    writeln!(writer)?;

    writeln!(writer, "### Problematic Patterns ❌\n")?;
    writeln!(writer, "| Pattern | Problem | Solution |")?;
    writeln!(writer, "|---------|---------|----------|")?;
    writeln!(
        writer,
        "| Strong + Far | Global complexity | Introduce adapter or move closer |"
    )?;
    writeln!(
        writer,
        "| Strong + Volatile | Cascading changes | Add stable interface |"
    )?;
    writeln!(
        writer,
        "| Intrusive + Cross-boundary | Encapsulation violation | Extract trait API |"
    )?;
    writeln!(writer)?;

    Ok(())
}

fn truncate_path(path: &str, max_len: usize) -> String {
    if path.len() <= max_len {
        path.to_string()
    } else {
        format!("...{}", &path[path.len() - max_len + 3..])
    }
}

fn truncate_chars(text: &str, max_chars: usize) -> String {
    if text.chars().count() <= max_chars {
        text.to_string()
    } else {
        let prefix: String = text.chars().take(max_chars).collect();
        format!("{}...", prefix)
    }
}

// ===== AI-Oriented Report =====

/// Generate AI-friendly output format for coding agents
///
/// This format is designed to be:
/// 1. Concise and structured for LLM consumption
/// 2. Actionable with specific file/module references
/// 3. Copy-paste ready for AI refactoring prompts
pub fn generate_ai_output<W: Write>(metrics: &ProjectMetrics, writer: &mut W) -> io::Result<()> {
    let manifest = default_manifest();
    generate_ai_output_with_thresholds(metrics, &IssueThresholds::default(), &manifest, writer)
}

/// Generate AI-friendly output with custom thresholds
pub fn generate_ai_output_with_thresholds<W: Write>(
    metrics: &ProjectMetrics,
    thresholds: &IssueThresholds,
    manifest: &AnalysisManifest,
    writer: &mut W,
) -> io::Result<()> {
    let report = analyze_project_balance_with_thresholds(metrics, thresholds);

    let project_name = metrics.workspace_name.as_deref().unwrap_or("project");
    writeln!(writer, "Coupling Issues in {}:", project_name)?;
    writeln!(
        writer,
        "────────────────────────────────────────────────────────────"
    )?;
    writeln!(writer)?;

    // Summary line
    writeln!(
        writer,
        "Grade: {} | Score: {:.2} | Issues: {} High, {} Medium",
        report.health_grade,
        report.average_score,
        report.issues_by_severity.get(&Severity::High).unwrap_or(&0),
        report
            .issues_by_severity
            .get(&Severity::Medium)
            .unwrap_or(&0)
    )?;
    writeln!(writer, "Why this grade: {}", report.grade_rationale.summary)?;
    writeln!(writer)?;

    // List issues in a structured format
    if report.issues.is_empty() {
        writeln!(writer, "✅ No coupling issues detected.")?;
        writeln!(writer)?;
    } else {
        writeln!(writer, "Issues:")?;
        writeln!(writer)?;

        for (i, issue) in report.issues.iter().take(10).enumerate() {
            let severity_marker = match issue.severity {
                Severity::Critical => "🔴",
                Severity::High => "🟠",
                Severity::Medium => "🟡",
                Severity::Low => "",
            };

            writeln!(
                writer,
                "{}. {} {}{}",
                i + 1,
                severity_marker,
                issue.source,
                issue.target
            )?;
            writeln!(writer, "   Type: {}", issue.issue_type)?;
            writeln!(writer, "   Problem: {}", issue.description)?;
            writeln!(writer, "   Fix: {}", issue.refactoring)?;
            writeln!(writer)?;
        }

        if report.issues.len() > 10 {
            writeln!(writer, "... and {} more issues", report.issues.len() - 10)?;
            writeln!(writer)?;
        }
    }

    // Circular dependencies (critical for AI to understand)
    let circular = metrics.circular_dependency_summary();
    if circular.total_cycles > 0 {
        writeln!(
            writer,
            "Circular Dependencies ({} cycles):",
            circular.total_cycles
        )?;
        for cycle in circular.cycles.iter().take(5) {
            writeln!(
                writer,
                "  {}{}",
                cycle.join(""),
                cycle.first().unwrap_or(&"?".to_string())
            )?;
        }
        writeln!(writer)?;
    }

    // Temporal coupling (important for AI to understand implicit dependencies)
    let strong_temporal: Vec<_> = metrics
        .temporal_couplings
        .iter()
        .filter(|tc| tc.is_strong())
        .collect();
    if !strong_temporal.is_empty() {
        writeln!(writer, "Temporal Coupling (implicit dependencies):")?;
        for tc in strong_temporal.iter().take(5) {
            writeln!(
                writer,
                "  {}{} ({} co-changes, {:.0}% ratio)",
                tc.file_a,
                tc.file_b,
                tc.co_change_count,
                tc.coupling_ratio * 100.0
            )?;
        }
        writeln!(writer)?;
    }

    // only show ai refactor advice if there is something to refactor
    if !report.issues.is_empty() || circular.total_cycles > 0 {
        writeln!(
            writer,
            "────────────────────────────────────────────────────────────"
        )?;
        writeln!(writer)?;

        // AI prompt suggestion
        writeln!(
            writer,
            "💡 To refactor with AI, copy this output and use this prompt:"
        )?;
        writeln!(writer)?;
        writeln!(writer, "```")?;
        writeln!(
            writer,
            "Analyze the coupling issues above from `cargo coupling --ai`. "
        )?;
        writeln!(
            writer,
            "For each issue, suggest specific code changes to reduce coupling."
        )?;
        writeln!(
            writer,
            "Focus on introducing traits, moving code closer, or breaking circular dependencies."
        )?;
        writeln!(writer, "```")?;
    }

    write_manifest_summary_section(manifest, false, true, writer)?;

    Ok(())
}

fn default_manifest() -> AnalysisManifest {
    build_manifest(&ManifestContext {
        git_used: true,
        tests_excluded: false,
        parse_failures: 0,
        skipped_crates: Vec::new(),
        boundary_skipped_files: 0,
        dead_config_patterns: Vec::new(),
    })
}

fn write_manifest_markdown_section<W: Write>(
    manifest: &AnalysisManifest,
    show_structural_blind_spots: bool,
    japanese: bool,
    writer: &mut W,
) -> io::Result<()> {
    if japanese {
        writeln!(writer, "## 未分析範囲\n")?;
    } else {
        writeln!(writer, "## Not Analyzed (blind spots)\n")?;
    }

    if show_structural_blind_spots {
        for blind_spot in &manifest.blind_spots {
            let description = if japanese {
                blind_spot.description_ja
            } else {
                blind_spot.description
            };
            writeln!(writer, "- **{}**: {}", blind_spot.area, description)?;
        }
    }

    let notes = manifest.localized_notes(japanese);
    if !notes.is_empty() {
        if show_structural_blind_spots {
            writeln!(writer)?;
        }
        if japanese {
            writeln!(writer, "実行時の注意:")?;
        } else {
            writeln!(writer, "Run-specific notes:")?;
        }
        for note in notes {
            writeln!(writer, "- {}", note)?;
        }
    }

    if !show_structural_blind_spots {
        if !notes.is_empty() {
            writeln!(writer)?;
        }
        if japanese {
            writeln!(
                writer,
                "{} 件の構造的な未分析範囲があります。詳細は --blind-spots (または --json) で確認できます。",
                manifest.blind_spots.len()
            )?;
        } else {
            writeln!(
                writer,
                "{} structural blind spots not analyzed — see --blind-spots (or --json).",
                manifest.blind_spots.len()
            )?;
        }
    }

    writeln!(writer)?;
    Ok(())
}

fn write_manifest_summary_section<W: Write>(
    manifest: &AnalysisManifest,
    japanese: bool,
    show_structural_blind_spots: bool,
    writer: &mut W,
) -> io::Result<()> {
    if japanese {
        writeln!(writer, "未分析範囲:")?;
    } else {
        writeln!(writer, "Not Analyzed (blind spots):")?;
    }

    if show_structural_blind_spots {
        for blind_spot in &manifest.blind_spots {
            let description = if japanese {
                blind_spot.description_ja
            } else {
                blind_spot.description
            };
            writeln!(writer, "  - {}: {}", blind_spot.area, description)?;
        }
    }

    let notes = manifest.localized_notes(japanese);
    if !notes.is_empty() {
        if japanese {
            writeln!(writer, "実行時の注意:")?;
        } else {
            writeln!(writer, "Run-specific notes:")?;
        }
        for note in notes {
            writeln!(writer, "  - {}", note)?;
        }
    }

    if !show_structural_blind_spots {
        if japanese {
            writeln!(
                writer,
                "{} 件の構造的な未分析範囲があります。詳細は --blind-spots (または --json) で確認できます。",
                manifest.blind_spots.len()
            )?;
        } else {
            writeln!(
                writer,
                "{} structural blind spots not analyzed — see --blind-spots (or --json).",
                manifest.blind_spots.len()
            )?;
        }
    }

    writeln!(writer)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::manifest::{ManifestContext, build_manifest};
    use std::path::PathBuf;

    #[test]
    fn test_generate_summary() {
        let metrics = ProjectMetrics::new();
        let mut output = Vec::new();

        let result = generate_summary(&metrics, &mut output);
        assert!(result.is_ok());

        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("Balanced Coupling Analysis"));
        assert!(output_str.contains("Grade:"));
        assert!(output_str.contains("Why this grade:"));
    }

    #[test]
    fn test_generate_report() {
        let metrics = ProjectMetrics::new();
        let mut output = Vec::new();

        let result = generate_report(&metrics, &mut output);
        assert!(result.is_ok());

        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("# Coupling Analysis Report"));
        assert!(output_str.contains("Executive Summary"));
        assert!(output_str.contains("**Why this grade**:"));
        assert!(output_str.contains("## Not Analyzed (blind spots)"));
        assert!(output_str.contains("4 structural blind spots not analyzed"));
        assert!(!output_str.contains("Dynamic connascence (Execution"));
    }

    #[test]
    fn test_generate_summary_includes_manifest_notes_and_pointer() {
        let metrics = ProjectMetrics::new();
        let thresholds = IssueThresholds::default();
        let manifest = build_manifest(&ManifestContext {
            git_used: false,
            tests_excluded: true,
            parse_failures: 0,
            skipped_crates: Vec::new(),
            boundary_skipped_files: 0,
            dead_config_patterns: Vec::new(),
        });
        let mut output = Vec::new();

        let result =
            generate_summary_with_thresholds(&metrics, &thresholds, &manifest, &mut output);
        assert!(result.is_ok());

        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("Not Analyzed (blind spots):"));
        assert!(output_str.contains("4 structural blind spots not analyzed"));
        assert!(!output_str.contains("Dynamic connascence (Execution"));
        assert!(output_str.contains("Git history was not analyzed"));
        assert!(output_str.contains("Test code was excluded"));
    }

    #[test]
    fn test_text_report_blind_spots_are_opt_in() {
        let metrics = ProjectMetrics::new();
        let thresholds = IssueThresholds::default();
        let manifest = build_manifest(&ManifestContext {
            git_used: false,
            tests_excluded: true,
            parse_failures: 1,
            skipped_crates: Vec::new(),
            boundary_skipped_files: 0,
            dead_config_patterns: Vec::new(),
        });

        let mut default_output = Vec::new();
        generate_report_with_options(
            &metrics,
            &thresholds,
            &manifest,
            TextReportOptions::default(),
            &mut default_output,
        )
        .unwrap();
        let default_text = String::from_utf8(default_output).unwrap();
        assert!(default_text.contains("4 structural blind spots not analyzed"));
        assert!(default_text.contains("Git history was not analyzed"));
        assert!(default_text.contains("Test code was excluded"));
        assert!(default_text.contains("1 source file(s) failed to parse"));
        assert!(!default_text.contains("Dynamic connascence (Execution"));

        for options in [
            TextReportOptions {
                show_structural_blind_spots: true,
                show_all_temporal_couplings: false,
            },
            TextReportOptions {
                show_structural_blind_spots: true,
                show_all_temporal_couplings: true,
            },
        ] {
            let mut output = Vec::new();
            generate_report_with_options(&metrics, &thresholds, &manifest, options, &mut output)
                .unwrap();
            let text = String::from_utf8(output).unwrap();
            assert!(text.contains("dynamic-connascence"));
            assert!(text.contains("Dynamic connascence (Execution"));
        }
    }

    #[test]
    fn test_text_report_temporal_coupling_default_truncates_strong_pairs() {
        use crate::volatility::TemporalCoupling;

        let mut metrics = ProjectMetrics::new();
        metrics.temporal_couplings = (0..7)
            .map(|i| TemporalCoupling {
                file_a: format!("src/a{}.rs", i),
                file_b: format!("src/b{}.rs", i),
                co_change_count: i + 1,
                coupling_ratio: 0.95 - (i as f64 * 0.05),
            })
            .collect();
        metrics.temporal_couplings.push(TemporalCoupling {
            file_a: "src/moderate_a.rs".to_string(),
            file_b: "src/moderate_b.rs".to_string(),
            co_change_count: 2,
            coupling_ratio: 0.4,
        });

        let manifest = default_manifest();
        let thresholds = IssueThresholds::default();
        let mut output = Vec::new();
        generate_report_with_options(
            &metrics,
            &thresholds,
            &manifest,
            TextReportOptions::default(),
            &mut output,
        )
        .unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains("src/a0.rs"));
        assert!(text.contains("src/a4.rs"));
        assert!(!text.contains("src/a5.rs"));
        assert!(!text.contains("src/moderate_a.rs"));
        assert!(text.contains("... and 2 more (use --all)"));

        let mut all_output = Vec::new();
        generate_report_with_options(
            &metrics,
            &thresholds,
            &manifest,
            TextReportOptions {
                show_structural_blind_spots: false,
                show_all_temporal_couplings: true,
            },
            &mut all_output,
        )
        .unwrap();
        let all_text = String::from_utf8(all_output).unwrap();
        assert!(all_text.contains("src/a6.rs"));
        assert!(all_text.contains("src/moderate_a.rs"));
    }

    #[test]
    fn test_report_issues_surfaced_count_matches_issue_list() {
        use crate::balance::project::analyze_project_balance_with_thresholds;
        use crate::metrics::coupling::CouplingMetrics;
        use crate::metrics::dimensions::{Distance, IntegrationStrength};
        use crate::volatility::Volatility;

        let mut metrics = ProjectMetrics::new();
        metrics.add_coupling(CouplingMetrics::new(
            "source".to_string(),
            "target".to_string(),
            IntegrationStrength::Intrusive,
            Distance::DifferentModule,
            Volatility::High,
        ));

        let thresholds = IssueThresholds::default();
        let report = analyze_project_balance_with_thresholds(&metrics, &thresholds);
        let mut output = Vec::new();
        generate_report_with_options(
            &metrics,
            &thresholds,
            &default_manifest(),
            TextReportOptions::default(),
            &mut output,
        )
        .unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains(&format!("| Issues Surfaced | {} |", report.issues.len())));
    }

    #[test]
    fn test_generate_ai_output_includes_manifest() {
        let metrics = ProjectMetrics::new();
        let manifest = build_manifest(&ManifestContext {
            git_used: false,
            tests_excluded: false,
            parse_failures: 0,
            skipped_crates: Vec::new(),
            boundary_skipped_files: 0,
            dead_config_patterns: Vec::new(),
        });
        let mut output = Vec::new();

        let result = generate_ai_output_with_thresholds(
            &metrics,
            &IssueThresholds::default(),
            &manifest,
            &mut output,
        );
        assert!(result.is_ok());

        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("Not Analyzed (blind spots):"));
        assert!(output_str.contains("macro-and-cfg"));
        assert!(output_str.contains("Git history was not analyzed"));
    }

    #[test]
    fn test_generate_report_with_modules() {
        use crate::metrics::module::ModuleMetrics;

        let mut metrics = ProjectMetrics::new();
        let mut module = ModuleMetrics::new(PathBuf::from("lib.rs"), "lib".to_string());
        module.trait_impl_count = 3;
        module.inherent_impl_count = 2;
        metrics.add_module(module);

        let mut output = Vec::new();
        let result = generate_report(&metrics, &mut output);
        assert!(result.is_ok());

        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("Module Statistics"));
    }

    #[test]
    fn test_generate_report_surfaces_subdomain_when_present() {
        use crate::config::Subdomain;
        use crate::metrics::module::ModuleMetrics;

        let mut metrics = ProjectMetrics::new();
        let mut module = ModuleMetrics::new(PathBuf::from("src/report.rs"), "report".to_string());
        module.subdomain = Some(Subdomain::Supporting);
        metrics.add_module(module);

        let mut output = Vec::new();
        generate_report(&metrics, &mut output).unwrap();

        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("| Module | Subdomain |"));
        assert!(output_str.contains("| `report` | Supporting |"));
    }

    #[test]
    fn test_truncate_path() {
        assert_eq!(truncate_path("short", 10), "short");
        assert_eq!(
            truncate_path("this_is_a_very_long_path", 15),
            "...ry_long_path"
        );
    }
}