jscycles 0.2.0

Find circular imports between files and workspace packages in JavaScript and TypeScript projects
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
//! Output formatting for cycle detection results.
//!
//! Provides human-readable and JSON output formats for both file-level
//! and package-level cycle detection results.

use std::io::Write;
use std::path::PathBuf;

use serde::Serialize;

use crate::cycles::{Cycle, PackageCycle, PackageCycleWithFiles};
use crate::terminal::label;

/// A cycle member relative to its package, or, outside it (a link target),
/// absolute without the Windows verbatim `\\?\` prefix of canonical paths.
fn display_path(path: &std::path::Path, base_path: &std::path::Path) -> PathBuf {
    path.strip_prefix(base_path).map_or_else(
        |_| crate::input::absolute_form(path),
        std::path::Path::to_path_buf,
    )
}

/// Results for a single package.
#[derive(Debug, Clone)]
pub struct PackageResult {
    /// Package name.
    pub name: String,

    /// Package path.
    pub path: PathBuf,

    /// Detected cycles.
    pub cycles: Vec<Cycle>,
}

/// Aggregated results for all packages.
#[derive(Debug, Clone)]
pub struct Results {
    /// Per-package results.
    pub packages: Vec<PackageResult>,
}

impl Results {
    /// Create empty results.
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self {
            packages: Vec::new(),
        }
    }

    /// Check if any cycles were found.
    #[inline]
    #[must_use]
    pub fn has_cycles(&self) -> bool {
        self.packages.iter().any(|p| !p.cycles.is_empty())
    }

    /// Get total number of cycles across all packages.
    #[inline]
    #[must_use]
    pub fn total_cycles(&self) -> usize {
        self.packages.iter().map(|p| p.cycles.len()).sum()
    }

    /// Get number of packages with cycles.
    #[inline]
    #[must_use]
    pub fn packages_with_cycles(&self) -> usize {
        self.packages
            .iter()
            .filter(|p| !p.cycles.is_empty())
            .count()
    }
}

impl Default for Results {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Filter for which types of cycles to display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CycleFilter {
    /// Show all cycles (default).
    #[default]
    All,
    /// Show only file-level (inner) cycles.
    Inner,
    /// Show only package-level (outer) cycles.
    Outer,
}

/// Unified results including both file-level and package-level cycles.
#[derive(Debug, Clone, Default)]
pub struct UnifiedResults {
    /// Per-package file-level results.
    pub file_results: Vec<PackageResult>,

    /// Package-level cycles (between packages).
    pub package_cycles: Vec<PackageCycle>,

    /// Package-level cycles with file detail (optional, for verbose output).
    pub package_cycles_with_files: Vec<PackageCycleWithFiles>,
}

impl UnifiedResults {
    /// Create empty unified results.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if any file-level cycles were found.
    #[inline]
    #[must_use]
    pub fn has_file_cycles(&self) -> bool {
        self.file_results.iter().any(|p| !p.cycles.is_empty())
    }

    /// Check if any package-level cycles were found.
    #[inline]
    #[must_use]
    pub const fn has_package_cycles(&self) -> bool {
        !self.package_cycles.is_empty() || !self.package_cycles_with_files.is_empty()
    }

    /// Check if any cycles were found (file or package level).
    #[inline]
    #[must_use]
    pub fn has_any_cycles(&self) -> bool {
        self.has_file_cycles() || self.has_package_cycles()
    }

    /// Get total number of file-level cycles.
    #[inline]
    #[must_use]
    pub fn total_file_cycles(&self) -> usize {
        self.file_results.iter().map(|p| p.cycles.len()).sum()
    }

    /// Get number of packages with file-level cycles.
    #[inline]
    #[must_use]
    pub fn packages_with_cycles(&self) -> usize {
        self.file_results
            .iter()
            .filter(|p| !p.cycles.is_empty())
            .count()
    }
}

/// Trait for output formatters.
pub trait OutputFormatter {
    /// Format results to the given writer.
    ///
    /// # Errors
    ///
    /// Returns an IO error if writing fails.
    fn format(&self, results: &Results, writer: &mut dyn Write) -> std::io::Result<()>;
}

/// Trait for unified output formatters (file + package cycles).
pub trait UnifiedOutputFormatter {
    /// Format unified results to the given writer.
    ///
    /// # Errors
    ///
    /// Returns an IO error if writing fails.
    fn format_unified(
        &self,
        results: &UnifiedResults,
        filter: CycleFilter,
        writer: &mut dyn Write,
    ) -> std::io::Result<()>;
}

/// Human-readable output formatter.
#[derive(Debug, Default)]
pub struct HumanFormatter {
    /// Whether to use colors (for TTY output).
    pub use_color: bool,
    /// Whether to show verbose output (including clean packages).
    pub verbose: bool,
}

impl HumanFormatter {
    /// Escape untrusted text for a human-readable label, preserving ordinary
    /// Unicode and exposing controls, bidi controls and Unicode line separators.
    /// This is a display representation; retain the original text for paths,
    /// identity comparisons and machine-readable reports.
    #[must_use]
    pub fn escape_label(text: &str) -> String {
        label(text)
    }

    /// Create a new human formatter.
    #[inline]
    #[must_use]
    pub const fn new(use_color: bool) -> Self {
        Self {
            use_color,
            verbose: false,
        }
    }

