code-graph-cli 3.0.2

Code intelligence engine for TypeScript/JavaScript/Rust/Python/Go — query the dependency graph instead of reading source files.
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
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
use std::io::IsTerminal;
use std::path::Path;

use crate::query::structure::StructureNode;

use crate::cli::OutputFormat;
use crate::graph::node::SymbolVisibility;
use crate::query::circular::CircularDep;
use crate::query::context::SymbolContext;
use crate::query::find::FindResult;
use crate::query::find::kind_to_str;
use crate::query::impact::ImpactResult;
use crate::query::refs::{RefKind, RefResult};
use crate::query::stats::ProjectStats;

/// Determine the display language name of a file from its extension.
fn language_of_file(path: &Path) -> &'static str {
    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
        "ts" | "tsx" => "TypeScript",
        "js" | "jsx" => "JavaScript",
        "rs" => "Rust",
        "py" => "Python",
        "go" => "Go",
        _ => "Unknown",
    }
}

/// Returns true if a slice of file paths spans multiple distinct languages.
fn is_mixed_language<F: Fn(&T) -> &Path, T>(items: &[T], get_path: F) -> bool {
    if items.is_empty() {
        return false;
    }
    let first_lang = language_of_file(get_path(&items[0]));
    items[1..]
        .iter()
        .any(|i| language_of_file(get_path(i)) != first_lang)
}

/// Sort key for language grouping: Go < JavaScript < Python < Rust < TypeScript < Unknown.
fn language_sort_key(lang: &str) -> u8 {
    match lang {
        "Go" => 1,
        "JavaScript" => 2,
        "Python" => 3,
        "Rust" => 4,
        "TypeScript" => 5,
        _ => 6,
    }
}

/// Map a `SymbolVisibility` to its display string for output.
fn visibility_str(vis: &SymbolVisibility) -> &'static str {
    match vis {
        SymbolVisibility::Pub => "pub",
        SymbolVisibility::PubCrate => "pub(crate)",
        SymbolVisibility::Private => "private",
    }
}

/// Returns true if any result has non-Private visibility.
/// Used to suppress visibility column noise for pure TS/JS projects.
fn any_non_private(results: &[FindResult]) -> bool {
    results
        .iter()
        .any(|r| r.visibility != SymbolVisibility::Private)
}

/// Format and print find results to stdout according to the selected output format.
///
/// In compact and table modes, if results span multiple languages, groups them under
/// `--- {Language} ---` section headers. JSON mode adds a "language" field per result.
pub fn format_find_results(
    results: &[FindResult],
    format: &OutputFormat,
    project_root: &Path,
    symbol_name: &str,
) {
    let show_vis = any_non_private(results);
    let mixed = is_mixed_language(results, |r: &FindResult| r.file_path.as_path());

    // Sort results: by language first (for grouping), then file path, then line.
    // Only clone when sorting is needed to avoid unnecessary allocation.
    let sorted;
    let results_ref = if mixed {
        sorted = {
            let mut v = results.to_vec();
            v.sort_by(|a, b| {
                let la = language_of_file(&a.file_path);
                let lb = language_of_file(&b.file_path);
                language_sort_key(la)
                    .cmp(&language_sort_key(lb))
                    .then(a.file_path.cmp(&b.file_path))
                    .then(a.line.cmp(&b.line))
            });
            v
        };
        &sorted[..]
    } else {
        results
    };

    match format {
        OutputFormat::Compact => {
            let mut last_lang: Option<&'static str> = None;
            for r in results_ref {
                if mixed {
                    let lang = language_of_file(&r.file_path);
                    if last_lang != Some(lang) {
                        println!("--- {} ---", lang);
                        last_lang = Some(lang);
                    }
                }
                let rel = r
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&r.file_path);
                if show_vis {
                    println!(
                        "def {} {}:{} {} {}",
                        r.symbol_name,
                        rel.display(),
                        r.line,
                        kind_to_str(&r.kind),
                        visibility_str(&r.visibility),
                    );
                } else {
                    println!(
                        "def {} {}:{} {}",
                        r.symbol_name,
                        rel.display(),
                        r.line,
                        kind_to_str(&r.kind)
                    );
                }
            }
            println!("{} definitions found", results.len());
            if results.is_empty() {
                println!("hint: no results found -- try a broader pattern or check spelling");
            } else {
                println!("hint: use refs {} to find all references", symbol_name);
            }
        }

        OutputFormat::Table => {
            let use_color = std::io::stdout().is_terminal();

            // Column widths: auto-sized to data (single pass).
            let (name_w, file_w) = results_ref.iter().fold((6usize, 4usize), |(nw, fw), r| {
                let file_len = r
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&r.file_path)
                    .to_string_lossy()
                    .len();
                (nw.max(r.symbol_name.len()), fw.max(file_len))
            });

            if show_vis {
                if use_color {
                    println!(
                        "\x1b[1m{:<name_w$}  {:<file_w$}  {:>4}  {:<10}  KIND\x1b[0m",
                        "SYMBOL",
                        "FILE",
                        "LINE",
                        "VIS",
                        name_w = name_w,
                        file_w = file_w,
                    );
                } else {
                    println!(
                        "{:<name_w$}  {:<file_w$}  {:>4}  {:<10}  KIND",
                        "SYMBOL",
                        "FILE",
                        "LINE",
                        "VIS",
                        name_w = name_w,
                        file_w = file_w,
                    );
                }
                println!("{}", "-".repeat(name_w + file_w + 26));
                let mut last_lang: Option<&'static str> = None;
                for r in results_ref {
                    if mixed {
                        let lang = language_of_file(&r.file_path);
                        if last_lang != Some(lang) {
                            println!("--- {} ---", lang);
                            last_lang = Some(lang);
                        }
                    }
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    println!(
                        "{:<name_w$}  {:<file_w$}  {:>4}  {:<10}  {}",
                        r.symbol_name,
                        rel.display(),
                        r.line,
                        visibility_str(&r.visibility),
                        kind_to_str(&r.kind),
                        name_w = name_w,
                        file_w = file_w,
                    );
                }
            } else {
                if use_color {
                    println!(
                        "\x1b[1m{:<name_w$}  {:<file_w$}  {:>4}  KIND\x1b[0m",
                        "SYMBOL",
                        "FILE",
                        "LINE",
                        name_w = name_w,
                        file_w = file_w,
                    );
                } else {
                    println!(
                        "{:<name_w$}  {:<file_w$}  {:>4}  KIND",
                        "SYMBOL",
                        "FILE",
                        "LINE",
                        name_w = name_w,
                        file_w = file_w,
                    );
                }
                println!("{}", "-".repeat(name_w + file_w + 14));
                let mut last_lang: Option<&'static str> = None;
                for r in results_ref {
                    if mixed {
                        let lang = language_of_file(&r.file_path);
                        if last_lang != Some(lang) {
                            println!("--- {} ---", lang);
                            last_lang = Some(lang);
                        }
                    }
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    println!(
                        "{:<name_w$}  {:<file_w$}  {:>4}  {}",
                        r.symbol_name,
                        rel.display(),
                        r.line,
                        kind_to_str(&r.kind),
                        name_w = name_w,
                        file_w = file_w,
                    );
                }
            }
        }

        OutputFormat::Json => {
            let json_results: Vec<serde_json::Value> = results_ref
                .iter()
                .map(|r| {
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    serde_json::json!({
                        "name": r.symbol_name,
                        "kind": kind_to_str(&r.kind),
                        "file": rel.to_string_lossy(),
                        "language": language_of_file(&r.file_path),
                        "line": r.line,
                        "col": r.col,
                        "exported": r.is_exported,
                        "default": r.is_default,
                        "visibility": visibility_str(&r.visibility),
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&json_results).unwrap_or_default()
            );
        }
    }
}

/// Determine if the stats have Rust symbols present.
fn stats_has_rust(stats: &ProjectStats) -> bool {
    stats.rust_fns
        + stats.rust_structs
        + stats.rust_enums
        + stats.rust_traits
        + stats.rust_impl_methods
        + stats.rust_type_aliases
        + stats.rust_consts
        + stats.rust_statics
        + stats.rust_macros
        + stats.rust_imports
        + stats.rust_reexports
        > 0
}

/// Determine if the stats have TypeScript/JavaScript symbols present.
fn stats_has_ts_js(stats: &ProjectStats) -> bool {
    // Total symbols minus Rust-specific, Python-specific, and Go-specific symbols indicates TS/JS presence.
    let rust_total = stats.rust_fns
        + stats.rust_structs
        + stats.rust_enums
        + stats.rust_traits
        + stats.rust_impl_methods
        + stats.rust_type_aliases
        + stats.rust_consts
        + stats.rust_statics
        + stats.rust_macros;
    let non_rust_non_py_non_go = stats
        .symbol_count
        .saturating_sub(rust_total + stats.python_symbol_count + stats.go_symbol_count);
    non_rust_non_py_non_go > 0
        || stats.classes > stats.python_classes
        || stats.interfaces > stats.go_interfaces
        || stats.variables > stats.python_variables + stats.go_variables
        || stats.methods > stats.python_methods + stats.go_methods
        || stats.components > 0
}

/// Determine if the stats have Python symbols or files present.
fn stats_has_python(stats: &ProjectStats) -> bool {
    stats.python_file_count > 0 || stats.python_symbol_count > 0
}

/// Determine if the stats have Go symbols or files present.
fn stats_has_go(stats: &ProjectStats) -> bool {
    stats.go_file_count > 0 || stats.go_symbol_count > 0
}