    /// Set verbose mode (show clean packages).
    #[inline]
    #[must_use]
    pub const fn with_verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Format a cycle path as a string.
    fn format_cycle(cycle: &Cycle, base_path: &std::path::Path) -> String {
        cycle
            .path
            .iter()
            .map(|p| label(&display_path(p, base_path).to_string_lossy()))
            .collect::<Vec<_>>()
            .join(" -> ")
    }

    /// Format a single package result.
    /// Returns Ok(true) if something was written, Ok(false) if skipped.
    fn format_package(
        &self,
        package: &PackageResult,
        writer: &mut dyn Write,
    ) -> std::io::Result<bool> {
        if package.cycles.is_empty() {
            if self.verbose {
                self.format_clean_package(package, writer)?;
                return Ok(true);
            }
            return Ok(false);
        }
        self.format_cyclic_package(package, writer)?;
        Ok(true)
    }

    /// Format a package with no cycles.
    fn format_clean_package(
        &self,
        package: &PackageResult,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        if self.use_color {
            writeln!(
                writer,
                "\x1b[32m✓\x1b[0m {}: no cycles",
                label(&package.name)
            )
        } else {
            writeln!(writer, "✓ {}: no cycles", label(&package.name))
        }
    }

    /// Format a package with cycles.
    fn format_cyclic_package(
        &self,
        package: &PackageResult,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        let cycle_word = if package.cycles.len() == 1 {
            "cycle"
        } else {
            "cycles"
        };
        let name = label(&package.name);
        let count = package.cycles.len();

        if self.use_color {
            writeln!(writer, "\x1b[31m✗\x1b[0m {name}: {count} {cycle_word}")?;
        } else {
            writeln!(writer, "✗ {name}: {count} {cycle_word}")?;
        }

        for cycle in &package.cycles {
            let formatted = Self::format_cycle(cycle, &package.path);
            writeln!(writer, "  {formatted}")?;
        }

        Ok(())
    }

    /// Format the summary line.
    fn format_summary(results: &Results, writer: &mut dyn Write) -> std::io::Result<()> {
        let total = results.packages.len();
        let with_cycles = results.packages_with_cycles();
        let total_cycles = results.total_cycles();

        let packages = counted(total, "package", "packages");
        let cycles = counted(total_cycles, "total cycle", "total cycles");
        writeln!(
            writer,
            "Summary: {packages} checked, {with_cycles} with cycles, {cycles}"
        )
    }

    /// Format the package-level cycles section.
    fn format_package_cycles_section(
        &self,
        results: &UnifiedResults,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        // Use detailed cycles if available, otherwise fall back to basic
        if !results.package_cycles_with_files.is_empty() {
            return self.format_package_cycles_with_files(results, writer);
        }

        if results.package_cycles.is_empty() {
            if self.use_color {
                writeln!(writer, "\x1b[32m✓\x1b[0m No inter-package cycles")?;
            } else {
                writeln!(writer, "✓ No inter-package cycles")?;
            }
        } else {
            let count = results.package_cycles.len();
            let cycle_word = if count == 1 { "cycle" } else { "cycles" };
            if self.use_color {
                writeln!(
                    writer,
                    "\x1b[31m✗\x1b[0m {count} inter-package {cycle_word}"
                )?;
            } else {
                writeln!(writer, "✗ {count} inter-package {cycle_word}")?;
            }
            for cycle in &results.package_cycles {
                let formatted = cycle
                    .packages
                    .iter()
                    .map(|name| label(name))
                    .collect::<Vec<_>>()
                    .join(" -> ");
                writeln!(writer, "  {formatted}")?;
            }
        }
        writeln!(writer)
    }

    /// Format package cycles with file-level detail.
    fn format_package_cycles_with_files(
        &self,
        results: &UnifiedResults,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        let count = results.package_cycles_with_files.len();
        if count == 0 {
            if self.use_color {
                writeln!(writer, "\x1b[32m✓\x1b[0m No inter-package cycles")?;
            } else {
                writeln!(writer, "✓ No inter-package cycles")?;
            }
            return writeln!(writer);
        }

        let cycle_word = if count == 1 { "cycle" } else { "cycles" };
        if self.use_color {
            writeln!(
                writer,
                "\x1b[31m✗\x1b[0m {count} inter-package {cycle_word}"
            )?;
        } else {
            writeln!(writer, "✗ {count} inter-package {cycle_word}")?;
        }

        for cycle in &results.package_cycles_with_files {
            Self::format_single_cycle_with_files(cycle, writer)?;
        }

        writeln!(writer)
    }

    /// Format a single cycle with file-level detail.
    fn format_single_cycle_with_files(
        cycle: &PackageCycleWithFiles,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        // Print the cycle summary
        let formatted = cycle
            .packages
            .iter()
            .map(|name| label(name))
            .collect::<Vec<_>>()
            .join(" -> ");
        writeln!(writer, "\n  {formatted}")?;

        // Print file details for each edge
        for edge in &cycle.edges {
            Self::format_cycle_edge(edge, writer)?;
        }

        Ok(())
    }

    /// Format a single edge in a cycle.
    fn format_cycle_edge(
        edge: &crate::cycles::PackageCycleEdge,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        writeln!(
            writer,
            "    {} -> {}",
            label(&edge.from_package),
            label(&edge.to_package)
        )?;
        for (file, subpath) in &edge.files {
            Self::format_edge_file(file, &edge.to_package, subpath.as_deref(), writer)?;
        }
        Ok(())
    }

    /// Format a single file in an edge.
    fn format_edge_file(
        file: &std::path::Path,
        package: &str,
        subpath: Option<&str>,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        let file_display = label(&file.to_string_lossy());
        if let Some(subpath_value) = subpath {
            let target = label(&format!("{package}/{subpath_value}"));
            writeln!(writer, "      - {file_display} (imports {target})")
        } else {
            writeln!(writer, "      - {file_display}")
        }
    }

    /// Format the file-level cycles section.
    fn format_file_cycles_section(
        &self,
        results: &UnifiedResults,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        if results.file_results.is_empty() {
            writeln!(writer, "No packages found.")?;
            return Ok(());
        }

        for package in &results.file_results {
            let written = self.format_package(package, writer)?;
            if written {
                writeln!(writer)?;
            }
        }

        Ok(())
    }

    /// Format the unified summary line.
    fn format_unified_summary(
        results: &UnifiedResults,
        filter: CycleFilter,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        let total_pkgs = results.file_results.len();
        let with_file_cycles = results.packages_with_cycles();
        let total_file_cycles = results.total_file_cycles();
        let pkg_cycles = if results.package_cycles_with_files.is_empty() {
            results.package_cycles.len()
        } else {
            results.package_cycles_with_files.len()
        };

        let packages = counted(total_pkgs, "package", "packages");
        let package_cycles = counted(pkg_cycles, "inter-package cycle", "inter-package cycles");
        match filter {
            CycleFilter::All => writeln!(
                writer,
                "Summary: {packages}, {with_file_cycles} with file cycles \
                ({total_file_cycles} total), {package_cycles}"
            ),
            CycleFilter::Inner => writeln!(
                writer,
                "Summary: {packages}, {with_file_cycles} with file cycles \
                ({total_file_cycles} total)"
            ),
            CycleFilter::Outer => writeln!(writer, "Summary: {package_cycles}"),
        }
    }
}

/// `count` followed by the singular or plural noun.
fn counted(count: usize, singular: &str, plural: &str) -> String {
    format!("{count} {}", if count == 1 { singular } else { plural })
}

impl OutputFormatter for HumanFormatter {
    fn format(&self, results: &Results, writer: &mut dyn Write) -> std::io::Result<()> {
        if results.packages.is_empty() {
            writeln!(writer, "No packages found.")?;
            return Ok(());
        }

        for package in &results.packages {
            let written = self.format_package(package, writer)?;
            if written {
                writeln!(writer)?;
            }
        }

        Self::format_summary(results, writer)
    }
}

impl UnifiedOutputFormatter for HumanFormatter {
    fn format_unified(
        &self,
        results: &UnifiedResults,
        filter: CycleFilter,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        let show_file = matches!(filter, CycleFilter::All | CycleFilter::Inner);
        let show_package = matches!(filter, CycleFilter::All | CycleFilter::Outer);

        // Package-level cycles section
        if show_package {
            self.format_package_cycles_section(results, writer)?;
        }

        // File-level cycles section
        if show_file {
            self.format_file_cycles_section(results, writer)?;
        }

        // Summary
        Self::format_unified_summary(results, filter, writer)
    }
}

/// JSON output formatter.
#[derive(Debug, Default)]
pub struct JsonFormatter;

/// JSON output structure.
#[derive(Debug, Serialize)]
struct JsonOutput {
    /// Whether any cycles were found.
    has_cycles: bool,

    /// Cycles per package.
    packages: Vec<JsonPackage>,
}

/// JSON package structure.
#[derive(Debug, Serialize)]
struct JsonPackage {
    /// Package name.
    name: String,

    /// Package path.
    path: String,

    /// Detected cycles.
    cycles: Vec<Vec<String>>,
}

impl JsonFormatter {
    /// Create a new JSON formatter.
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self
    }

    /// Convert a package result to JSON format.
    fn convert_package(package: &PackageResult) -> JsonPackage {
        let cycles: Vec<Vec<String>> = package
            .cycles
            .iter()
            .map(|c| Self::convert_cycle(c, &package.path))
            .collect();

        JsonPackage {
            name: package.name.clone(),
            path: package.path.to_string_lossy().to_string(),
            cycles,
        }
    }

    /// Convert a cycle to relative path strings.
    fn convert_cycle(cycle: &Cycle, base_path: &std::path::Path) -> Vec<String> {
        cycle
            .path
            .iter()
            .map(|path| display_path(path, base_path).to_string_lossy().into_owned())
            .collect()
    }

    /// Convert a package cycle with files to JSON format.
    fn convert_cycle_with_files(cycle: &PackageCycleWithFiles) -> JsonPackageCycleWithFiles {
        let edges = cycle
            .edges
            .iter()
            .map(|edge| JsonPackageCycleEdge {
                from_package: edge.from_package.clone(),
                to_package: edge.to_package.clone(),
                files: edge
                    .files
                    .iter()
                    .map(|(path, subpath)| JsonEdgeFile {
                        path: path.to_string_lossy().to_string(),
                        subpath: subpath.clone(),
                    })
                    .collect(),
            })
            .collect();

        JsonPackageCycleWithFiles {
            packages: cycle.packages.clone(),
            edges,
        }
    }

    /// Convert a basic package cycle to JSON format (no file detail).
    fn convert_basic_cycle(cycle: &PackageCycle) -> JsonPackageCycleWithFiles {
        // Create edges without file evidence
        let mut edges = Vec::new();
        for window in cycle.packages.windows(2) {
            let (Some(from), Some(to)) = (window.first(), window.get(1)) else {
                continue;
            };
            edges.push(JsonPackageCycleEdge {
                from_package: from.clone(),
                to_package: to.clone(),
                files: Vec::new(),
            });
        }

        JsonPackageCycleWithFiles {
            packages: cycle.packages.clone(),
            edges,
        }
    }
}