/// Format and print project stats to stdout according to the selected output format.
///
/// `language_filter`: if Some("rust"), show only Rust section; if Some("typescript"),
/// show only TypeScript section; if Some("python"), show Python section; if None, show all.
pub fn format_stats(stats: &ProjectStats, format: &OutputFormat, language_filter: Option<&str>) {
    let show_rust = language_filter.is_none() || language_filter == Some("rust");
    let show_ts = language_filter.is_none()
        || language_filter == Some("typescript")
        || language_filter == Some("javascript");
    let show_python = language_filter.is_none() || language_filter == Some("python");
    let show_go = language_filter.is_none() || language_filter == Some("go");
    let show_totals = language_filter.is_none();

    let has_rust = stats_has_rust(stats);
    let has_ts = stats_has_ts_js(stats);
    let has_python = stats_has_python(stats);
    let has_go = stats_has_go(stats);

    match format {
        OutputFormat::Compact => {
            // File overview line
            if stats.non_parsed_files > 0 {
                println!(
                    "{} files ({} source, {} non-parsed), {} symbols",
                    stats.file_count,
                    stats.source_files,
                    stats.non_parsed_files,
                    stats.symbol_count
                );
                println!(
                    "non-parsed: doc {} config {} ci {} asset {} other {}",
                    stats.doc_files,
                    stats.config_files,
                    stats.ci_files,
                    stats.asset_files,
                    stats.other_files,
                );
            }
            // Per-language sections with per-language counts and combined totals.
            if show_rust && has_rust {
                let rust_symbol_total = stats.rust_fns
                    + stats.rust_structs
                    + stats.rust_enums
                    + stats.rust_traits
                    + stats.rust_impl_methods
                    + stats.rust_type_aliases
                    + stats.rust_consts
                    + stats.rust_statics
                    + stats.rust_macros;
                println!(
                    "Rust: {} symbols (fn: {} struct: {} enum: {} trait: {} impl_method: {} type: {} const: {} static: {} macro: {})",
                    rust_symbol_total,
                    stats.rust_fns,
                    stats.rust_structs,
                    stats.rust_enums,
                    stats.rust_traits,
                    stats.rust_impl_methods,
                    stats.rust_type_aliases,
                    stats.rust_consts,
                    stats.rust_statics,
                    stats.rust_macros,
                );
                println!(
                    "rust_use {} rust_pub_use {}",
                    stats.rust_imports, stats.rust_reexports,
                );
                // Dependencies section (Phase 9)
                let has_deps = stats.external_packages > 0 || stats.builtin_count > 0;
                if has_deps {
                    println!(
                        "dependencies external_crates {} (usages {}) builtins {} (usages {})",
                        stats.external_packages,
                        stats.external_usage_count,
                        stats.builtin_count,
                        stats.builtin_usage_count,
                    );
                }
                // Per-crate breakdown (Phase 9, only for workspaces with multiple crates)
                if !stats.rust_crate_stats.is_empty() {
                    for cs in &stats.rust_crate_stats {
                        println!(
                            "crate {} files {} symbols {}",
                            cs.crate_name, cs.file_count, cs.symbol_count
                        );
                    }
                }
            }
            if show_ts && has_ts {
                // Subtract Rust-specific, Python, and Go symbols to get TS/JS-only counts.
                let ts_fns = stats
                    .functions
                    .saturating_sub(stats.rust_fns + stats.python_fns + stats.go_fns);
                let ts_classes = stats.classes.saturating_sub(stats.python_classes);
                let ts_enums = stats.enums.saturating_sub(stats.rust_enums);
                let ts_type_aliases = stats.type_aliases.saturating_sub(
                    stats.rust_type_aliases + stats.python_type_aliases + stats.go_type_aliases,
                );
                let ts_variables = stats
                    .variables
                    .saturating_sub(stats.python_variables + stats.go_variables);
                let ts_methods = stats
                    .methods
                    .saturating_sub(stats.python_methods + stats.go_methods);
                let rust_total = stats.rust_fns
                    + stats.rust_structs
                    + stats.rust_enums
                    + stats.rust_traits
                    + stats.rust_impl_methods
                    + stats.rust_type_aliases
                    + stats.rust_consts
                    + stats.rust_statics
                    + stats.rust_macros;
                let ts_total = stats
                    .symbol_count
                    .saturating_sub(rust_total + stats.python_symbol_count + stats.go_symbol_count);
                println!(
                    "TypeScript: {} symbols (function: {} class: {} interface: {} type: {} enum: {} variable: {} component: {} method: {} property: {})",
                    ts_total,
                    ts_fns,
                    ts_classes,
                    stats.interfaces,
                    ts_type_aliases,
                    ts_enums,
                    ts_variables,
                    stats.components,
                    ts_methods,
                    stats.properties,
                );
                println!(
                    "imports {} external {} unresolved {}",
                    stats.import_edges, stats.external_packages, stats.unresolved_imports,
                );
            }
            if show_python && has_python {
                println!(
                    "Python: {} files, {} symbols (fn: {} class: {} method: {} type: {} variable: {})",
                    stats.python_file_count,
                    stats.python_symbol_count,
                    stats.python_fns,
                    stats.python_classes,
                    stats.python_methods,
                    stats.python_type_aliases,
                    stats.python_variables,
                );
            }
            if show_go && has_go {
                println!(
                    "Go: {} files, {} symbols (fn: {} struct: {} interface: {} method: {} const: {} var: {} type: {})",
                    stats.go_file_count,
                    stats.go_symbol_count,
                    stats.go_fns,
                    stats.go_structs,
                    stats.go_interfaces,
                    stats.go_methods,
                    stats.go_consts,
                    stats.go_variables,
                    stats.go_type_aliases,
                );
            }
            if show_totals && (has_rust || has_ts || has_python || has_go) {
                let language_count = [has_rust, has_ts, has_python, has_go]
                    .iter()
                    .filter(|&&x| x)
                    .count();
                if language_count > 1 {
                    println!("---");
                    println!(
                        "Total: {} files, {} symbols",
                        stats.file_count, stats.symbol_count
                    );
                } else {
                    println!("files {}", stats.file_count);
                    println!("symbols {}", stats.symbol_count);
                }
            } else if show_totals {
                println!("files {}", stats.file_count);
                println!("symbols {}", stats.symbol_count);
            }
            // Fallback: show full stats if no language-specific sections match
            if !has_rust && !has_ts && !has_python && !has_go {
                println!("files {}", stats.file_count);
                println!("symbols {}", stats.symbol_count);
                println!(
                    "imports {} external {} unresolved {}",
                    stats.import_edges, stats.external_packages, stats.unresolved_imports
                );
            }
            println!("hint: use dead-code to find unreferenced symbols");
        }

        OutputFormat::Table => {
            let use_color = std::io::stdout().is_terminal();
            let header = |s: &str| {
                if use_color {
                    format!("\x1b[1m{s}\x1b[0m")
                } else {
                    s.to_string()
                }
            };

            if show_totals || show_rust && !show_ts || show_ts && !show_rust {
                println!("{}", header("=== Project Overview ==="));
                println!(
                    "Files:    {} ({} source, {} non-parsed)",
                    stats.file_count, stats.source_files, stats.non_parsed_files
                );
                println!("Symbols:  {}", stats.symbol_count);
                if stats.non_parsed_files > 0 {
                    println!(
                        "  doc: {} config: {} ci: {} asset: {} other: {}",
                        stats.doc_files,
                        stats.config_files,
                        stats.ci_files,
                        stats.asset_files,
                        stats.other_files
                    );
                }
                println!();
            }

            if show_ts && has_ts {
                // Subtract both Rust-specific and Python symbols to get TS/JS-only counts.
                let ts_fns = stats
                    .functions
                    .saturating_sub(stats.rust_fns + stats.python_fns);
                let ts_classes = stats.classes.saturating_sub(stats.python_classes);
                let ts_enums = stats.enums.saturating_sub(stats.rust_enums);
                let ts_type_aliases = stats
                    .type_aliases
                    .saturating_sub(stats.rust_type_aliases + stats.python_type_aliases);
                let ts_variables = stats.variables.saturating_sub(stats.python_variables);
                let ts_methods = stats.methods.saturating_sub(stats.python_methods);
                println!("{}", header("--- TypeScript/JavaScript ---"));
                println!("  Functions:    {}", ts_fns);
                println!("  Classes:      {}", ts_classes);
                println!("  Interfaces:   {}", stats.interfaces);
                println!("  Type Aliases: {}", ts_type_aliases);
                println!("  Enums:        {}", ts_enums);
                println!("  Variables:    {}", ts_variables);
                println!("  Components:   {}", stats.components);
                println!("  Methods:      {}", ts_methods);
                println!("  Properties:   {}", stats.properties);
                println!();
                println!("{}", header("--- Import Summary ---"));
                println!("  Resolved imports:  {}", stats.import_edges);
                println!("  External packages: {}", stats.external_packages);
                println!("  Unresolved:        {}", stats.unresolved_imports);
            } else if show_totals && !has_rust {
                println!("{}", header("--- Symbol Breakdown ---"));
                println!("  Functions:   {}", stats.functions);
                println!("  Classes:     {}", stats.classes);
                println!("  Interfaces:  {}", stats.interfaces);
                println!("  Type Aliases:{}", stats.type_aliases);
                println!("  Enums:       {}", stats.enums);
                println!("  Variables:   {}", stats.variables);
                println!("  Components:  {}", stats.components);
                println!("  Methods:     {}", stats.methods);
                println!("  Properties:  {}", stats.properties);
                println!();
                println!("{}", header("--- Import Summary ---"));
                println!("  Resolved imports:  {}", stats.import_edges);
                println!("  External packages: {}", stats.external_packages);
                println!("  Unresolved:        {}", stats.unresolved_imports);
            }

            // Python section — only when Python symbols/files are present and filter allows
            if show_python && has_python {
                println!();
                println!("{}", header("--- Python ---"));
                println!("  Files:        {}", stats.python_file_count);
                println!("  Symbols:      {}", stats.python_symbol_count);
                println!("  Functions:    {}", stats.python_fns);
                println!("  Classes:      {}", stats.python_classes);
                println!("  Methods:      {}", stats.python_methods);
                println!("  Type Aliases: {}", stats.python_type_aliases);
                println!("  Variables:    {}", stats.python_variables);
            }

            // Rust section — only when Rust symbols are present and filter allows
            if show_rust && has_rust {
                println!();
                println!("{}", header("--- Rust Symbols ---"));
                println!("  fn:          {}", stats.rust_fns);
                println!("  struct:      {}", stats.rust_structs);
                println!("  enum:        {}", stats.rust_enums);
                println!("  trait:       {}", stats.rust_traits);
                println!("  impl method: {}", stats.rust_impl_methods);
                println!("  type:        {}", stats.rust_type_aliases);
                println!("  const:       {}", stats.rust_consts);
                println!("  static:      {}", stats.rust_statics);
                println!("  macro:       {}", stats.rust_macros);
                println!("  use (unresolved): {}", stats.rust_imports);
                println!("  pub use (re-exports): {}", stats.rust_reexports);

                // Dependencies section (Phase 9)
                let has_deps = stats.external_packages > 0 || stats.builtin_count > 0;
                if has_deps {
                    println!();
                    println!("{}", header("--- Dependencies ---"));
                    if stats.external_packages > 0 {
                        println!(
                            "  External crates: {} ({} usages)",
                            stats.external_packages, stats.external_usage_count
                        );
                    }
                    if stats.builtin_count > 0 {
                        println!(
                            "  Builtins (std/core/alloc): {} ({} usages)",
                            stats.builtin_count, stats.builtin_usage_count
                        );
                    }
                }

                // Per-crate breakdown (Phase 9, only for workspaces with multiple crates)
                if !stats.rust_crate_stats.is_empty() {
                    println!();
                    println!("{}", header("--- Per-Crate Breakdown ---"));
                    for cs in &stats.rust_crate_stats {
                        println!(
                            "  {} ({} files, {} symbols: fn={} struct={} enum={} trait={} impl={})",
                            cs.crate_name,
                            cs.file_count,
                            cs.symbol_count,
                            cs.fn_count,
                            cs.struct_count,
                            cs.enum_count,
                            cs.trait_count,
                            cs.impl_method_count,
                        );
                    }
                }
            }
        }

        OutputFormat::Json => {
            // Build per-crate breakdown as JSON array
            let crate_stats_json: Vec<serde_json::Value> = stats
                .rust_crate_stats
                .iter()
                .map(|cs| {
                    serde_json::json!({
                        "crate_name": cs.crate_name,
                        "file_count": cs.file_count,
                        "symbol_count": cs.symbol_count,
                        "fn_count": cs.fn_count,
                        "struct_count": cs.struct_count,
                        "enum_count": cs.enum_count,
                        "trait_count": cs.trait_count,
                        "impl_method_count": cs.impl_method_count,
                        "type_alias_count": cs.type_alias_count,
                        "const_count": cs.const_count,
                        "static_count": cs.static_count,
                        "macro_count": cs.macro_count,
                    })
                })
                .collect();

            let json = serde_json::json!({
                "file_count": stats.file_count,
                "source_files": stats.source_files,
                "non_parsed_files": stats.non_parsed_files,
                "doc_files": stats.doc_files,
                "config_files": stats.config_files,
                "ci_files": stats.ci_files,
                "asset_files": stats.asset_files,
                "other_files": stats.other_files,
                "symbol_count": stats.symbol_count,
                "functions": stats.functions,
                "classes": stats.classes,
                "interfaces": stats.interfaces,
                "type_aliases": stats.type_aliases,
                "enums": stats.enums,
                "variables": stats.variables,
                "components": stats.components,
                "methods": stats.methods,
                "properties": stats.properties,
                "import_edges": stats.import_edges,
                "external_packages": stats.external_packages,
                "unresolved_imports": stats.unresolved_imports,
                "rust_fns": stats.rust_fns,
                "rust_structs": stats.rust_structs,
                "rust_enums": stats.rust_enums,
                "rust_traits": stats.rust_traits,
                "rust_impl_methods": stats.rust_impl_methods,
                "rust_type_aliases": stats.rust_type_aliases,
                "rust_consts": stats.rust_consts,
                "rust_statics": stats.rust_statics,
                "rust_macros": stats.rust_macros,
                "rust_imports": stats.rust_imports,
                "rust_reexports": stats.rust_reexports,
                "dependencies": {
                    "external_crates": stats.external_packages,
                    "external_usage_count": stats.external_usage_count,
                    "builtin_crates": stats.builtin_count,
                    "builtin_usage_count": stats.builtin_usage_count,
                },
                "crate_stats": crate_stats_json,
                "python_file_count": stats.python_file_count,
                "python_symbol_count": stats.python_symbol_count,
                "python_fns": stats.python_fns,
                "python_classes": stats.python_classes,
                "python_methods": stats.python_methods,
                "python_type_aliases": stats.python_type_aliases,
                "python_variables": stats.python_variables,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&json).unwrap_or_default()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Refs output
// ---------------------------------------------------------------------------

/// Format and print reference results to stdout.
pub fn format_refs_results(
    results: &[RefResult],
    format: &OutputFormat,
    project_root: &Path,
    symbol_name: &str,
) {
    match format {
        OutputFormat::Compact => {
            for r in results {
                let rel = r
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&r.file_path);
                match r.ref_kind {
                    RefKind::Import => {
                        println!("ref {} import", rel.display());
                    }
                    RefKind::Call => {
                        let caller = r.symbol_name.as_deref().unwrap_or("?");
                        let line = r.line.map_or_else(|| "?".to_string(), |l| l.to_string());
                        println!("ref {}:{} call {}", rel.display(), line, caller);
                    }
                }
            }
            println!("{} references found", results.len());
            if results.is_empty() {
                println!("hint: no results found -- try a broader pattern or check spelling");
            } else {
                println!("hint: use impact {} to see blast radius", symbol_name);
            }
        }

        OutputFormat::Table => {
            let use_color = std::io::stdout().is_terminal();

            let file_w = results
                .iter()
                .map(|r| {
                    r.file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path)
                        .to_string_lossy()
                        .len()
                })
                .max()
                .unwrap_or(4)
                .max(4);
            let caller_w = results
                .iter()
                .map(|r| r.symbol_name.as_deref().unwrap_or("").len())
                .max()
                .unwrap_or(6)
                .max(6);

            if use_color {
                println!(
                    "\x1b[1m{:<file_w$}  {:<6}  {:<caller_w$}  {:>6}\x1b[0m",
                    "FILE",
                    "TYPE",
                    "CALLER",
                    "LINE",
                    file_w = file_w,
                    caller_w = caller_w,
                );
            } else {
                println!(
                    "{:<file_w$}  {:<6}  {:<caller_w$}  {:>6}",
                    "FILE",
                    "TYPE",
                    "CALLER",
                    "LINE",
                    file_w = file_w,
                    caller_w = caller_w,
                );
            }
            println!("{}", "-".repeat(file_w + caller_w + 20));

            for r in results {
                let rel = r
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&r.file_path);
                let kind_str = match r.ref_kind {
                    RefKind::Import => "import",
                    RefKind::Call => "call",
                };
                let caller = r.symbol_name.as_deref().unwrap_or("");
                let line_str = r.line.map_or_else(|| "-".to_string(), |l| l.to_string());
                println!(
                    "{:<file_w$}  {:<6}  {:<caller_w$}  {:>6}",
                    rel.display(),
                    kind_str,
                    caller,
                    line_str,
                    file_w = file_w,
                    caller_w = caller_w,
                );
            }
        }

        OutputFormat::Json => {
            let json_results: Vec<serde_json::Value> = results
                .iter()
                .map(|r| {
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    let kind_str = match r.ref_kind {
                        RefKind::Import => "import",
                        RefKind::Call => "call",
                    };
                    serde_json::json!({
                        "file": rel.to_string_lossy(),
                        "kind": kind_str,
                        "caller": r.symbol_name,
                        "line": r.line,
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&json_results).unwrap_or_default()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Impact output
// ---------------------------------------------------------------------------

/// Format and print impact (blast radius) results to stdout.
///
/// `tree_mode`: when true, use 2-space indentation per depth level.
pub fn format_impact_results(
    results: &[ImpactResult],
    format: &OutputFormat,
    project_root: &Path,
    tree_mode: bool,
    symbol_name: &str,
) {
    match format {
        OutputFormat::Compact => {
            if tree_mode {
                for r in results {
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    let indent = "  ".repeat(r.depth.saturating_sub(1));
                    println!(
                        "{}impact {} [{}: {}]",
                        indent,
                        rel.display(),
                        r.confidence,
                        r.basis
                    );
                }
            } else {
                for r in results {
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    println!("impact {} [{}: {}]", rel.display(), r.confidence, r.basis);
                }
            }
            println!("{} files affected", results.len());
            if results.is_empty() {
                println!("hint: no results found -- try a broader pattern or check spelling");
            } else {
                println!(
                    "hint: use context {} for full dependency picture",
                    symbol_name
                );
            }
        }

        OutputFormat::Table => {
            let use_color = std::io::stdout().is_terminal();

            let file_w = results
                .iter()
                .map(|r| {
                    r.file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path)
                        .to_string_lossy()
                        .len()
                })
                .max()
                .unwrap_or(4)
                .max(4);

            if use_color {
                println!(
                    "\x1b[1m{:>5}  {:<file_w$}  {:<10}  BASIS\x1b[0m",
                    "DEPTH",
                    "FILE",
                    "CONFIDENCE",
                    file_w = file_w,
                );
            } else {
                println!(
                    "{:>5}  {:<file_w$}  {:<10}  BASIS",
                    "DEPTH",
                    "FILE",
                    "CONFIDENCE",
                    file_w = file_w,
                );
            }
            println!("{}", "-".repeat(file_w + 8 + 14 + 20));

            for r in results {
                let rel = r
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&r.file_path);
                println!(
                    "{:>5}  {:<file_w$}  {:<10}  {}",
                    r.depth,
                    rel.display(),
                    r.confidence.to_string(),
                    r.basis,
                    file_w = file_w,
                );
            }
        }

        OutputFormat::Json => {
            let json_results: Vec<serde_json::Value> = results
                .iter()
                .map(|r| {
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    serde_json::json!({
                        "file": rel.to_string_lossy(),
                        "depth": r.depth,
                        "confidence": r.confidence.to_string(),
                        "basis": r.basis,
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&json_results).unwrap_or_default()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Circular output
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Context output
// ---------------------------------------------------------------------------

/// Format and print symbol context results to stdout.
///
/// Compact format is token-optimized: prefixed lines with relative paths, no decoration.
/// Sections only appear when non-empty.
pub fn format_context_results(
    contexts: &[SymbolContext],
    format: &OutputFormat,
    project_root: &Path,
    symbol_name: &str,
) {
    match format {
        OutputFormat::Compact => {
            for ctx in contexts {
                println!("symbol {}", ctx.symbol_name);

                for def in &ctx.definitions {
                    let rel = def
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&def.file_path);
                    println!(
                        "def {}:{} {}",
                        rel.display(),
                        def.line,
                        kind_to_str(&def.kind)
                    );
                }

                for r in &ctx.references {
                    let rel = r
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&r.file_path);
                    match r.ref_kind {
                        RefKind::Import => {
                            println!("ref {} import", rel.display());
                        }
                        RefKind::Call => {
                            let caller = r.symbol_name.as_deref().unwrap_or("?");
                            let line = r.line.map_or_else(|| "?".to_string(), |l| l.to_string());
                            println!("ref {}:{} call {}", rel.display(), line, caller);
                        }
                    }
                }

                for callee in &ctx.callees {
                    let rel = callee
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&callee.file_path);
                    println!(
                        "calls {} {}:{}",
                        callee.symbol_name,
                        rel.display(),
                        callee.line
                    );
                }

                for caller in &ctx.callers {
                    let rel = caller
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&caller.file_path);
                    println!(
                        "called-by {} {}:{}",
                        caller.symbol_name,
                        rel.display(),
                        caller.line
                    );
                }

                for ext in &ctx.extends {
                    let rel = ext
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&ext.file_path);
                    println!("extends {} {}:{}", ext.symbol_name, rel.display(), ext.line);
                }

                for imp in &ctx.implements {
                    let rel = imp
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&imp.file_path);
                    println!(
                        "implements {} {}:{}",
                        imp.symbol_name,
                        rel.display(),
                        imp.line
                    );
                }

                for ext_by in &ctx.extended_by {
                    let rel = ext_by
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&ext_by.file_path);
                    println!(
                        "extended-by {} {}:{}",
                        ext_by.symbol_name,
                        rel.display(),
                        ext_by.line
                    );
                }

                for impl_by in &ctx.implemented_by {
                    let rel = impl_by
                        .file_path
                        .strip_prefix(project_root)
                        .unwrap_or(&impl_by.file_path);
                    println!(
                        "implemented-by {} {}:{}",
                        impl_by.symbol_name,
                        rel.display(),
                        impl_by.line
                    );
                }

                // Summary line.
                println!(
                    "{} refs, {} callers, {} callees",
                    ctx.references.len(),
                    ctx.callers.len(),
                    ctx.callees.len()
                );
            }
            if contexts.is_empty() {
                println!("hint: no results found -- try a broader pattern or check spelling");
            } else {
                println!(
                    "hint: use flow {} <target> to trace data paths",
                    symbol_name
                );
            }
        }

        OutputFormat::Table => {
            let use_color = std::io::stdout().is_terminal();
            let bold = |s: &str| -> String {
                if use_color {
                    format!("\x1b[1m{s}\x1b[0m")
                } else {
                    s.to_string()
                }
            };

            for ctx in contexts {
                // Determine the primary kind from the first definition.
                let kind_label = ctx
                    .definitions
                    .first()
                    .map(|d| format!(" ({})", kind_to_str(&d.kind)))
                    .unwrap_or_default();

                println!(
                    "{}",
                    bold(&format!("=== {}{} ===", ctx.symbol_name, kind_label))
                );
                println!();

                // Definition section.
                println!("{}", bold("Definition:"));
                if ctx.definitions.is_empty() {
                    println!("  (none)");
                } else {
                    for def in &ctx.definitions {
                        let rel = def
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&def.file_path);
                        println!("  {}:{}", rel.display(), def.line);
                    }
                }
                println!();

                // References section.
                if !ctx.references.is_empty() {
                    println!(
                        "{}",
                        bold(&format!("References ({}):", ctx.references.len()))
                    );
                    for r in &ctx.references {
                        let rel = r
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&r.file_path);
                        match r.ref_kind {
                            RefKind::Import => {
                                println!("  {}  import", rel.display());
                            }
                            RefKind::Call => {
                                let caller = r.symbol_name.as_deref().unwrap_or("?");
                                let line =
                                    r.line.map_or_else(|| "?".to_string(), |l| l.to_string());
                                println!("  {}:{}  call  {}", rel.display(), line, caller);
                            }
                        }
                    }
                    println!();
                }

                // Calls section.
                if !ctx.callees.is_empty() {
                    println!("{}", bold(&format!("Calls ({}):", ctx.callees.len())));
                    for callee in &ctx.callees {
                        let rel = callee
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&callee.file_path);
                        println!(
                            "  {}  {}:{}",
                            callee.symbol_name,
                            rel.display(),
                            callee.line
                        );
                    }
                    println!();
                }

                // Called By section.
                if !ctx.callers.is_empty() {
                    println!("{}", bold(&format!("Called By ({}):", ctx.callers.len())));
                    for caller in &ctx.callers {
                        let rel = caller
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&caller.file_path);
                        println!(
                            "  {}  {}:{}",
                            caller.symbol_name,
                            rel.display(),
                            caller.line
                        );
                    }
                    println!();
                }

                // Extends section.
                if !ctx.extends.is_empty() {
                    println!("{}", bold(&format!("Extends ({}):", ctx.extends.len())));
                    for ext in &ctx.extends {
                        let rel = ext
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&ext.file_path);
                        println!("  {}  {}:{}", ext.symbol_name, rel.display(), ext.line);
                    }
                    println!();
                }

                // Implements section.
                if !ctx.implements.is_empty() {
                    println!(
                        "{}",
                        bold(&format!("Implements ({}):", ctx.implements.len()))
                    );
                    for imp in &ctx.implements {
                        let rel = imp
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&imp.file_path);
                        println!("  {}  {}:{}", imp.symbol_name, rel.display(), imp.line);
                    }
                    println!();
                }

                // Extended By section.
                if !ctx.extended_by.is_empty() {
                    println!(
                        "{}",
                        bold(&format!("Extended By ({}):", ctx.extended_by.len()))
                    );
                    for ext_by in &ctx.extended_by {
                        let rel = ext_by
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&ext_by.file_path);
                        println!(
                            "  {}  {}:{}",
                            ext_by.symbol_name,
                            rel.display(),
                            ext_by.line
                        );
                    }
                    println!();
                }

                // Implemented By section.
                if !ctx.implemented_by.is_empty() {
                    println!(
                        "{}",
                        bold(&format!("Implemented By ({}):", ctx.implemented_by.len()))
                    );
                    for impl_by in &ctx.implemented_by {
                        let rel = impl_by
                            .file_path
                            .strip_prefix(project_root)
                            .unwrap_or(&impl_by.file_path);
                        println!(
                            "  {}  {}:{}",
                            impl_by.symbol_name,
                            rel.display(),
                            impl_by.line
                        );
                    }
                    println!();
                }
            }
        }

        OutputFormat::Json => {
            let json_results: Vec<serde_json::Value> = contexts
                .iter()
                .map(|ctx| {
                    let definitions: Vec<serde_json::Value> = ctx
                        .definitions
                        .iter()
                        .map(|d| {
                            let rel = d
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&d.file_path);
                            serde_json::json!({
                                "file": rel.to_string_lossy(),
                                "line": d.line,
                                "kind": kind_to_str(&d.kind),
                                "exported": d.is_exported,
                            })
                        })
                        .collect();

                    let references: Vec<serde_json::Value> = ctx
                        .references
                        .iter()
                        .map(|r| {
                            let rel = r
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&r.file_path);
                            let kind_str = match r.ref_kind {
                                RefKind::Import => "import",
                                RefKind::Call => "call",
                            };
                            serde_json::json!({
                                "file": rel.to_string_lossy(),
                                "kind": kind_str,
                                "caller": r.symbol_name,
                                "line": r.line,
                            })
                        })
                        .collect();

                    let callees: Vec<serde_json::Value> = ctx
                        .callees
                        .iter()
                        .map(|c| {
                            let rel = c
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&c.file_path);
                            serde_json::json!({
                                "name": c.symbol_name,
                                "kind": kind_to_str(&c.kind),
                                "file": rel.to_string_lossy(),
                                "line": c.line,
                            })
                        })
                        .collect();

                    let callers: Vec<serde_json::Value> = ctx
                        .callers
                        .iter()
                        .map(|c| {
                            let rel = c
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&c.file_path);
                            serde_json::json!({
                                "name": c.symbol_name,
                                "kind": kind_to_str(&c.kind),
                                "file": rel.to_string_lossy(),
                                "line": c.line,
                            })
                        })
                        .collect();

                    let extends: Vec<serde_json::Value> = ctx
                        .extends
                        .iter()
                        .map(|e| {
                            let rel = e
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&e.file_path);
                            serde_json::json!({
                                "name": e.symbol_name,
                                "kind": kind_to_str(&e.kind),
                                "file": rel.to_string_lossy(),
                                "line": e.line,
                            })
                        })
                        .collect();

                    let implements: Vec<serde_json::Value> = ctx
                        .implements
                        .iter()
                        .map(|i| {
                            let rel = i
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&i.file_path);
                            serde_json::json!({
                                "name": i.symbol_name,
                                "kind": kind_to_str(&i.kind),
                                "file": rel.to_string_lossy(),
                                "line": i.line,
                            })
                        })
                        .collect();

                    let extended_by: Vec<serde_json::Value> = ctx
                        .extended_by
                        .iter()
                        .map(|e| {
                            let rel = e
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&e.file_path);
                            serde_json::json!({
                                "name": e.symbol_name,
                                "kind": kind_to_str(&e.kind),
                                "file": rel.to_string_lossy(),
                                "line": e.line,
                            })
                        })
                        .collect();

                    let implemented_by: Vec<serde_json::Value> = ctx
                        .implemented_by
                        .iter()
                        .map(|i| {
                            let rel = i
                                .file_path
                                .strip_prefix(project_root)
                                .unwrap_or(&i.file_path);
                            serde_json::json!({
                                "name": i.symbol_name,
                                "kind": kind_to_str(&i.kind),
                                "file": rel.to_string_lossy(),
                                "line": i.line,
                            })
                        })
                        .collect();

                    serde_json::json!({
                        "symbol": ctx.symbol_name,
                        "definitions": definitions,
                        "references": references,
                        "callees": callees,
                        "callers": callers,
                        "extends": extends,
                        "implements": implements,
                        "extended_by": extended_by,
                        "implemented_by": implemented_by,
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&json_results).unwrap_or_default()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// String-returning formatters (siblings of the println!-based CLI formatters)
// ---------------------------------------------------------------------------

/// Format find results to a String in compact prefix-free format for CLI output.
///
/// No summary line. No "def " prefix. Line format: `{rel_path}:{line} {symbol_name} {kind}`
/// (with optional visibility suffix for Rust). In mixed-language results, groups by language
/// with `--- {Language} ---` section headers.
#[cfg(test)]
pub fn format_find_to_string(
    results: &[FindResult],
    project_root: &Path,
    symbol_name: &str,
) -> String {
    use std::fmt::Write;
    let show_vis = any_non_private(results);
    let mixed = is_mixed_language(results, |r: &FindResult| r.file_path.as_path());

    // Only clone when sorting is needed to avoid unnecessary allocation.
    let sorted;
    let results_ref = if mixed {
        sorted = {
            let mut v = results.to_vec();
            v.sort_by(|a, b| {
                let la = language_of_file(&a.file_path);
                let lb = language_of_file(&b.file_path);
                language_sort_key(la)
                    .cmp(&language_sort_key(lb))
                    .then(a.file_path.cmp(&b.file_path))
                    .then(a.line.cmp(&b.line))
            });
            v
        };
        &sorted[..]
    } else {
        results
    };

    let mut buf = String::new();
    let mut last_lang: Option<&'static str> = None;
    for r in results_ref {
        if mixed {
            let lang = language_of_file(&r.file_path);
            if last_lang != Some(lang) {
                writeln!(buf, "--- {} ---", lang).unwrap();
                last_lang = Some(lang);
            }
        }
        let rel = r
            .file_path
            .strip_prefix(project_root)
            .unwrap_or(&r.file_path);
        let line_range = if r.line_end > r.line {
            format!("L{}-L{}", r.line, r.line_end)
        } else {
            format!("L{}", r.line)
        };
        if show_vis {
            writeln!(
                buf,
                "{}:{} {} {} {}",
                rel.display(),
                line_range,
                r.symbol_name,
                kind_to_str(&r.kind),
                visibility_str(&r.visibility),
            )
            .unwrap();
        } else {
            writeln!(
                buf,
                "{}:{} {} {}",
                rel.display(),
                line_range,
                r.symbol_name,
                kind_to_str(&r.kind)
            )
            .unwrap();
        }
    }
    if results.is_empty() {
        writeln!(
            buf,
            "hint: no results found -- try a broader pattern or check spelling"
        )
        .unwrap();
    } else {
        writeln!(buf, "hint: use refs {} to find all references", symbol_name).unwrap();
    }
    buf
}

/// Format find_by_decorator results to a String for CLI output.
///
/// Each result is formatted as:
/// `@decorator_name[args] symbol_name (kind) file:line`
/// Followed by `  framework: <fw>` if a framework label is available.
pub fn format_decorator_to_string(
    results: &[crate::query::decorators::DecoratorMatch],
    project_root: &Path,
    limit: usize,
) -> String {
    use std::fmt::Write;
    if results.is_empty() {
        return "No decorated symbols found.".to_string();
    }
    let mut out = String::new();
    for r in results {
        let rel_path = r
            .file_path
            .strip_prefix(project_root)
            .unwrap_or(&r.file_path);
        let kind_str = kind_to_str(&r.kind);
        // Build decorator suffix: name + optional args
        let args_str = r
            .decorator_args
            .as_deref()
            .map(|a| a.to_string())
            .unwrap_or_default();
        writeln!(
            out,
            "@{}{} {} {} {}:{}",
            r.decorator_name,
            args_str,
            r.symbol_name,
            kind_str,
            rel_path.display(),
            r.line,
        )
        .unwrap();
        if let Some(ref fw) = r.framework {
            writeln!(out, "  framework: {fw}").unwrap();
        }
    }
    if results.len() >= limit {
        writeln!(out, "… truncated at {} results", limit).unwrap();
    }
    out
}

/// Format reference results to a String in compact prefix-free format for CLI output.
///
/// No summary line. No "ref " prefix. Line formats:
/// - Import: `{rel_path} import`
/// - Call:   `{rel_path}:{line} call {caller_name}`
#[cfg(test)]
pub fn format_refs_to_string(
    results: &[RefResult],
    project_root: &Path,
    symbol_name: &str,
) -> String {
    use std::fmt::Write;
    let mut buf = String::new();
    for r in results {
        let rel = r
            .file_path
            .strip_prefix(project_root)
            .unwrap_or(&r.file_path);
        match r.ref_kind {
            RefKind::Import => {
                writeln!(buf, "{} import", rel.display()).unwrap();
            }
            RefKind::Call => {
                let caller = r.symbol_name.as_deref().unwrap_or("?");
                let line = r.line.map_or_else(|| "?".to_string(), |l| l.to_string());
                writeln!(buf, "{}:{} call {}", rel.display(), line, caller).unwrap();
            }
        }
    }
    if results.is_empty() {
        writeln!(
            buf,
            "hint: no results found -- try a broader pattern or check spelling"
        )
        .unwrap();
    } else {
        writeln!(buf, "hint: use impact {} to see blast radius", symbol_name).unwrap();
    }
    buf
}

/// Format impact (blast radius) results to a String in compact prefix-free flat format for CLI output.
///
/// No summary line. No "impact " prefix. Line format: `{rel_path} (depth N) [TIER: basis]`.
/// Uses flat (non-tree) format — flat format is more token-efficient.
#[cfg(test)]
pub fn format_impact_to_string(
    results: &[ImpactResult],
    project_root: &Path,
    symbol_name: &str,
) -> String {
    use std::fmt::Write;
    let mut buf = String::new();
    for r in results {
        let rel = r
            .file_path
            .strip_prefix(project_root)
            .unwrap_or(&r.file_path);
        writeln!(
            buf,
            "{} (depth {}) [{}: {}]",
            rel.display(),
            r.depth,
            r.confidence,
            r.basis
        )
        .unwrap();
    }
    if results.is_empty() {
        writeln!(
            buf,
            "hint: no results found -- try a broader pattern or check spelling"
        )
        .unwrap();
    } else {
        writeln!(
            buf,
            "hint: use context {} for full dependency picture",
            symbol_name
        )
        .unwrap();
    }
    buf
}

/// Format circular dependency results to a String in compact prefix-free format for CLI output.
///
/// No summary line. No "cycle " prefix. Line format: `{file1} -> {file2} -> {file3}`.
#[cfg(test)]
pub fn format_circular_to_string(cycles: &[CircularDep], project_root: &Path) -> String {
    use std::fmt::Write;
    let mut buf = String::new();
    for cycle in cycles {
        let parts: Vec<String> = cycle
            .files
            .iter()
            .map(|p| {
                p.strip_prefix(project_root)
                    .unwrap_or(p)
                    .to_string_lossy()
                    .to_string()
            })
            .collect();
        writeln!(buf, "{}", parts.join(" -> ")).unwrap();
    }
    if cycles.is_empty() {
        writeln!(
            buf,
            "hint: no results found -- try a broader pattern or check spelling"
        )
        .unwrap();
    } else {
        let first_file = cycles[0]
            .files
            .first()
            .map(|p| {
                p.strip_prefix(project_root)
                    .unwrap_or(p)
                    .to_string_lossy()
                    .to_string()
            })
            .unwrap_or_default();
        writeln!(
            buf,
            "hint: use file-summary {} to understand the circular dependency",
            first_file
        )
        .unwrap();
    }
    buf
}

/// Parse a sections filter string into an active set of section names.
///
/// - `None` input → `None` output (no filtering, all sections shown)
/// - Characters map to section names: r=references, c=callers, e=callees,
///   x=extends, i=implements, X=extended-by, I=implemented-by
/// - Commas and whitespace are separators (silently ignored)
/// - Unknown characters are silently ignored
/// - Returns `Some(HashSet)` with the matched section names
#[cfg(test)]
pub fn parse_sections(sections: Option<&str>) -> Option<std::collections::HashSet<&'static str>> {
    let s = sections?;
    let mut set = std::collections::HashSet::new();
    for ch in s.chars() {
        match ch {
            'r' => {
                set.insert("references");
            }
            'c' => {
                set.insert("callers");
            }
            'e' => {
                set.insert("callees");
            }
            'x' => {
                set.insert("extends");
            }
            'i' => {
                set.insert("implements");
            }
            'X' => {
                set.insert("extended-by");
            }
            'I' => {
                set.insert("implemented-by");
            }
            _ => {} // separators (comma, space) and unknown chars silently ignored
        }
    }
    Some(set)
}