impl OutputFormatter for JsonFormatter {
    fn format(&self, results: &Results, writer: &mut dyn Write) -> std::io::Result<()> {
        let packages: Vec<JsonPackage> =
            results.packages.iter().map(Self::convert_package).collect();

        let output = JsonOutput {
            has_cycles: results.has_cycles(),
            packages,
        };

        serde_json::to_writer_pretty(&mut *writer, &output).map_err(std::io::Error::other)?;
        writeln!(writer)?;
        Ok(())
    }
}

/// JSON edge with file detail.
#[derive(Debug, Serialize)]
struct JsonPackageCycleEdge {
    /// Source package.
    from_package: String,

    /// Target package.
    to_package: String,

    /// Files creating this edge.
    files: Vec<JsonEdgeFile>,
}

/// JSON file in an edge.
#[derive(Debug, Serialize)]
struct JsonEdgeFile {
    /// Path to the source file.
    path: String,

    /// Optional subpath being imported.
    #[serde(skip_serializing_if = "Option::is_none")]
    subpath: Option<String>,
}

/// JSON package cycle with file detail.
#[derive(Debug, Serialize)]
struct JsonPackageCycleWithFiles {
    /// Packages in the cycle.
    packages: Vec<String>,

    /// Edges with file evidence.
    edges: Vec<JsonPackageCycleEdge>,
}

/// Unified JSON output structure.
#[derive(Debug, Serialize)]
#[expect(
    clippy::struct_field_names,
    reason = "JSON field names are part of API"
)]
struct JsonUnifiedOutput {
    /// Whether any cycles were found.
    has_cycles: bool,

    /// Whether any file-level cycles were found.
    has_file_cycles: bool,

    /// Whether any package-level cycles were found.
    has_package_cycles: bool,

    /// File-level cycles per package.
    file_cycles: Vec<JsonPackage>,

    /// Package-level cycles (with file detail if available).
    package_cycles: Vec<JsonPackageCycleWithFiles>,
}

impl UnifiedOutputFormatter for JsonFormatter {
    fn format_unified(
        &self,
        results: &UnifiedResults,
        filter: CycleFilter,
        writer: &mut dyn Write,
    ) -> std::io::Result<()> {
        let file_cycles: Vec<JsonPackage> = match filter {
            CycleFilter::All | CycleFilter::Inner => results
                .file_results
                .iter()
                .map(Self::convert_package)
                .collect(),
            CycleFilter::Outer => Vec::new(),
        };

        // Use detailed cycles if available, otherwise convert basic cycles
        let package_cycles: Vec<JsonPackageCycleWithFiles> = match filter {
            CycleFilter::All | CycleFilter::Outer => {
                if results.package_cycles_with_files.is_empty() {
                    results
                        .package_cycles
                        .iter()
                        .map(Self::convert_basic_cycle)
                        .collect()
                } else {
                    results
                        .package_cycles_with_files
                        .iter()
                        .map(Self::convert_cycle_with_files)
                        .collect()
                }
            },
            CycleFilter::Inner => Vec::new(),
        };

        let output = JsonUnifiedOutput {
            has_cycles: results.has_any_cycles(),
            has_file_cycles: results.has_file_cycles(),
            has_package_cycles: results.has_package_cycles(),
            file_cycles,
            package_cycles,
        };

        serde_json::to_writer_pretty(&mut *writer, &output).map_err(std::io::Error::other)?;
        writeln!(writer)?;
        Ok(())
    }
}

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

    #[test]
    fn counts_use_the_singular_only_for_one() {
        assert_eq!(counted(0, "package", "packages"), "0 packages");
        assert_eq!(counted(1, "package", "packages"), "1 package");
        assert_eq!(counted(2, "package", "packages"), "2 packages");
    }

    #[test]
    fn cycle_members_outside_the_package_are_shown_absolute_in_user_form() {
        let (base, inside, outside, shown) = if cfg!(windows) {
            (
                r"\\?\C:\repo\a",
                r"\\?\C:\repo\a\x.ts",
                r"\\?\C:\repo\lib\y.ts",
                r"C:\repo\lib\y.ts",
            )
        } else {
            (
                "/repo/a",
                "/repo/a/x.ts",
                "/repo/lib/y.ts",
                "/repo/lib/y.ts",
            )
        };
        let base = std::path::Path::new(base);
        assert_eq!(
            display_path(std::path::Path::new(inside), base),
            PathBuf::from("x.ts")
        );
        assert_eq!(
            display_path(std::path::Path::new(outside), base),
            PathBuf::from(shown)
        );
    }

    #[test]
    fn human_reports_expose_every_bidi_control_and_unicode_line_separator() {
        for character in [
            '\u{061c}', '\u{200e}', '\u{200f}', '\u{202a}', '\u{202b}', '\u{202c}', '\u{202d}',
            '\u{202e}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}', '\u{2028}', '\u{2029}',
        ] {
            let name = format!("pkg-{character}-λ");
            let mut results = Results::new();
            results.packages.push(PackageResult {
                name: name.clone(),
                path: PathBuf::from(&name),
                cycles: vec![Cycle::new(
                    ["a.ts", "b.ts", "a.ts"].map(PathBuf::from).to_vec(),
                )],
            });
            let mut output = Vec::new();
            HumanFormatter::new(false)
                .format(&results, &mut output)
                .expect("human report");
            let text = String::from_utf8(output).expect("UTF-8 report");
            assert!(
                !text.contains(character),
                "no invisible directional or line control"
            );
            assert!(
                text.contains(&character.escape_unicode().to_string()),
                "visible escape"
            );
            assert!(text.contains('λ'), "ordinary Unicode is preserved");
        }
    }

    #[test]
    fn test_empty_results() {
        let results = Results::new();
        assert!(!results.has_cycles(), "empty results should have no cycles");
        assert_eq!(
            results.total_cycles(),
            0,
            "empty results should have 0 total cycles"
        );
    }

    #[test]
    fn test_has_cycles() {
        let mut results = Results::new();
        results.packages.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("a.ts"),
                PathBuf::from("b.ts"),
                PathBuf::from("a.ts"),
            ])],
        });
        assert!(
            results.has_cycles(),
            "results with cycles should report has_cycles"
        );
        assert_eq!(
            results.total_cycles(),
            1,
            "results should have 1 total cycle"
        );
        assert_eq!(
            results.packages_with_cycles(),
            1,
            "results should have 1 package with cycles"
        );
    }

    #[test]
    fn test_human_formatter() {
        let formatter = HumanFormatter::new(false);
        let results = Results::new();
        let mut output = Vec::new();
        formatter
            .format(&results, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");
        assert!(
            output_str.contains("No packages found"),
            "empty results should show 'No packages found'"
        );
    }

    #[test]
    fn test_json_formatter() {
        let formatter = JsonFormatter::new();
        let mut results = Results::new();
        results.packages.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![],
        });

        let mut output = Vec::new();
        formatter
            .format(&results, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");
        assert!(
            output_str.contains("\"has_cycles\": false"),
            "JSON output should contain has_cycles: false"
        );
    }

    // =========================================================================
    // Additional output formatter tests for comprehensive coverage
    // =========================================================================

    #[test]
    fn test_unified_results_new() {
        let results = UnifiedResults::new();
        assert!(
            results.file_results.is_empty(),
            "new unified results should have no file results"
        );
        assert!(
            results.package_cycles.is_empty(),
            "new unified results should have no package cycles"
        );
    }

    #[test]
    fn test_unified_results_has_cycles() {
        let mut results = UnifiedResults::new();
        assert!(
            !results.has_file_cycles(),
            "empty should have no file cycles"
        );
        assert!(
            !results.has_package_cycles(),
            "empty should have no package cycles"
        );
        assert!(!results.has_any_cycles(), "empty should have no cycles");

        // Add file cycle
        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("a.ts"),
                PathBuf::from("b.ts"),
                PathBuf::from("a.ts"),
            ])],
        });

        assert!(
            results.has_file_cycles(),
            "should have file cycles after adding"
        );
        assert!(
            results.has_any_cycles(),
            "should have any cycles after adding file cycle"
        );
        assert!(
            !results.has_package_cycles(),
            "should not have package cycles yet"
        );

        // Add package cycle
        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        assert!(
            results.has_package_cycles(),
            "should have package cycles after adding"
        );
        assert!(
            results.has_any_cycles(),
            "should have any cycles after adding package cycle"
        );
    }

    #[test]
    fn test_unified_results_totals() {
        let mut results = UnifiedResults::new();
        assert_eq!(
            results.total_file_cycles(),
            0,
            "empty should have 0 file cycles"
        );
        assert_eq!(
            results.packages_with_cycles(),
            0,
            "empty should have 0 packages with cycles"
        );

        // Add packages with cycles
        results.file_results.push(PackageResult {
            name: "@test/pkg-a".to_owned(),
            path: PathBuf::from("/test/a"),
            cycles: vec![
                Cycle::new(vec![
                    PathBuf::from("a.ts"),
                    PathBuf::from("b.ts"),
                    PathBuf::from("a.ts"),
                ]),
                Cycle::new(vec![
                    PathBuf::from("c.ts"),
                    PathBuf::from("d.ts"),
                    PathBuf::from("c.ts"),
                ]),
            ],
        });

        results.file_results.push(PackageResult {
            name: "@test/pkg-b".to_owned(),
            path: PathBuf::from("/test/b"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("x.ts"),
                PathBuf::from("y.ts"),
                PathBuf::from("x.ts"),
            ])],
        });

        results.file_results.push(PackageResult {
            name: "@test/pkg-c".to_owned(),
            path: PathBuf::from("/test/c"),
            cycles: vec![],
        });

        assert_eq!(
            results.total_file_cycles(),
            3,
            "should have 3 total file cycles"
        );
        assert_eq!(
            results.packages_with_cycles(),
            2,
            "should have 2 packages with cycles"
        );
    }

    #[test]
    fn test_cycle_filter_default() {
        let filter = CycleFilter::default();
        assert_eq!(filter, CycleFilter::All, "default filter should be All");
    }

    #[test]
    fn test_human_formatter_with_cycles() {
        let formatter = HumanFormatter::new(false);
        let mut results = Results::new();
        results.packages.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("/test/a.ts"),
                PathBuf::from("/test/b.ts"),
                PathBuf::from("/test/a.ts"),
            ])],
        });

        let mut output = Vec::new();
        formatter
            .format(&results, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("@test/pkg"),
            "should contain package name"
        );
        assert!(output_str.contains("1 cycle"), "should show cycle count");
        assert!(
            output_str.contains("a.ts") && output_str.contains("b.ts"),
            "should show cycle files"
        );
    }

    #[test]
    fn test_human_formatter_with_color() {
        let formatter = HumanFormatter::new(true).with_verbose(true);
        let mut results = Results::new();
        results.packages.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![],
        });

        let mut output = Vec::new();
        formatter
            .format(&results, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // Check for ANSI color codes (green for success)
        assert!(
            output_str.contains("\x1b[32m"),
            "should contain green color code for no cycles"
        );
    }

    #[test]
    fn test_json_formatter_with_cycles() {
        let formatter = JsonFormatter::new();
        let mut results = Results::new();
        results.packages.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("/test/a.ts"),
                PathBuf::from("/test/b.ts"),
                PathBuf::from("/test/a.ts"),
            ])],
        });

        let mut output = Vec::new();
        formatter
            .format(&results, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("\"has_cycles\": true"),
            "JSON should report has_cycles: true"
        );
        assert!(
            output_str.contains("@test/pkg"),
            "JSON should contain package name"
        );
        assert!(
            output_str.contains("a.ts"),
            "JSON should contain cycle file"
        );
    }

    #[test]
    fn test_unified_human_formatter_all_filter() {
        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("/test/a.ts"),
                PathBuf::from("/test/b.ts"),
                PathBuf::from("/test/a.ts"),
            ])],
        });

        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::All, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("inter-package"),
            "should show inter-package cycles with All filter"
        );
        assert!(
            output_str.contains("@test/pkg"),
            "should show file-level package with All filter"
        );
    }

    #[test]
    fn test_unified_human_formatter_inner_filter() {
        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("/test/a.ts"),
                PathBuf::from("/test/b.ts"),
                PathBuf::from("/test/a.ts"),
            ])],
        });

        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Inner, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("@test/pkg"),
            "should show file-level package with Inner filter"
        );
        assert!(
            output_str.contains("file cycles"),
            "should mention file cycles in summary"
        );
    }

    #[test]
    fn test_unified_human_formatter_outer_filter() {
        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("/test/a.ts"),
                PathBuf::from("/test/b.ts"),
                PathBuf::from("/test/a.ts"),
            ])],
        });

        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("inter-package"),
            "should show inter-package cycles with Outer filter"
        );
    }

    #[test]
    fn test_unified_json_formatter_all_filter() {
        let formatter = JsonFormatter::new();
        let mut results = UnifiedResults::new();

        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("/test/a.ts"),
                PathBuf::from("/test/b.ts"),
                PathBuf::from("/test/a.ts"),
            ])],
        });

        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::All, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("\"has_cycles\": true"),
            "JSON should report has_cycles"
        );
        assert!(
            output_str.contains("\"has_file_cycles\": true"),
            "JSON should report has_file_cycles"
        );
        assert!(
            output_str.contains("\"has_package_cycles\": true"),
            "JSON should report has_package_cycles"
        );
        assert!(
            output_str.contains("\"file_cycles\""),
            "JSON should include file_cycles"
        );
        assert!(
            output_str.contains("\"package_cycles\""),
            "JSON should include package_cycles"
        );
    }

    #[test]
    fn test_unified_json_formatter_inner_filter() {
        let formatter = JsonFormatter::new();
        let mut results = UnifiedResults::new();

        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![],
        });

        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Inner, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // With Inner filter, package_cycles should be empty in output
        assert!(
            output_str.contains("\"package_cycles\": []"),
            "JSON should have empty package_cycles with Inner filter"
        );
    }

    #[test]
    fn test_unified_json_formatter_outer_filter() {
        let formatter = JsonFormatter::new();
        let mut results = UnifiedResults::new();

        results.file_results.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("a.ts"),
                PathBuf::from("a.ts"),
            ])],
        });

        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // With Outer filter, file_cycles should be empty in output
        assert!(
            output_str.contains("\"file_cycles\": []"),
            "JSON should have empty file_cycles with Outer filter"
        );
        assert!(
            output_str.contains("@pkg/a"),
            "JSON should include package cycle"
        );
    }

    #[test]
    fn test_human_formatter_multiple_cycles() {
        let formatter = HumanFormatter::new(false);
        let mut results = Results::new();
        results.packages.push(PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![
                Cycle::new(vec![
                    PathBuf::from("/test/a.ts"),
                    PathBuf::from("/test/b.ts"),
                    PathBuf::from("/test/a.ts"),
                ]),
                Cycle::new(vec![
                    PathBuf::from("/test/c.ts"),
                    PathBuf::from("/test/d.ts"),
                    PathBuf::from("/test/c.ts"),
                ]),
            ],
        });

        let mut output = Vec::new();
        formatter
            .format(&results, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("2 cycles"),
            "should show plural 'cycles' for multiple"
        );
    }

    #[test]
    fn test_results_default() {
        let results = Results::default();
        assert!(
            results.packages.is_empty(),
            "default results should be empty"
        );
        assert!(
            !results.has_cycles(),
            "default results should have no cycles"
        );
    }

    #[test]
    fn test_unified_results_default() {
        let results = UnifiedResults::default();
        assert!(
            results.file_results.is_empty(),
            "default unified results should have no file results"
        );
        assert!(
            results.package_cycles.is_empty(),
            "default unified results should have no package cycles"
        );
    }

    #[test]
    fn test_package_result_clone() {
        let result = PackageResult {
            name: "@test/pkg".to_owned(),
            path: PathBuf::from("/test"),
            cycles: vec![Cycle::new(vec![
                PathBuf::from("a.ts"),
                PathBuf::from("a.ts"),
            ])],
        };

        let cloned = result.clone();
        assert_eq!(cloned.name, result.name, "cloned name should match");
        assert_eq!(cloned.path, result.path, "cloned path should match");
        assert_eq!(
            cloned.cycles.len(),
            result.cycles.len(),
            "cloned cycles should match"
        );
    }

    #[test]
    fn test_human_formatter_no_package_cycles() {
        let formatter = HumanFormatter::new(false);
        let results = UnifiedResults::new();

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("No inter-package cycles"),
            "should show no inter-package cycles message"
        );
    }

    #[test]
    fn test_human_formatter_package_cycle_format() {
        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        results.package_cycles.push(PackageCycle::new(vec![
            "@myorg/a".to_owned(),
            "@myorg/b".to_owned(),
            "@myorg/c".to_owned(),
            "@myorg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        assert!(
            output_str.contains("@myorg/a -> @myorg/b -> @myorg/c -> @myorg/a"),
            "should format package cycle with arrows"
        );
    }

    // =========================================================================
    // Tests for file-level detail in output
    // =========================================================================

    #[test]
    fn test_human_formatter_cycle_with_files() {
        use crate::cycles::{PackageCycleEdge, PackageCycleWithFiles};

        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        // Create a cycle with file details
        let mut edge1 = PackageCycleEdge::new("@pkg/a".to_owned(), "@pkg/b".to_owned());
        edge1
            .files
            .push((PathBuf::from("/project/a/index.ts"), None));

        let mut edge2 = PackageCycleEdge::new("@pkg/b".to_owned(), "@pkg/a".to_owned());
        edge2.files.push((
            PathBuf::from("/project/b/utils.ts"),
            Some("helpers".to_owned()),
        ));

        results
            .package_cycles_with_files
            .push(PackageCycleWithFiles {
                packages: vec![
                    "@pkg/a".to_owned(),
                    "@pkg/b".to_owned(),
                    "@pkg/a".to_owned(),
                ],
                edges: vec![edge1, edge2],
            });

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // Check cycle summary
        assert!(
            output_str.contains("@pkg/a -> @pkg/b -> @pkg/a"),
            "should show cycle summary: {output_str}"
        );

        // Check edge headers
        assert!(
            output_str.contains("@pkg/a -> @pkg/b"),
            "should show first edge: {output_str}"
        );
        assert!(
            output_str.contains("@pkg/b -> @pkg/a"),
            "should show second edge: {output_str}"
        );

        // Check file paths
        assert!(
            output_str.contains("/project/a/index.ts"),
            "should show first file path: {output_str}"
        );
        assert!(
            output_str.contains("/project/b/utils.ts"),
            "should show second file path: {output_str}"
        );

        // Check subpath is shown
        assert!(
            output_str.contains("(imports @pkg/a/helpers)"),
            "should show subpath: {output_str}"
        );
    }

    #[test]
    fn test_human_formatter_cycle_with_files_multiple_files() {
        use crate::cycles::{PackageCycleEdge, PackageCycleWithFiles};

        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        // Create a cycle with multiple files per edge
        let mut edge1 = PackageCycleEdge::new("@pkg/a".to_owned(), "@pkg/b".to_owned());
        edge1
            .files
            .push((PathBuf::from("/project/a/index.ts"), None));
        edge1.files.push((
            PathBuf::from("/project/a/helpers.ts"),
            Some("utils".to_owned()),
        ));
        edge1
            .files
            .push((PathBuf::from("/project/a/types.ts"), None));

        let mut edge2 = PackageCycleEdge::new("@pkg/b".to_owned(), "@pkg/a".to_owned());
        edge2.files.push((PathBuf::from("/project/b/lib.ts"), None));

        results
            .package_cycles_with_files
            .push(PackageCycleWithFiles {
                packages: vec![
                    "@pkg/a".to_owned(),
                    "@pkg/b".to_owned(),
                    "@pkg/a".to_owned(),
                ],
                edges: vec![edge1, edge2],
            });

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // Check all files are shown
        assert!(
            output_str.contains("/project/a/index.ts"),
            "should show first file"
        );
        assert!(
            output_str.contains("/project/a/helpers.ts"),
            "should show second file"
        );
        assert!(
            output_str.contains("/project/a/types.ts"),
            "should show third file"
        );
        assert!(
            output_str.contains("/project/b/lib.ts"),
            "should show fourth file"
        );
    }

    #[test]
    fn test_human_formatter_uses_cycles_with_files_when_available() {
        use crate::cycles::{PackageCycleEdge, PackageCycleWithFiles};

        let formatter = HumanFormatter::new(false);
        let mut results = UnifiedResults::new();

        // Add both basic cycles and cycles with files - should use the detailed version
        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/x".to_owned(),
            "@pkg/y".to_owned(),
            "@pkg/x".to_owned(),
        ]));

        let mut edge = PackageCycleEdge::new("@pkg/a".to_owned(), "@pkg/b".to_owned());
        edge.files.push((PathBuf::from("/detailed.ts"), None));

        results
            .package_cycles_with_files
            .push(PackageCycleWithFiles {
                packages: vec![
                    "@pkg/a".to_owned(),
                    "@pkg/b".to_owned(),
                    "@pkg/a".to_owned(),
                ],
                edges: vec![
                    edge,
                    PackageCycleEdge::new("@pkg/b".to_owned(), "@pkg/a".to_owned()),
                ],
            });

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // Should use detailed format when available
        assert!(
            output_str.contains("/detailed.ts"),
            "should use detailed format when available: {output_str}"
        );
    }

    #[test]
    fn test_json_formatter_cycle_with_files() {
        use crate::cycles::{PackageCycleEdge, PackageCycleWithFiles};

        let formatter = JsonFormatter::new();
        let mut results = UnifiedResults::new();

        let mut edge = PackageCycleEdge::new("@pkg/a".to_owned(), "@pkg/b".to_owned());
        edge.files
            .push((PathBuf::from("/src/index.ts"), Some("lib".to_owned())));

        results
            .package_cycles_with_files
            .push(PackageCycleWithFiles {
                packages: vec![
                    "@pkg/a".to_owned(),
                    "@pkg/b".to_owned(),
                    "@pkg/a".to_owned(),
                ],
                edges: vec![
                    edge,
                    PackageCycleEdge::new("@pkg/b".to_owned(), "@pkg/a".to_owned()),
                ],
            });

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        // Parse as JSON to verify structure
        let json: serde_json::Value =
            serde_json::from_str(&output_str).expect("output should be valid JSON");

        assert!(
            json.get("has_package_cycles")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            "has_package_cycles should be true"
        );

        let package_cycles = json
            .get("package_cycles")
            .and_then(|v| v.as_array())
            .expect("package_cycles should be array");
        assert_eq!(package_cycles.len(), 1, "should have 1 cycle");

        let cycle = package_cycles.first().expect("should have first cycle");
        let edges = cycle
            .get("edges")
            .and_then(|v| v.as_array())
            .expect("should have edges");
        assert_eq!(edges.len(), 2, "should have 2 edges");

        let first_edge = edges.first().expect("should have first edge");
        assert_eq!(
            first_edge.get("from_package").and_then(|v| v.as_str()),
            Some("@pkg/a"),
            "from_package should be @pkg/a"
        );
        assert_eq!(
            first_edge.get("to_package").and_then(|v| v.as_str()),
            Some("@pkg/b"),
            "to_package should be @pkg/b"
        );

        let files = first_edge
            .get("files")
            .and_then(|v| v.as_array())
            .expect("should have files");
        assert_eq!(files.len(), 1, "should have 1 file");

        let file = files.first().expect("should have first file");
        assert_eq!(
            file.get("path").and_then(|v| v.as_str()),
            Some("/src/index.ts"),
            "file path should match"
        );
        assert_eq!(
            file.get("subpath").and_then(|v| v.as_str()),
            Some("lib"),
            "file subpath should match"
        );
    }

    #[test]
    fn json_edge_file_without_subpath_omits_the_key() {
        // R05: an absent subpath is omitted (not `null`); consumers test presence.
        let value = serde_json::to_value(JsonEdgeFile {
            path: "/src/index.ts".to_owned(),
            subpath: None,
        })
        .expect("serializable");
        assert_eq!(value, serde_json::json!({"path": "/src/index.ts"}));
    }

    #[test]
    fn test_json_formatter_basic_cycle_without_files() {
        let formatter = JsonFormatter::new();
        let mut results = UnifiedResults::new();

        // Only basic cycles, no detailed version
        results.package_cycles.push(PackageCycle::new(vec![
            "@pkg/a".to_owned(),
            "@pkg/b".to_owned(),
            "@pkg/a".to_owned(),
        ]));

        let mut output = Vec::new();
        formatter
            .format_unified(&results, CycleFilter::Outer, &mut output)
            .expect("test formatting should succeed");
        let output_str = String::from_utf8(output).expect("test output should be valid UTF-8");

        let json: serde_json::Value =
            serde_json::from_str(&output_str).expect("output should be valid JSON");

        let package_cycles = json
            .get("package_cycles")
            .and_then(|v| v.as_array())
            .expect("package_cycles should be array");
        assert_eq!(package_cycles.len(), 1, "should have 1 cycle");

        let cycle = package_cycles.first().expect("should have first cycle");
        let edges = cycle
            .get("edges")
            .and_then(|v| v.as_array())
            .expect("should have edges");

        // Edges should exist but have empty files
        let first_edge = edges.first().expect("should have first edge");
        let files = first_edge
            .get("files")
            .and_then(|v| v.as_array())
            .expect("should have files array");
        assert!(files.is_empty(), "files should be empty for basic cycle");
    }

    #[test]
    fn test_unified_results_has_package_cycles_with_files() {
        use crate::cycles::{PackageCycleEdge, PackageCycleWithFiles};

        let mut results = UnifiedResults::new();
        assert!(
            !results.has_package_cycles(),
            "empty should have no package cycles"
        );

        // Add cycle with files
        results
            .package_cycles_with_files
            .push(PackageCycleWithFiles {
                packages: vec![
                    "@pkg/a".to_owned(),
                    "@pkg/b".to_owned(),
                    "@pkg/a".to_owned(),
                ],
                edges: vec![PackageCycleEdge::new(
                    "@pkg/a".to_owned(),
                    "@pkg/b".to_owned(),
                )],
            });

        assert!(
            results.has_package_cycles(),
            "should have package cycles after adding cycles_with_files"
        );
        assert!(
            results.has_any_cycles(),
            "should have any cycles after adding"
        );
    }
}