/// Format symbol context results to a String in compact prefix-free format for CLI output.
///
/// No "N symbols" summary. No "symbol " prefix (bare symbol name on its own line).
/// No "--- section ---" delimiter lines. No "def ", "ref ", "called-by ", "calls ",
/// "extends ", "implements ", "extended-by ", "implemented-by " prefixes.
///
/// Per-section formats:
/// - Symbol header:          `{symbol_name}`
/// - Definitions:            `{rel_path}:{line} {kind}`
/// - References (import):    `{rel_path} import`
/// - References (call):      `{rel_path}:{line} call {caller}`
/// - Callers:                `{caller_name} {rel_path}:{line}`
/// - Callees:                `{callee_name} {rel_path}:{line}`
/// - Extends/implements/extended-by/implemented-by: `{name} {rel_path}:{line}`
///
/// Empty sections are silently omitted.
///
/// `sections`: optional filter string (e.g. `"r,c"`). Definitions are always included.
/// Non-empty sections that were filtered out are listed on an `omitted: ...` line.
#[cfg(test)]
pub fn format_context_to_string(
    contexts: &[SymbolContext],
    project_root: &Path,
    sections: Option<&str>,
) -> String {
    use std::fmt::Write;
    let active = parse_sections(sections);
    let mut buf = String::new();
    for ctx in contexts {
        writeln!(buf, "{}", ctx.symbol_name).unwrap();

        // Definitions are ALWAYS rendered regardless of filter.
        for def in &ctx.definitions {
            let rel = def
                .file_path
                .strip_prefix(project_root)
                .unwrap_or(&def.file_path);
            // Show decorators if present (e.g. "@Controller @Injectable")
            if !def.decorators.is_empty() {
                let decorator_str: Vec<String> = def
                    .decorators
                    .iter()
                    .map(|d| format!("@{}", d.name))
                    .collect();
                writeln!(buf, "{}", decorator_str.join(" ")).unwrap();
            }
            // Show line range (L5-L20) if line_end > line, else just line
            let line_range = if def.line_end > def.line {
                format!("L{}-L{}", def.line, def.line_end)
            } else {
                format!("L{}", def.line)
            };
            writeln!(
                buf,
                "{}:{} {}",
                rel.display(),
                line_range,
                kind_to_str(&def.kind)
            )
            .unwrap();
        }

        // Track non-empty sections that were filtered out.
        let mut omitted: Vec<&'static str> = Vec::new();

        // References
        if active.as_ref().is_none_or(|s| s.contains("references")) {
            for r in &ctx.references {
                let rel = r
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&r.file_path);
                match r.ref_kind {
                    RefKind::Import => {
                        writeln!(buf, "{} import", rel.display()).unwrap();
                    }
                    RefKind::Call => {
                        let caller = r.symbol_name.as_deref().unwrap_or("?");
                        let line = r.line.map_or_else(|| "?".to_string(), |l| l.to_string());
                        writeln!(buf, "{}:{} call {}", rel.display(), line, caller).unwrap();
                    }
                }
            }
        } else if !ctx.references.is_empty() {
            omitted.push("references");
        }

        // Callers
        if active.as_ref().is_none_or(|s| s.contains("callers")) {
            for caller in &ctx.callers {
                let rel = caller
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&caller.file_path);
                writeln!(
                    buf,
                    "{} {}:{}",
                    caller.symbol_name,
                    rel.display(),
                    caller.line
                )
                .unwrap();
            }
        } else if !ctx.callers.is_empty() {
            omitted.push("callers");
        }

        // Callees
        if active.as_ref().is_none_or(|s| s.contains("callees")) {
            for callee in &ctx.callees {
                let rel = callee
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&callee.file_path);
                writeln!(
                    buf,
                    "{} {}:{}",
                    callee.symbol_name,
                    rel.display(),
                    callee.line
                )
                .unwrap();
            }
        } else if !ctx.callees.is_empty() {
            omitted.push("callees");
        }

        // Extends
        if active.as_ref().is_none_or(|s| s.contains("extends")) {
            for ext in &ctx.extends {
                let rel = ext
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&ext.file_path);
                writeln!(buf, "{} {}:{}", ext.symbol_name, rel.display(), ext.line).unwrap();
            }
        } else if !ctx.extends.is_empty() {
            omitted.push("extends");
        }

        // Implements
        if active.as_ref().is_none_or(|s| s.contains("implements")) {
            for imp in &ctx.implements {
                let rel = imp
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&imp.file_path);
                writeln!(buf, "{} {}:{}", imp.symbol_name, rel.display(), imp.line).unwrap();
            }
        } else if !ctx.implements.is_empty() {
            omitted.push("implements");
        }

        // Extended-by
        if active.as_ref().is_none_or(|s| s.contains("extended-by")) {
            for ext_by in &ctx.extended_by {
                let rel = ext_by
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&ext_by.file_path);
                writeln!(
                    buf,
                    "{} {}:{}",
                    ext_by.symbol_name,
                    rel.display(),
                    ext_by.line
                )
                .unwrap();
            }
        } else if !ctx.extended_by.is_empty() {
            omitted.push("extended-by");
        }

        // Implemented-by
        if active.as_ref().is_none_or(|s| s.contains("implemented-by")) {
            for impl_by in &ctx.implemented_by {
                let rel = impl_by
                    .file_path
                    .strip_prefix(project_root)
                    .unwrap_or(&impl_by.file_path);
                writeln!(
                    buf,
                    "{} {}:{}",
                    impl_by.symbol_name,
                    rel.display(),
                    impl_by.line
                )
                .unwrap();
            }
        } else if !ctx.implemented_by.is_empty() {
            omitted.push("implemented-by");
        }

        // Emit omitted line only when sections were filtered AND some were non-empty.
        if !omitted.is_empty() {
            writeln!(buf, "omitted: {}", omitted.join(", ")).unwrap();
        }
    }
    if contexts.is_empty() {
        writeln!(
            buf,
            "hint: no results found -- try a broader pattern or check spelling"
        )
        .unwrap();
    } else {
        writeln!(
            buf,
            "hint: use flow {} <target> to trace data paths",
            &contexts[0].symbol_name
        )
        .unwrap();
    }
    buf
}

/// Format and print circular dependency results to stdout.
pub fn format_circular_results(cycles: &[CircularDep], format: &OutputFormat, project_root: &Path) {
    match format {
        OutputFormat::Compact => {
            for cycle in cycles {
                let parts: Vec<String> = cycle
                    .files
                    .iter()
                    .map(|p| {
                        p.strip_prefix(project_root)
                            .unwrap_or(p)
                            .to_string_lossy()
                            .to_string()
                    })
                    .collect();
                println!("cycle {}", parts.join(" -> "));
            }
            println!("{} cycles found", cycles.len());
            if cycles.is_empty() {
                println!("hint: no results found -- try a broader pattern or check spelling");
            } else {
                // Suggest investigating the first file in the first cycle.
                let first_file = cycles[0]
                    .files
                    .first()
                    .map(|p| {
                        p.strip_prefix(project_root)
                            .unwrap_or(p)
                            .to_string_lossy()
                            .to_string()
                    })
                    .unwrap_or_default();
                println!(
                    "hint: use file-summary {} to understand the circular dependency",
                    first_file
                );
            }
        }

        OutputFormat::Table => {
            let use_color = std::io::stdout().is_terminal();
            let header = |s: &str| {
                if use_color {
                    format!("\x1b[1m{s}\x1b[0m")
                } else {
                    s.to_string()
                }
            };

            for (i, cycle) in cycles.iter().enumerate() {
                println!("{}", header(&format!("=== Cycle {} ===", i + 1)));
                // Show all but the last entry (which is the repeated first file).
                let unique_files = &cycle.files[..cycle.files.len().saturating_sub(1)];
                for path in unique_files {
                    let rel = path.strip_prefix(project_root).unwrap_or(path);
                    println!("  {}", rel.display());
                }
                println!();
            }
            println!("{} cycles found", cycles.len());
        }

        OutputFormat::Json => {
            let json_results: Vec<serde_json::Value> = cycles
                .iter()
                .map(|cycle| {
                    let files: Vec<String> = cycle
                        .files
                        .iter()
                        .map(|p| {
                            p.strip_prefix(project_root)
                                .unwrap_or(p)
                                .to_string_lossy()
                                .to_string()
                        })
                        .collect();
                    serde_json::json!({ "files": files })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&json_results).unwrap_or_default()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Structure formatter
// ---------------------------------------------------------------------------

/// Render a structure tree to an indented compact string.
///
/// Format:
/// ```text
/// src/
///   cache/
///     loader.rs
///       pub load_or_build (fn)
///   query/
///     structure.rs
///       pub file_structure (fn)
/// README.md [doc]
/// Cargo.toml [config]
/// ```
///
/// Rules:
/// - 2 spaces per depth level.
/// - Directories end with `/`.
/// - Source files show symbols indented one level deeper.
/// - Non-parsed files show `[kind_tag]` after the filename.
/// - Symbols: visibility prefix (if pub or pub(crate)), then `name (kind)`.
/// - Truncation nodes render as `... (N more items)`.
/// - No trailing newline.
pub fn format_structure_to_string(tree: &[StructureNode], _root: &Path) -> String {
    let mut lines: Vec<String> = Vec::new();
    format_nodes(tree, 0, &mut lines);
    lines.join("\n")
}

fn format_nodes(nodes: &[StructureNode], depth: usize, lines: &mut Vec<String>) {
    let indent = "  ".repeat(depth);
    for node in nodes {
        match node {
            StructureNode::Dir { name, children } => {
                lines.push(format!("{}{}/", indent, name));
                format_nodes(children, depth + 1, lines);
            }
            StructureNode::SourceFile { name, symbols } => {
                lines.push(format!("{}{}", indent, name));
                let sym_indent = "  ".repeat(depth + 1);
                for sym in symbols {
                    let prefix = match sym.visibility.as_str() {
                        "pub" => "pub ",
                        "pub(crate)" => "pub(crate) ",
                        _ => "",
                    };
                    lines.push(format!(
                        "{}{}{} ({})",
                        sym_indent, prefix, sym.name, sym.kind
                    ));
                }
            }
            StructureNode::NonParsedFile { name, kind_tag } => {
                lines.push(format!("{}{} [{}]", indent, name, kind_tag));
            }
            StructureNode::Truncated { count } => {
                lines.push(format!("{}... ({} more items)", indent, count));
            }
        }
    }
}

// ---------------------------------------------------------------------------
// FileSummary formatter
// ---------------------------------------------------------------------------

/// Render a `FileSummary` to a compact string (compact format, no trailing newline).
///
/// Format:
/// ```text
/// src/cache/loader.rs
/// role: utility
/// lines: 200
/// symbols: 3 (2 fn, 1 struct)
/// exports: load_or_build (fn), apply_staleness_diff (fn)
/// imports: 12
/// importers: 0
/// graph: leaf
/// ```
///
/// - `symbols:` shows total then parenthesized kind breakdown (only kinds with > 0 count).
/// - `exports:` lists ALL exported symbols — no truncation.
/// - `graph:` line is omitted if graph_label is None.
pub fn format_file_summary_to_string(summary: &crate::query::file_summary::FileSummary) -> String {
    use crate::query::file_summary::{FileRole, GraphLabel};

    let mut lines: Vec<String> = Vec::new();

    // Line 1: relative path
    lines.push(summary.relative_path.clone());

    // role:
    let role_str = match summary.role {
        FileRole::EntryPoint => "entry_point",
        FileRole::LibraryRoot => "library_root",
        FileRole::Test => "test",
        FileRole::Config => "config",
        FileRole::Types => "types",
        FileRole::Utility => "utility",
    };
    lines.push(format!("role: {}", role_str));

    // lines:
    lines.push(format!("lines: {}", summary.line_count));

    // symbols: N (breakdown by kind)
    if summary.symbol_count == 0 {
        lines.push("symbols: 0".to_string());
    } else if summary.symbol_kinds.is_empty() {
        lines.push(format!("symbols: {}", summary.symbol_count));
    } else {
        // Build sorted kind breakdown string (sorted alphabetically for determinism)
        let mut kinds: Vec<(&String, &usize)> = summary.symbol_kinds.iter().collect();
        kinds.sort_by_key(|(k, _)| k.as_str());
        let breakdown: String = kinds
            .iter()
            .map(|(k, count)| format!("{} {}", count, k))
            .collect::<Vec<_>>()
            .join(", ");
        lines.push(format!("symbols: {} ({})", summary.symbol_count, breakdown));
    }

    // exports:
    if summary.exports.is_empty() {
        lines.push("exports: none".to_string());
    } else {
        let export_list: String = summary
            .exports
            .iter()
            .map(|e| format!("{} ({})", e.name, e.kind))
            .collect::<Vec<_>>()
            .join(", ");
        lines.push(format!("exports: {}", export_list));
    }

    // imports: / importers:
    lines.push(format!("imports: {}", summary.import_count));
    lines.push(format!("importers: {}", summary.importer_count));

    // graph: (only if Some)
    if let Some(ref label) = summary.graph_label {
        let label_str = match label {
            GraphLabel::Hub => "hub",
            GraphLabel::Leaf => "leaf",
            GraphLabel::Bridge => "bridge",
        };
        lines.push(format!("graph: {}", label_str));
    }

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Imports formatter
// ---------------------------------------------------------------------------

/// Render a list of `ImportEntry` items to a compact string (compact format, no trailing newline).
///
/// Format:
/// ```text
/// src/cache/loader.rs imports:
/// ./envelope (internal)
/// ../graph (internal)
/// ../parser (internal)
/// rayon (external)
/// std::sync (builtin)
/// crate::query::structure [re-export] (internal)
/// ```
///
/// - If no imports, shows `{file_path} imports: none`.
/// - `[re-export]` label only appears when `is_reexport` is true.
/// - Insertion order preserved (no sorting or grouping).
pub fn format_imports_to_string(
    entries: &[crate::query::imports::ImportEntry],
    file_path: &str,
) -> String {
    use crate::query::imports::ImportCategory;

    if entries.is_empty() {
        return format!("{} imports: none", file_path);
    }

    let mut lines: Vec<String> = Vec::new();
    lines.push(format!("{} imports:", file_path));

    for entry in entries {
        let category_str = match entry.category {
            ImportCategory::Internal => "internal",
            ImportCategory::Workspace => "workspace",
            ImportCategory::External => "external",
            ImportCategory::Builtin => "builtin",
        };
        if entry.is_reexport {
            lines.push(format!(
                "{} [re-export] ({})",
                entry.specifier, category_str
            ));
        } else {
            lines.push(format!("{} ({})", entry.specifier, category_str));
        }
    }

    lines.join("\n")
}

/// Format dead code analysis results to a compact string.
///
/// Output format:
/// ```text
/// unreachable files (N):
///   src/unused_module.rs
///   src/old_helper.ts
///
/// unreferenced symbols (N in M files):
/// src/utils/helpers.rs:
///   fn unused_helper :10
///   fn old_function :25
/// src/lib/parser.ts:
///   function deadFunc :42
/// ```
///
/// Paths are relative to `root`.
pub fn format_dead_code_to_string(
    result: &crate::query::dead_code::DeadCodeResult,
    root: &Path,
) -> String {
    let mut lines: Vec<String> = Vec::new();

    // --- Unreachable files section ---
    let file_count = result.unreachable_files.len();
    lines.push(format!("unreachable files ({}):", file_count));
    if file_count == 0 {
        lines.push("  none".to_string());
    } else {
        for file_path in &result.unreachable_files {
            let rel = file_path.strip_prefix(root).unwrap_or(file_path);
            lines.push(format!("  {}", rel.display()));
        }
    }

    lines.push(String::new()); // blank line between sections

    // --- Unreferenced symbols section ---
    let total_symbols: usize = result
        .unreferenced_symbols
        .iter()
        .map(|(_, syms)| syms.len())
        .sum();
    let file_groups = result.unreferenced_symbols.len();

    lines.push(format!(
        "unreferenced symbols ({} in {} files):",
        total_symbols, file_groups
    ));

    if total_symbols == 0 {
        lines.push("  none".to_string());
    } else {
        for (file_path, syms) in &result.unreferenced_symbols {
            let rel = file_path.strip_prefix(root).unwrap_or(file_path);
            lines.push(format!("{}:", rel.display()));
            for sym in syms {
                lines.push(format!("  {} {} :{}", sym.kind, sym.name, sym.line));
            }
        }
    }

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Clone detection output
// ---------------------------------------------------------------------------

/// Format clone detection results as a compact string for CLI output (token-optimized).
///
/// Example:
/// ```text
/// Clone Groups (3 groups, 8 symbols analyzed):
/// group#1 (3 members): kind=function body=10 out=0 in=1 decorators=0
///   function process_data src/utils.rs:1 body=10
///   function transform_data src/helpers.rs:5 body=10
///   function convert_data src/convert.rs:1 body=10
/// ```
pub fn format_clones_to_string(
    result: &crate::query::clones::CloneGroupResult,
    root: &Path,
) -> String {
    let mut lines: Vec<String> = Vec::new();

    lines.push(format!(
        "Clone Groups ({} groups, {} symbols analyzed):",
        result.groups.len(),
        result.total_symbols_analyzed
    ));

    if result.groups.is_empty() {
        lines.push("  none detected".to_string());
    } else {
        for (i, group) in result.groups.iter().enumerate() {
            lines.push(format!(
                "group#{} ({} members): {}",
                i + 1,
                group.members.len(),
                group.signature
            ));
            for m in &group.members {
                let rel = m.file.strip_prefix(root).unwrap_or(&m.file);
                lines.push(format!(
                    "  {} {} {}:{} body={}",
                    m.kind,
                    m.name,
                    rel.display(),
                    m.line,
                    m.body_size,
                ));
            }
        }
    }

    lines.join("\n")
}

/// Format clone detection results as a human-readable table for CLI output.
///
/// Example:
/// ```text
/// Clone Groups (2 groups, 10 symbols analyzed)
///
/// Group #1 (3 members) -- kind=function body=10 out=0 in=1 decorators=0
///   KIND       NAME             FILE                LINE  BODY
///   function   process_data     src/utils.rs          1    10
///   function   transform_data   src/helpers.rs        5    10
/// ```
pub fn format_clones_table(result: &crate::query::clones::CloneGroupResult, root: &Path) -> String {
    let mut lines: Vec<String> = Vec::new();

    let use_color = std::io::IsTerminal::is_terminal(&std::io::stdout());

    if use_color {
        lines.push(format!(
            "\x1b[1mClone Groups ({} groups, {} symbols analyzed)\x1b[0m",
            result.groups.len(),
            result.total_symbols_analyzed
        ));
    } else {
        lines.push(format!(
            "Clone Groups ({} groups, {} symbols analyzed)",
            result.groups.len(),
            result.total_symbols_analyzed
        ));
    }

    if result.groups.is_empty() {
        lines.push(String::new());
        lines.push("  No structural clones detected.".to_string());
    } else {
        for (i, group) in result.groups.iter().enumerate() {
            lines.push(String::new());
            if use_color {
                lines.push(format!(
                    "\x1b[1mGroup #{} ({} members)\x1b[0m -- {}",
                    i + 1,
                    group.members.len(),
                    group.signature
                ));
            } else {
                lines.push(format!(
                    "Group #{} ({} members) -- {}",
                    i + 1,
                    group.members.len(),
                    group.signature
                ));
            }

            // Compute column widths
            let (name_w, file_w) = group.members.iter().fold((4usize, 4usize), |(nw, fw), m| {
                let file_len = m
                    .file
                    .strip_prefix(root)
                    .unwrap_or(&m.file)
                    .as_os_str()
                    .len();
                (nw.max(m.name.len()), fw.max(file_len))
            });

            if use_color {
                lines.push(format!(
                    "  \x1b[1m{:<12}  {:<name_w$}  {:<file_w$}  {:>4}  {:>4}\x1b[0m",
                    "KIND",
                    "NAME",
                    "FILE",
                    "LINE",
                    "BODY",
                    name_w = name_w,
                    file_w = file_w,
                ));
            } else {
                lines.push(format!(
                    "  {:<12}  {:<name_w$}  {:<file_w$}  {:>4}  {:>4}",
                    "KIND",
                    "NAME",
                    "FILE",
                    "LINE",
                    "BODY",
                    name_w = name_w,
                    file_w = file_w,
                ));
            }

            lines.push(format!(
                "  {}",
                "-".repeat(12 + 2 + name_w + 2 + file_w + 2 + 4 + 2 + 4)
            ));

            for m in &group.members {
                let rel = m.file.strip_prefix(root).unwrap_or(&m.file);
                lines.push(format!(
                    "  {:<12}  {:<name_w$}  {:<file_w$}  {:>4}  {:>4}",
                    m.kind,
                    m.name,
                    rel.display(),
                    m.line,
                    m.body_size,
                    name_w = name_w,
                    file_w = file_w,
                ));
            }
        }
    }

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Diff output
// ---------------------------------------------------------------------------

/// Format a GraphDiff as a compact string for CLI output.
///
/// Example:
/// ```text
/// files: +2 -1
/// +  src/new_module.rs
/// -  src/removed.rs
///
/// symbols: +3 -2 ~1
/// +  src/new_module.rs :: new_function
/// -  src/removed.rs :: old_function
/// ~  src/utils.rs :: parse_input (line 10 → 15, callers 3 → 5)
/// ```
pub fn format_diff_to_string(diff: &crate::query::diff::GraphDiff) -> String {
    let mut lines: Vec<String> = Vec::new();

    // Files header
    lines.push(format!(
        "files: +{} -{}",
        diff.added_files.len(),
        diff.removed_files.len()
    ));
    for f in &diff.added_files {
        lines.push(format!("+  {}", f));
    }
    for f in &diff.removed_files {
        lines.push(format!("-  {}", f));
    }

    lines.push(String::new()); // blank separator

    // Symbols header
    lines.push(format!(
        "symbols: +{} -{} ~{}",
        diff.added_symbols.len(),
        diff.removed_symbols.len(),
        diff.modified_symbols.len()
    ));
    for (file, sym) in &diff.added_symbols {
        lines.push(format!("+  {} :: {}", file, sym));
    }
    for (file, sym) in &diff.removed_symbols {
        lines.push(format!("-  {} :: {}", file, sym));
    }
    for change in &diff.modified_symbols {
        let change_str = change.changes.join(", ");
        lines.push(format!(
            "~  {} :: {} ({})",
            change.file, change.name, change_str
        ));
    }

    lines.join("\n")
}
// ---------------------------------------------------------------------------
// Unit tests for compact formatters
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;
    use crate::graph::node::{SymbolKind, SymbolVisibility};
    use crate::query::circular::CircularDep;
    use crate::query::context::{CallInfo, SymbolContext};
    use crate::query::find::FindResult;
    use crate::query::impact::ImpactResult;
    use crate::query::refs::{RefKind, RefResult};

    fn make_find_result(name: &str, path: &str, line: usize, kind: SymbolKind) -> FindResult {
        FindResult {
            symbol_name: name.to_string(),
            kind,
            file_path: PathBuf::from(path),
            line,
            line_end: 0,
            col: 0,
            is_exported: false,
            is_default: false,
            visibility: SymbolVisibility::Private,
            decorators: Vec::new(),
        }
    }

    #[test]
    fn test_find_compact_format_no_prefix() {
        let root = PathBuf::from("/project");
        let results = vec![make_find_result(
            "MyFunc",
            "/project/src/foo.ts",
            10,
            SymbolKind::Function,
        )];
        let output = format_find_to_string(&results, &root, "MyFunc");

        // Must NOT contain old prefix
        assert!(
            !output.contains("def "),
            "output should not contain 'def ' prefix"
        );
        // Must NOT contain old summary line
        assert!(
            !output.contains("definitions found"),
            "output should not contain 'definitions found' summary"
        );
        // Must contain new compact format: path:L{line} name kind
        assert!(
            output.contains("src/foo.ts:L10 MyFunc function"),
            "output should contain compact format 'src/foo.ts:L10 MyFunc function', got: {output}"
        );
    }

    #[test]
    fn test_refs_compact_format_no_prefix() {
        let root = PathBuf::from("/project");
        let results = vec![
            RefResult {
                file_path: PathBuf::from("/project/src/bar.ts"),
                ref_kind: RefKind::Import,
                symbol_name: None,
                line: None,
            },
            RefResult {
                file_path: PathBuf::from("/project/src/baz.ts"),
                ref_kind: RefKind::Call,
                symbol_name: Some("callerFn".to_string()),
                line: Some(42),
            },
        ];
        let output = format_refs_to_string(&results, &root, "MySymbol");

        // Must NOT contain old prefix
        assert!(
            !output.contains("ref "),
            "output should not contain 'ref ' prefix"
        );
        // Must NOT contain old summary line
        assert!(
            !output.contains("references found"),
            "output should not contain 'references found' summary"
        );
        // Must contain new compact formats
        assert!(
            output.contains("src/bar.ts import"),
            "output should contain import ref format, got: {output}"
        );
        assert!(
            output.contains("src/baz.ts:42 call callerFn"),
            "output should contain call ref format, got: {output}"
        );
    }

    #[test]
    fn test_impact_compact_format_no_prefix() {
        use crate::query::impact::ConfidenceTier;

        let root = PathBuf::from("/project");
        let results = vec![ImpactResult {
            file_path: PathBuf::from("/project/src/affected.ts"),
            depth: 1,
            confidence: ConfidenceTier::High,
            basis: "direct caller at depth 1".to_string(),
        }];
        let output = format_impact_to_string(&results, &root, "MySymbol");

        // Must NOT contain old prefix
        assert!(
            !output.contains("impact "),
            "output should not contain 'impact ' prefix"
        );
        // Must NOT contain old summary line
        assert!(
            !output.contains("affected files"),
            "output should not contain 'affected files' summary"
        );
        // Must contain bare path
        assert!(
            output.contains("src/affected.ts"),
            "output should contain relative path, got: {output}"
        );
        // Must contain confidence tag
        assert!(
            output.contains("[HIGH: direct caller at depth 1]"),
            "output should contain confidence tag, got: {output}"
        );
    }

    #[test]
    fn test_format_impact_with_confidence() {
        use crate::query::impact::ConfidenceTier;

        let root = PathBuf::from("/project");
        let results = vec![ImpactResult {
            file_path: PathBuf::from("/project/src/affected.ts"),
            depth: 1,
            confidence: ConfidenceTier::High,
            basis: "direct caller at depth 1".to_string(),
        }];
        let output = format_impact_to_string(&results, &root, "MySymbol");

        assert!(
            output.contains("[HIGH: direct caller at depth 1]"),
            "output should contain '[HIGH: direct caller at depth 1]', got: {output}"
        );
        assert!(
            output.contains("src/affected.ts"),
            "output should contain file path, got: {output}"
        );
        assert!(
            output.contains("(depth 1)"),
            "output should contain depth info, got: {output}"
        );
    }

    #[test]
    fn test_circular_compact_format_no_prefix() {
        let root = PathBuf::from("/project");
        let cycles = vec![CircularDep {
            files: vec![
                PathBuf::from("/project/src/a.ts"),
                PathBuf::from("/project/src/b.ts"),
                PathBuf::from("/project/src/a.ts"),
            ],
        }];
        let output = format_circular_to_string(&cycles, &root);

        // Must NOT contain old prefix
        assert!(
            !output.contains("cycle "),
            "output should not contain 'cycle ' prefix"
        );
        // Must NOT contain old summary line
        assert!(
            !output.contains("circular dependencies found"),
            "output should not contain 'circular dependencies found' summary"
        );
        // Must contain arrow chain format
        assert!(
            output.contains("src/a.ts -> src/b.ts -> src/a.ts"),
            "output should contain arrow-chain format, got: {output}"
        );
    }

    #[test]
    fn test_context_compact_format_no_delimiters() {
        let root = PathBuf::from("/project");
        let def = make_find_result("MyStruct", "/project/src/lib.rs", 5, SymbolKind::Struct);
        let caller = CallInfo {
            symbol_name: "main".to_string(),
            kind: SymbolKind::Function,
            file_path: PathBuf::from("/project/src/main.rs"),
            line: 20,
        };
        let ctx = SymbolContext {
            symbol_name: "MyStruct".to_string(),
            definitions: vec![def],
            references: vec![],
            callees: vec![],
            callers: vec![caller],
            extends: vec![],
            implements: vec![],
            extended_by: vec![],
            implemented_by: vec![],
        };
        let output = format_context_to_string(&[ctx], &root, None);

        // Must NOT contain old section delimiters
        assert!(
            !output.contains("--- "),
            "output should not contain '--- ' delimiter lines"
        );
        // Must NOT contain old symbol prefix
        assert!(
            !output.contains("symbol "),
            "output should not contain 'symbol ' prefix"
        );
        // Must NOT contain old summary
        assert!(
            !output.contains(" symbols"),
            "output should not contain 'N symbols' summary"
        );
        // Must NOT contain old "called-by " prefix
        assert!(
            !output.contains("called-by "),
            "output should not contain 'called-by ' prefix"
        );
        // Symbol name as bare header
        assert!(
            output.contains("MyStruct"),
            "output should contain symbol name, got: {output}"
        );
        // Definition in compact format: path:L{line} kind
        assert!(
            output.contains("src/lib.rs:L5 struct"),
            "output should contain definition in compact format, got: {output}"
        );
        // Caller in compact format: caller_name path:line
        assert!(
            output.contains("main src/main.rs:20"),
            "output should contain caller in compact format, got: {output}"
        );
    }

    #[test]
    fn test_truncation_format() {
        // Verify the truncation prefix string format used in server handlers.
        let limit = 20usize;
        let total = 45usize;
        let formatted_output = "src/foo.ts:10 MyFunc function\n";
        let truncated_output = format!("truncated: {}/{}\n{}", limit, total, formatted_output);

        assert!(
            truncated_output.starts_with("truncated: 20/45\n"),
            "truncated output should start with 'truncated: N/total\\n', got: {truncated_output}"
        );
        assert!(
            truncated_output.contains("src/foo.ts:10 MyFunc function"),
            "truncated output should include formatted results"
        );
    }

    // ---------------------------------------------------------------------------
    // Section scoping tests (SCOPE-01, SCOPE-02)
    // ---------------------------------------------------------------------------

    #[test]
    fn test_parse_sections_none() {
        // None input -> None output (all sections, no filtering)
        let result = parse_sections(None);
        assert!(result.is_none(), "parse_sections(None) should return None");
    }

    #[test]
    fn test_parse_sections_single() {
        // 'r' maps to "references" only
        let result = parse_sections(Some("r")).expect("should return Some");
        assert_eq!(result.len(), 1, "should have exactly 1 entry");
        assert!(result.contains("references"), "should contain 'references'");
    }

    #[test]
    fn test_parse_sections_multiple() {
        // "r,c" and "rc" both produce {"references", "callers"}
        let with_comma = parse_sections(Some("r,c")).expect("should return Some");
        assert!(
            with_comma.contains("references"),
            "should contain 'references'"
        );
        assert!(with_comma.contains("callers"), "should contain 'callers'");
        assert_eq!(with_comma.len(), 2, "should have exactly 2 entries");

        let without_sep = parse_sections(Some("rc")).expect("should return Some");
        assert!(
            without_sep.contains("references"),
            "should contain 'references'"
        );
        assert!(without_sep.contains("callers"), "should contain 'callers'");
        assert_eq!(without_sep.len(), 2, "should have exactly 2 entries");
    }

    #[test]
    fn test_parse_sections_unknown_ignored() {
        // Unknown char 'z' is silently ignored; 'r' still maps
        let result = parse_sections(Some("rz")).expect("should return Some");
        assert!(result.contains("references"), "should contain 'references'");
        assert_eq!(result.len(), 1, "unknown 'z' should be silently ignored");
    }

    fn make_call_info(name: &str, path: &str, line: usize) -> crate::query::context::CallInfo {
        crate::query::context::CallInfo {
            symbol_name: name.to_string(),
            kind: crate::graph::node::SymbolKind::Function,
            file_path: PathBuf::from(path),
            line,
        }
    }

    fn make_ref_result(path: &str, kind: RefKind) -> RefResult {
        RefResult {
            file_path: PathBuf::from(path),
            ref_kind: kind,
            symbol_name: None,
            line: None,
        }
    }

    #[test]
    fn test_context_sections_filter_references_only() {
        let root = PathBuf::from("/test/project");
        let def = make_find_result(
            "MyFunc",
            "/test/project/src/foo.rs",
            10,
            SymbolKind::Function,
        );
        let r = make_ref_result("/test/project/src/bar.rs", RefKind::Import);
        let caller = make_call_info("main", "/test/project/src/main.rs", 5);
        let ctx = SymbolContext {
            symbol_name: "MyFunc".to_string(),
            definitions: vec![def],
            references: vec![r],
            callees: vec![],
            callers: vec![caller],
            extends: vec![],
            implements: vec![],
            extended_by: vec![],
            implemented_by: vec![],
        };
        let output = format_context_to_string(&[ctx], &root, Some("r"));

        // References must appear
        assert!(
            output.contains("src/bar.rs import"),
            "references should appear when 'r' requested, got: {output}"
        );
        // Definitions always included
        assert!(
            output.contains("src/foo.rs:L10 function"),
            "definitions always included, got: {output}"
        );
        // Callers must NOT appear (filtered out)
        assert!(
            !output.contains("main src/main.rs"),
            "callers should NOT appear when only 'r' requested, got: {output}"
        );
        // Omitted line must mention callers (non-empty, filtered)
        assert!(
            output.contains("omitted: callers"),
            "omitted line should list 'callers', got: {output}"
        );
    }

    #[test]
    fn test_context_sections_definitions_always_included() {
        let root = PathBuf::from("/test/project");
        let def = make_find_result(
            "MyFunc",
            "/test/project/src/foo.rs",
            10,
            SymbolKind::Function,
        );
        let ctx = SymbolContext {
            symbol_name: "MyFunc".to_string(),
            definitions: vec![def],
            references: vec![],
            callees: vec![],
            callers: vec![],
            extends: vec![],
            implements: vec![],
            extended_by: vec![],
            implemented_by: vec![],
        };
        // Request only callers — but definitions should still be rendered
        let output = format_context_to_string(&[ctx], &root, Some("c"));

        assert!(
            output.contains("src/foo.rs:L10 function"),
            "definitions always included even when not in sections filter, got: {output}"
        );
    }

    #[test]
    fn test_context_sections_omitted_skips_empty() {
        let root = PathBuf::from("/test/project");
        let def = make_find_result(
            "MyFunc",
            "/test/project/src/foo.rs",
            10,
            SymbolKind::Function,
        );
        let r = make_ref_result("/test/project/src/bar.rs", RefKind::Import);
        // callers is EMPTY
        let ctx = SymbolContext {
            symbol_name: "MyFunc".to_string(),
            definitions: vec![def],
            references: vec![r],
            callees: vec![],
            callers: vec![], // empty — should NOT appear in omitted
            extends: vec![],
            implements: vec![],
            extended_by: vec![],
            implemented_by: vec![],
        };
        // Request only references — callers is empty so should NOT appear in omitted
        let output = format_context_to_string(&[ctx], &root, Some("r"));

        assert!(
            !output.contains("callers"),
            "empty 'callers' section should not appear in omitted line, got: {output}"
        );
    }

    #[test]
    fn test_context_no_sections_returns_all() {
        let root = PathBuf::from("/test/project");
        let def = make_find_result(
            "MyFunc",
            "/test/project/src/foo.rs",
            10,
            SymbolKind::Function,
        );
        let r = make_ref_result("/test/project/src/bar.rs", RefKind::Import);
        let caller = make_call_info("main", "/test/project/src/main.rs", 5);
        let callee = make_call_info("helper", "/test/project/src/lib.rs", 20);
        let ctx = SymbolContext {
            symbol_name: "MyFunc".to_string(),
            definitions: vec![def],
            references: vec![r],
            callees: vec![callee],
            callers: vec![caller],
            extends: vec![],
            implements: vec![],
            extended_by: vec![],
            implemented_by: vec![],
        };
        // sections=None means all sections
        let output = format_context_to_string(&[ctx], &root, None);

        // All non-empty sections must appear
        assert!(
            output.contains("src/bar.rs import"),
            "references should appear with no filter, got: {output}"
        );
        assert!(
            output.contains("main src/main.rs:5"),
            "callers should appear with no filter, got: {output}"
        );
        assert!(
            output.contains("helper src/lib.rs:20"),
            "callees should appear with no filter, got: {output}"
        );
        // No omitted line when no filter applied
        assert!(
            !output.contains("omitted:"),
            "omitted line should NOT appear when no filter, got: {output}"
        );
    }
}

// ---------------------------------------------------------------------------
// Cluster / Flow / Rename string formatters (for CLI output)
// ---------------------------------------------------------------------------

use crate::query::clusters::ClusterResult;
use crate::query::flow::FlowResult;
use crate::query::rename::RenameItem;

/// Format cluster results as a human-readable string for CLI output.
///
/// Output format:
/// ```text
/// Functional Clusters (N groups):
/// auth (3 symbols): authenticate, authorize, hash_password
/// api (2 symbols): get_users, create_user
/// ```
pub fn format_clusters_to_string(clusters: &[ClusterResult]) -> String {
    if clusters.is_empty() {
        return "Functional Clusters (0 groups): none detected.".to_string();
    }

    let mut lines: Vec<String> = Vec::new();
    lines.push(format!("Functional Clusters ({} groups):", clusters.len()));

    for c in clusters {
        let top = if c.top_symbols.is_empty() {
            "(no symbols)".to_string()
        } else {
            c.top_symbols.join(", ")
        };
        lines.push(format!("{} ({} symbols): {}", c.label, c.member_count, top));
    }

    lines.join("\n")
}

/// Format flow trace results as a human-readable string for CLI output.
///
/// Output format (paths found):
/// ```text
/// Flow Trace: entry -> target
/// A -> B -> C (2 hops)
/// A -> D -> C (2 hops)
/// ```
///
/// Output format (no paths):
/// ```text
/// Flow Trace: entry -> target
/// No direct path found between entry and target.
/// Shared dependency: SomeSharedNode
/// ```
pub fn format_flow_to_string(result: &FlowResult, entry: &str, target: &str) -> String {
    let mut lines: Vec<String> = Vec::new();
    lines.push(format!("Flow Trace: {} -> {}", entry, target));

    if result.paths.is_empty() {
        lines.push(format!(
            "No direct path found between {} and {}.",
            entry, target
        ));
        if let Some(ref shared) = result.shared_dependency {
            lines.push(format!("Shared dependency: {}", shared));
        }
    } else {
        for path in &result.paths {
            let chain = path.hops.join(" -> ");
            lines.push(format!("{} ({} hops)", chain, path.depth));
        }
    }

    lines.join("\n")
}

/// Format rename plan items as a human-readable string for CLI output.
///
/// Output format:
/// ```text
/// Rename Plan: Foo -> Bar (3 sites)
/// src/foo.rs:10  Foo -> Bar
/// src/bar.rs:5   Foo -> Bar
/// src/baz.rs:0   Foo -> Bar  [import site — verify manually]
/// ```
pub fn format_rename_to_string(items: &[RenameItem], root: &Path) -> String {
    if items.is_empty() {
        return "Rename Plan: no sites found — symbol not in graph.".to_string();
    }

    // Derive old/new from the first item (all items share the same old/new).
    let old_text = &items[0].old_text;
    let new_text = &items[0].new_text;

    let mut lines: Vec<String> = Vec::new();
    lines.push(format!(
        "Rename Plan: {} -> {} ({} sites)",
        old_text,
        new_text,
        items.len()
    ));

    for item in items {
        let rel = item.file_path.strip_prefix(root).unwrap_or(&item.file_path);
        let line_str = if item.line == 0 {
            "?".to_string()
        } else {
            item.line.to_string()
        };
        let note_str = item
            .note
            .as_deref()
            .map(|n| format!("  [{}]", n))
            .unwrap_or_default();
        lines.push(format!(
            "{}:{}  {} -> {}{}",
            rel.display(),
            line_str,
            item.old_text,
            item.new_text,
            note_str,
        ));
    }

    lines.join("\n")
}

/// Format diff-impact results as a human-readable string.
///
/// Used by the diff-impact CLI subcommand.
///
/// Output format:
/// ```text
/// ## src/foo.rs [HIGH] (5 affected files)
///   src/bar.rs (depth 1) [high: direct import]
///   src/baz.rs (depth 2) [medium: transitive]
/// ```
pub fn format_diff_impact_to_string(
    results: &[crate::query::impact::DiffImpactResult],
    root: &Path,
) -> String {
    use std::fmt::Write;
    let mut buf = String::new();

    for r in results {
        let rel = r.changed_file.strip_prefix(root).unwrap_or(&r.changed_file);
        writeln!(
            buf,
            "## {} [{}] ({} affected files)",
            rel.display(),
            r.risk,
            r.affected.len()
        )
        .unwrap();
        for a in &r.affected {
            let arel = a.file_path.strip_prefix(root).unwrap_or(&a.file_path);
            writeln!(
                buf,
                "  {} (depth {}) [{}: {}]",
                arel.display(),
                a.depth,
                a.confidence,
                a.basis
            )
            .unwrap();
        }
    }

    if buf.is_empty() {
        buf.push_str("No impact detected from changed files.");
    }
    buf
}

#[cfg(test)]
mod formatter_tests {
    use super::*;
    use std::path::PathBuf;

    use crate::query::clusters::ClusterResult;
    use crate::query::flow::{FlowPath, FlowResult};
    use crate::query::rename::RenameItem;

    #[test]
    fn test_format_clusters_to_string() {
        let clusters = vec![
            ClusterResult {
                label: "auth".to_string(),
                member_count: 3,
                top_symbols: vec![
                    "authenticate".to_string(),
                    "authorize".to_string(),
                    "hash_pw".to_string(),
                ],
            },
            ClusterResult {
                label: "api".to_string(),
                member_count: 2,
                top_symbols: vec!["get_users".to_string(), "create_user".to_string()],
            },
        ];

        let output = format_clusters_to_string(&clusters);

        assert!(
            output.contains("Functional Clusters (2 groups):"),
            "header line missing, got: {output}"
        );
        assert!(
            output.contains("auth"),
            "auth cluster missing in output: {output}"
        );
        assert!(
            output.contains("authenticate"),
            "top symbol missing in output: {output}"
        );
        assert!(
            output.contains("api"),
            "api cluster missing in output: {output}"
        );
        assert!(
            output.contains("get_users"),
            "api top symbol missing in output: {output}"
        );
        // Member counts
        assert!(
            output.contains("3 symbols"),
            "auth member count missing: {output}"
        );
        assert!(
            output.contains("2 symbols"),
            "api member count missing: {output}"
        );
    }

    #[test]
    fn test_format_flow_to_string() {
        let result = FlowResult {
            paths: vec![FlowPath {
                hops: vec!["A".to_string(), "B".to_string(), "C".to_string()],
                depth: 2,
            }],
            shared_dependency: None,
        };

        let output = format_flow_to_string(&result, "A", "C");

        assert!(
            output.contains("Flow Trace: A -> C"),
            "header missing in output: {output}"
        );
        assert!(
            output.contains("A -> B -> C"),
            "chain notation missing in output: {output}"
        );
        assert!(
            output.contains("2 hops"),
            "hop count missing in output: {output}"
        );
    }

    #[test]
    fn test_format_flow_to_string_no_path() {
        let result = FlowResult {
            paths: vec![],
            shared_dependency: Some("SharedDep".to_string()),
        };

        let output = format_flow_to_string(&result, "A", "Z");

        assert!(
            output.contains("No direct path found"),
            "no-path message missing: {output}"
        );
        assert!(
            output.contains("SharedDep"),
            "shared dependency missing: {output}"
        );
    }

    #[test]
    fn test_format_rename_to_string() {
        let root = PathBuf::from("/proj");
        let items = vec![
            RenameItem {
                file_path: root.join("src/foo.rs"),
                line: 10,
                old_text: "Foo".to_string(),
                new_text: "Bar".to_string(),
                note: None,
            },
            RenameItem {
                file_path: root.join("src/importer.rs"),
                line: 0,
                old_text: "Foo".to_string(),
                new_text: "Bar".to_string(),
                note: Some("import site — verify manually".to_string()),
            },
        ];

        let output = format_rename_to_string(&items, &root);

        assert!(
            output.contains("Rename Plan: Foo -> Bar (2 sites)"),
            "header missing: {output}"
        );
        assert!(
            output.contains("src/foo.rs"),
            "foo.rs path missing: {output}"
        );
        assert!(output.contains("10"), "line number missing: {output}");
        assert!(
            output.contains("import site"),
            "import site note missing: {output}"
        );
    }
}