calcit-cli 0.60.0

CLI command handlers, static analysis, diffing, and native FFI host injection for Calcit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
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
//! Effects graph analysis: State / Transform / Effect decomposition per definition.

use calcit_core::builtins;
use calcit_core::calcit::CalcitTypeAnnotation;
use calcit_core::calcit::NullableOrigin;
use calcit_core::calcit::{Calcit, CalcitFnArgs, CalcitLocal, CalcitProc, CalcitStructDef, CalcitSyntax, MethodKind};
use calcit_core::program::{
  ImportRule, PROGRAM_CODE_DATA, lookup_codegen_type_hint, lookup_def_code, lookup_def_schema, lookup_ns_target_in_import,
};
use cirru_edn::{Edn, EdnListView, EdnMapView, EdnTag};
use cirru_parser::Cirru;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Configuration for effects graph analysis.
#[derive(Debug, Clone, Default)]
pub struct EffectsGraphConfig {
  pub include_core: bool,
  pub max_depth: usize,
  pub ns_prefix: Option<String>,
  pub detail: EffectsGraphDetail,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EffectsGraphDetail {
  #[default]
  Summary,
  Full,
  Minimal,
}

/// A detected state item inside a definition.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StateItem {
  pub kind: String,
  pub name: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub type_hint: Option<String>,
}

/// A classified effect occurrence.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EffectItem {
  pub kind: String,
  pub target: String,
  pub count: usize,
}

/// Compressed transform summary for a definition.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TransformInfo {
  pub summary: String,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub control: Vec<String>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub calls: Vec<String>,
}

/// Per-definition decomposition node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectsGraphNode {
  pub ns: String,
  pub def: String,
  pub fqn: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub doc: Option<String>,
  pub source: String,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub state: Vec<StateItem>,
  pub transform: TransformInfo,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub effects: Vec<EffectItem>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub children: Vec<EffectsGraphNode>,
  #[serde(skip_serializing_if = "std::ops::Not::not")]
  pub circular: bool,
  #[serde(skip_serializing_if = "std::ops::Not::not")]
  pub seen: bool,
  /// True when max_depth limit prevented expanding children (analysis still present).
  #[serde(skip_serializing_if = "std::ops::Not::not")]
  pub depth_exceeded: bool,
}

/// Analysis result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectsGraphResult {
  pub entry: String,
  pub tree: EffectsGraphNode,
  pub stats: EffectsGraphStats,
  pub display: EffectsGraphDisplayMeta,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectsGraphDisplayMeta {
  /// configured `--max-depth` (0 = unlimited)
  pub max_depth_limit: usize,
  pub detail: String,
  pub include_core: bool,
  pub ns_prefix: Option<String>,
  /// package root inferred from entry or `--ns-prefix`, used to shorten display paths
  pub package_root: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectsGraphStats {
  pub reachable_count: usize,
  pub effect_sites: usize,
  pub state_items: usize,
  pub max_depth: usize,
  pub subgraph_count: usize,
}

/// Effect kind reported when a call target carries no effect declaration that the analyzer can read.
pub const UNKNOWN_EFFECT_KIND: &str = "unknown";

/// Effect tags for core syntax forms without a Snapshot entry.
const HIDDEN_CORE_SYNTAX_TAGS: &[(CalcitSyntax, &[&str])] = &[
  (CalcitSyntax::DefWasmExport, &[]),
  (CalcitSyntax::DefWasmImport, &[]),
  (CalcitSyntax::JsCast, &[]),
  (CalcitSyntax::ParseCirruEdnAs, &[]),
  (CalcitSyntax::AnyBox, &[]),
  (CalcitSyntax::AnyDowncast, &[]),
  (CalcitSyntax::AssertTraits, &["control"]),
  (CalcitSyntax::DynBox, &[]),
  (CalcitSyntax::Match, &[]),
];

/// Effect tags for compiler-internal core procs without a public Snapshot entry.
const HIDDEN_CORE_PROC_TAGS: &[(CalcitProc, &[&str])] = &[
  (CalcitProc::NativeNamedEnumNew, &[]),
  (CalcitProc::NativeStructImplTraits, &[]),
  (CalcitProc::NativeEnumImplTraits, &[]),
];

/// Effect declarations for core definitions, syntax forms and methods.
struct TagIndex {
  core: HashMap<String, HashSet<EdnTag>>,
  /// Method name (without the leading `.`) to the union of effect kinds of every core
  /// implementation; `unknown` when an implementation names a definition outside core.
  core_methods: HashMap<String, Vec<String>>,
}

impl TagIndex {
  fn load() -> Result<Self, String> {
    let snapshot = calcit_core::load_core_snapshot()?;
    let mut core = HashMap::new();
    let mut method_impls: Vec<(String, Option<String>)> = vec![];
    if let Some(file) = snapshot.files.get("calcit.core") {
      for (def, entry) in &file.defs {
        core.insert(def.clone(), entry.tags.clone());
        collect_core_method_impls(&entry.code, def, &mut method_impls);
      }
    }
    for (syntax, tags) in HIDDEN_CORE_SYNTAX_TAGS {
      let name = syntax.to_string();
      core
        .entry(name)
        .or_insert_with(|| tags.iter().map(|tag| EdnTag::new(*tag)).collect());
    }
    for (proc, tags) in HIDDEN_CORE_PROC_TAGS {
      let name = proc.as_ref().to_owned();
      core
        .entry(name)
        .or_insert_with(|| tags.iter().map(|tag| EdnTag::new(*tag)).collect());
    }

    let mut core_methods: HashMap<String, Vec<String>> = HashMap::new();
    for (method, implementation) in method_impls {
      let kinds = match implementation.as_deref().and_then(|name| core.get(name)) {
        Some(tags) => tags_to_effect_kinds(tags),
        None => vec![UNKNOWN_EFFECT_KIND.to_string()],
      };
      let entry = core_methods.entry(method).or_default();
      entry.extend(kinds);
      entry.sort();
      entry.dedup();
    }
    Ok(TagIndex { core, core_methods })
  }

  fn tags_for(&self, name: &str) -> Option<&HashSet<EdnTag>> {
    self.core.get(name)
  }
}

/// Collect `(method, implementation)` pairs from core impl tables:
/// `defimpl Name Trait (.method impl) ...` and `&impl::new Name (:: :method impl) ...`.
/// An inline implementation (e.g. `(:: :empty? $ defn &enum:empty?-impl ...)`) belongs to the
/// enclosing core definition `owner` and inherits its tags.
fn collect_core_method_impls(code: &Cirru, owner: &str, out: &mut Vec<(String, Option<String>)>) {
  let Cirru::List(items) = code else {
    return;
  };
  let leaf = |node: &Cirru| match node {
    Cirru::Leaf(text) => Some(text.to_string()),
    Cirru::List(_) => None,
  };
  match items.first().and_then(leaf).as_deref() {
    Some("defimpl") => {
      for pair in items.iter().skip(3) {
        if let Cirru::List(pair) = pair
          && let [key, value] = pair.as_slice()
          && let Some(method) = leaf(key).as_deref().and_then(|text| text.strip_prefix('.')).map(str::to_owned)
        {
          out.push((method, leaf(value).or_else(|| Some(owner.to_string()))));
        }
      }
    }
    Some("&impl::new") => {
      for pair in items.iter().skip(2) {
        if let Cirru::List(pair) = pair
          && let [head, key, value] = pair.as_slice()
          && leaf(head).as_deref() == Some("::")
          && let Some(method) = leaf(key).as_deref().and_then(|text| text.strip_prefix(':')).map(str::to_owned)
        {
          out.push((method, leaf(value).or_else(|| Some(owner.to_string()))));
        }
      }
    }
    _ => {}
  }
  for item in items {
    collect_core_method_impls(item, owner, out);
  }
}

/// Method names implemented outside `calcit.core` (project and module `defimpl` / `&impl::new`).
/// A call to one of these methods may dispatch to code whose effects are not declared at the
/// call site, so it is reported as `unknown`.
fn collect_program_method_names() -> HashSet<String> {
  let mut names = HashSet::new();
  let Ok(program_code) = PROGRAM_CODE_DATA.read() else {
    return names;
  };
  for (ns, file) in program_code.iter() {
    if ns.as_ref() == "calcit.core" {
      continue;
    }
    for entry in file.defs.values() {
      collect_program_methods_in(&entry.code, &mut names);
    }
  }
  names
}

fn collect_program_methods_in(code: &Calcit, names: &mut HashSet<String>) {
  match code {
    Calcit::List(list) => {
      let head = list.first().and_then(extract_symbol_name);
      match head.as_deref() {
        Some("defimpl") => {
          for pair in list.iter().skip(3) {
            if let Calcit::List(pair) = pair
              && let Some(Calcit::Method(name, _)) = pair.first()
            {
              names.insert(name.to_string());
            }
          }
        }
        Some("&impl::new") => {
          for pair in list.iter().skip(2) {
            if let Calcit::List(pair) = pair
              && let Some(Calcit::Tag(tag)) = pair.get(1)
            {
              names.insert(tag.ref_str().to_string());
            }
          }
        }
        _ => {}
      }
      for item in list.iter() {
        collect_program_methods_in(item, names);
      }
    }
    Calcit::Fn { info, .. } => {
      for expr in info.body.iter() {
        collect_program_methods_in(expr, names);
      }
    }
    Calcit::Macro { info, .. } => {
      for expr in info.body.iter() {
        collect_program_methods_in(expr, names);
      }
    }
    _ => {}
  }
}

struct DefAnalysis {
  /// Lexical scopes entered while walking. Each `defn` / `defmacro` / `fn` pushes its parameters
  /// (`true`); each binding form pushes the names it binds (`false`), shadowing outer parameters.
  /// Calling a parameter calls a function value supplied by the caller, whose effects are `unknown`.
  scopes: Vec<HashMap<String, bool>>,
  state: Vec<StateItem>,
  effects: HashMap<String, EffectItem>,
  transform: TransformInfo,
  /// Effect kinds declared by `:tags` on project/module definitions this one calls, keyed by `ns/def`.
  declared: HashMap<String, Vec<String>>,
}

pub struct EffectsGraphAnalyzer {
  config: EffectsGraphConfig,
  tag_index: TagIndex,
  program_methods: HashSet<String>,
  visited: HashSet<String>,
  expanded: HashMap<String, bool>,
  reachable: HashSet<String>,
  max_depth: usize,
  total_effect_sites: usize,
  total_state_items: usize,
}

impl EffectsGraphAnalyzer {
  pub fn new(config: EffectsGraphConfig) -> Result<Self, String> {
    Ok(EffectsGraphAnalyzer {
      config,
      tag_index: TagIndex::load()?,
      program_methods: collect_program_method_names(),
      visited: HashSet::new(),
      expanded: HashMap::new(),
      reachable: HashSet::new(),
      max_depth: 0,
      total_effect_sites: 0,
      total_state_items: 0,
    })
  }

  pub fn analyze(&mut self, entry_ns: &str, entry_def: &str) -> Result<EffectsGraphResult, String> {
    let entry = format!("{entry_ns}/{entry_def}");
    let mut tree = self.build_node(entry_ns, entry_def, 0)?;
    if let Some(ref prefix) = self.config.ns_prefix {
      tree = prune_tree_by_ns_prefix(tree, prefix);
    }

    let subgraph_count = count_subgraph_nodes(&tree);

    let stats = EffectsGraphStats {
      reachable_count: self.reachable.len(),
      effect_sites: self.total_effect_sites,
      state_items: self.total_state_items,
      max_depth: self.max_depth,
      subgraph_count,
    };

    let package_root = infer_package_root(entry_ns, &self.config.ns_prefix);

    let display = EffectsGraphDisplayMeta {
      max_depth_limit: self.config.max_depth,
      detail: match self.config.detail {
        EffectsGraphDetail::Full => "full".into(),
        EffectsGraphDetail::Minimal => "minimal".into(),
        EffectsGraphDetail::Summary => "summary".into(),
      },
      include_core: self.config.include_core,
      ns_prefix: self.config.ns_prefix.clone(),
      package_root,
    };

    Ok(EffectsGraphResult {
      entry,
      tree,
      stats,
      display,
    })
  }

  fn build_node(&mut self, ns: &str, def: &str, depth: usize) -> Result<EffectsGraphNode, String> {
    let fqn = format!("{ns}/{def}");
    if depth > self.max_depth {
      self.max_depth = depth;
    }

    if self.visited.contains(&fqn) {
      return Ok(EffectsGraphNode {
        ns: ns.to_string(),
        def: def.to_string(),
        fqn,
        doc: None,
        source: self.source_type(ns),
        state: vec![],
        transform: TransformInfo::default(),
        effects: vec![],
        children: vec![],
        circular: true,
        seen: false,
        depth_exceeded: false,
      });
    }

    if let Some(&had_children) = self.expanded.get(&fqn) {
      return Ok(EffectsGraphNode {
        ns: ns.to_string(),
        def: def.to_string(),
        fqn,
        doc: None,
        source: self.source_type(ns),
        state: vec![],
        transform: TransformInfo::default(),
        effects: vec![],
        children: vec![],
        circular: false,
        seen: had_children,
        depth_exceeded: false,
      });
    }

    self.visited.insert(fqn.clone());
    self.reachable.insert(fqn.clone());

    let program_code = PROGRAM_CODE_DATA.read().map_err(|e| format!("Failed to read program code: {e}"))?;
    let (code, doc, schema_return) = match program_code.get(ns) {
      Some(file) => match file.defs.get(def) {
        Some(entry) => {
          let doc = if entry.doc.is_empty() { None } else { Some(entry.doc.to_string()) };
          let return_hint = format_type_hint(&entry.schema);
          (Some(entry.code.clone()), doc, return_hint)
        }
        None => (None, None, None),
      },
      None => (None, None, None),
    };

    let mut children = vec![];
    let mut analysis = DefAnalysis {
      scopes: vec![],
      state: vec![],
      effects: HashMap::new(),
      transform: TransformInfo::default(),
      declared: HashMap::new(),
    };

    let depth_exceeded = self.config.max_depth > 0 && depth >= self.config.max_depth;

    if let Some(code) = code {
      let call_refs = extract_call_targets(&code, ns);
      // Effects declared on called project/module definitions are read while the program is locked.
      for (call_ns, call_def) in &call_refs {
        if call_ns == "calcit.core" {
          continue;
        }
        if let Some(entry) = program_code.get(call_ns.as_str()).and_then(|file| file.defs.get(call_def.as_str())) {
          let kinds = tags_to_effect_kinds(&entry.tags.iter().cloned().collect());
          if !kinds.is_empty() {
            analysis.declared.insert(format!("{call_ns}/{call_def}"), kinds);
          }
        }
      }
      // Always analyze the code for state/effects/transform, even at max depth
      self.analyze_code(&code, ns, doc.as_deref(), &mut analysis);
      if def.starts_with('*') {
        enrich_atom_def_state(ns, def, &mut analysis.state);
      }
      if let Some(hint) = schema_return {
        analysis.state.push(StateItem {
          kind: "return".into(),
          name: "return".into(),
          type_hint: Some(hint),
        });
      }

      drop(program_code);

      // Only build children if not at max depth
      if !depth_exceeded {
        for (call_ns, call_def) in call_refs {
          if !self.config.include_core && self.is_core_ns(&call_ns) {
            continue;
          }
          if call_ns == ns && call_def == def {
            continue;
          }
          children.push(self.build_node(&call_ns, &call_def, depth + 1)?);
        }
      }
    } else {
      drop(program_code);
    }

    self.visited.remove(&fqn);
    self.expanded.insert(fqn.clone(), !children.is_empty());

    self.total_effect_sites += analysis.effects.values().map(|e| e.count).sum::<usize>();
    self.total_state_items += analysis.state.len();

    let effects: Vec<EffectItem> = {
      let mut items: Vec<EffectItem> = analysis.effects.into_values().collect();
      items.sort_by(|a, b| a.kind.cmp(&b.kind).then(a.target.cmp(&b.target)));
      items
    };

    Ok(EffectsGraphNode {
      ns: ns.to_string(),
      def: def.to_string(),
      fqn,
      doc,
      source: self.source_type(ns),
      state: analysis.state,
      transform: analysis.transform,
      effects,
      children,
      circular: false,
      seen: false,
      depth_exceeded,
    })
  }

  fn analyze_code(&self, code: &Calcit, current_ns: &str, doc: Option<&str>, out: &mut DefAnalysis) {
    match code {
      Calcit::Fn { info, .. } => {
        extract_fn_params(&info.args, &info.arg_types, &mut out.state);
        for expr in info.body.iter() {
          self.walk_expr(expr, current_ns, out, 0);
        }
        if out.transform.summary.is_empty() {
          out.transform.summary = doc_or_generated_summary(doc, &out.transform.control, &out.transform.calls);
        }
      }
      Calcit::Macro { info, .. } => {
        for expr in info.body.iter() {
          self.walk_expr(expr, current_ns, out, 0);
        }
        if out.transform.summary.is_empty() {
          out.transform.summary = doc_or_generated_summary(doc, &out.transform.control, &out.transform.calls);
        }
      }
      _ => {
        self.walk_expr(code, current_ns, out, 0);
        if out.transform.summary.is_empty() {
          out.transform.summary = doc_or_generated_summary(doc, &out.transform.control, &out.transform.calls);
        }
      }
    }
  }

  fn walk_expr(&self, code: &Calcit, current_ns: &str, out: &mut DefAnalysis, depth: usize) {
    if let Calcit::List(list) = code {
      // A parameter list is not a call; its names form a new scope for the body.
      let args_index = list.first().and_then(fn_form_args_index);
      let binding = list.first().and_then(binding_form_kind);
      let mut pushed_scope = false;
      if let Some(Calcit::List(args)) = args_index.and_then(|index| list.get(index)) {
        let mut scope = HashMap::new();
        collect_bound_names(&Calcit::List(args.clone()), true, &mut scope);
        out.scopes.push(scope);
        pushed_scope = true;
      }
      // `(receiver .method args)` is a method call on `receiver`, not a call of `receiver`.
      let call_head = match (list.first(), list.get(1)) {
        (Some(first), Some(method @ Calcit::Method(..))) if !matches!(first, Calcit::Method(..)) => Some(method),
        (first, _) => first,
      };
      if let Some(head) = call_head {
        self.inspect_call_head(head, Some(list), current_ns, out);
        if depth < 3 {
          record_control_head(head, &mut out.transform.control);
        }
      }
      // Binding pairs such as `(x value)` in `let` / `loop` / `&let` are not calls either;
      // only their values are walked, and the bound names shadow outer parameters in the body.
      let bindings_index = binding.as_ref().map(|_| 1);
      // Clauses such as `(pattern body)` in `case` / `match` / `cond` are not calls; walk their parts.
      let clauses_from = list.first().and_then(clause_form_start);
      for (index, item) in list.iter().enumerate() {
        if Some(index) == args_index {
          continue;
        }
        if Some(index) == bindings_index
          && let Some(kind) = &binding
        {
          let mut scope = HashMap::new();
          match kind {
            // `let[] (a b) value`: names only, the value comes next.
            BindingForm::Destructure => {
              collect_bound_names(item, false, &mut scope);
            }
            BindingForm::Single | BindingForm::Many => {
              let pairs: Vec<&Calcit> = match (kind, item) {
                (BindingForm::Many, Calcit::List(bindings)) => bindings.iter().collect(),
                _ => vec![item],
              };
              for pair in pairs {
                if let Calcit::List(pair) = pair {
                  for value in pair.iter().skip(1) {
                    self.walk_expr(value, current_ns, out, depth + 1);
                  }
                  if let Some(name) = pair.first() {
                    collect_bound_names(name, false, &mut scope);
                  }
                }
              }
            }
          }
          out.scopes.push(scope);
          pushed_scope = true;
          continue;
        }
        if clauses_from.is_some_and(|start| index >= start)
          && let Calcit::List(clause) = item
        {
          for part in clause.iter() {
            self.walk_expr(part, current_ns, out, depth + 1);
          }
          continue;
        }
        self.walk_expr(item, current_ns, out, depth + 1);
      }
      if pushed_scope {
        out.scopes.pop();
      }
      return;
    }

    match code {
      Calcit::Fn { info, .. } => {
        for expr in info.body.iter() {
          self.walk_expr(expr, current_ns, out, depth);
        }
      }
      Calcit::Macro { info, .. } => {
        for expr in info.body.iter() {
          self.walk_expr(expr, current_ns, out, depth);
        }
      }
      Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => {
        self.walk_expr(code, current_ns, out, depth);
      }
      Calcit::Enum(enum_value) => {
        for item in enum_value.extra.iter() {
          self.walk_expr(item, current_ns, out, depth);
        }
      }
      Calcit::Map(map) => {
        for (k, v) in map.iter() {
          self.walk_expr(k, current_ns, out, depth);
          self.walk_expr(v, current_ns, out, depth);
        }
      }
      Calcit::Set(set) => {
        for item in set.iter() {
          self.walk_expr(item, current_ns, out, depth);
        }
      }
      _ => {}
    }
  }

  fn inspect_call_head(&self, head: &Calcit, list: Option<&calcit_core::calcit::CalcitList>, current_ns: &str, out: &mut DefAnalysis) {
    if let Calcit::Symbol { sym, .. } = head
      && out.is_param(sym)
    {
      let key = format!("{UNKNOWN_EFFECT_KIND}::{sym}");
      out
        .effects
        .entry(key)
        .and_modify(|item| item.count += 1)
        .or_insert_with(|| EffectItem {
          kind: UNKNOWN_EFFECT_KIND.to_string(),
          target: sym.to_string(),
          count: 1,
        });
      return;
    }
    let Some(call) = resolve_call_head(head, current_ns) else {
      return;
    };

    if let CallHead::Core(name) = &call
      && is_state_operator(name)
    {
      let target = extract_state_target(list, name);
      record_state_operator(name, &target, list, current_ns, &mut out.state);
      if matches!(name.as_str(), "defref" | "ref" | "reset!" | "swap!" | "deref" | "set!") {
        return;
      }
    }

    let (mut kinds, target) = self.classify_call_head(&call);
    // `hint-fn` carries type hints in general; only the enclosing function's own schema with
    // `:async true` declares async, the same contract the JavaScript lowering checks.
    if matches!(&call, CallHead::Core(name) if name == "hint-fn") && !list.is_some_and(hint_marks_async) {
      kinds.clear();
    }
    for kind in kinds {
      let key = format!("{kind}::{target}");
      out
        .effects
        .entry(key)
        .and_modify(|item| item.count += 1)
        .or_insert_with(|| EffectItem {
          kind,
          target: target.clone(),
          count: 1,
        });
    }

    if let Some((call_ns, call_def)) = resolve_def_call(head, current_ns) {
      let fqn = format!("{call_ns}/{call_def}");
      if let Some(kinds) = out.declared.get(&fqn).cloned() {
        for kind in kinds {
          let key = format!("{kind}::{fqn}");
          out
            .effects
            .entry(key)
            .and_modify(|item| item.count += 1)
            .or_insert_with(|| EffectItem {
              kind,
              target: fqn.clone(),
              count: 1,
            });
        }
      }
      if !is_meaningful_call_target(&call_ns, &call_def, self.config.include_core) {
        return;
      }
      let target = format!("{call_ns}/{call_def}");
      if !out.transform.calls.contains(&target) {
        out.transform.calls.push(target);
      }
    }
  }

  /// Effect kinds of one call site, derived only from declarations:
  /// core definition tags, registered proc descriptor tags and core impl tables.
  /// Calls into project/module definitions add nothing here unless the callee declares effect
  /// `:tags` (see `DefAnalysis::declared`); the callee body's own effects are reported on its node.
  fn classify_call_head(&self, call: &CallHead) -> (Vec<String>, String) {
    match call {
      CallHead::Core(name) => (classify_call(name, self.tag_index.tags_for(name)), name.clone()),
      CallHead::Registered(name) => (classify_call(name, None), name.clone()),
      CallHead::Def(..) => (vec![], String::new()),
      CallHead::MissingDef(ns, def) => (vec![UNKNOWN_EFFECT_KIND.to_string()], format!("{ns}/{def}")),
      CallHead::JsGlobal(name) => (vec!["interop/js".to_string()], name.clone()),
      CallHead::Method(name, kind) => (self.classify_method(name, kind), method_call_label(name, kind)),
    }
  }

  fn classify_method(&self, name: &str, kind: &MethodKind) -> Vec<String> {
    match kind {
      // Field and tag reads do not dispatch to code.
      MethodKind::Access
      | MethodKind::AccessOptional
      | MethodKind::TagAccess
      | MethodKind::ExternalAccess(_)
      | MethodKind::ExternalGet(_) => {
        vec![]
      }
      MethodKind::InvokeNative | MethodKind::InvokeNativeOptional | MethodKind::ExternalSet(_) | MethodKind::ExternalInvoke(_) => {
        vec!["interop/js".to_string()]
      }
      MethodKind::Invoke(_) => {
        if self.program_methods.contains(name) {
          return vec![UNKNOWN_EFFECT_KIND.to_string()];
        }
        match self.tag_index.core_methods.get(name) {
          Some(kinds) => kinds.clone(),
          None => vec![UNKNOWN_EFFECT_KIND.to_string()],
        }
      }
    }
  }

  fn source_type(&self, ns: &str) -> String {
    if self.is_core_ns(ns) {
      "core".into()
    } else if ns.starts_with("js/") {
      "external".into()
    } else {
      "project".into()
    }
  }

  fn is_core_ns(&self, ns: &str) -> bool {
    ns == "calcit.core" || ns.starts_with("calcit.")
  }
}

fn extract_fn_params(
  args: &CalcitFnArgs,
  arg_types: &[std::sync::Arc<calcit_core::calcit::CalcitTypeAnnotation>],
  state: &mut Vec<StateItem>,
) {
  match args {
    CalcitFnArgs::Args(indices) => {
      for (idx, local_idx) in indices.iter().enumerate() {
        state.push(StateItem {
          kind: "param".into(),
          name: CalcitLocal::read_name(*local_idx),
          type_hint: arg_types.get(idx).map(|t| t.to_string()),
        });
      }
    }
    CalcitFnArgs::MarkedArgs(labels) => {
      let mut arg_idx = 0usize;
      for label in labels {
        if let calcit_core::calcit::CalcitArgLabel::Idx(local_idx) = label {
          state.push(StateItem {
            kind: "param".into(),
            name: label.to_string(),
            type_hint: arg_types.get(arg_idx).map(|t| t.to_string()),
          });
          arg_idx += 1;
          let _ = local_idx;
        }
      }
    }
  }
}

/// A call head resolved without guessing from its spelling.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CallHead {
  /// `calcit.core` definition, builtin proc or syntax.
  Core(String),
  /// Proc registered by the host (platform APIs, dylib bindings).
  Registered(String),
  /// Project or module definition with loaded code; analyzed as its own call-graph node.
  Def(String, String),
  /// Qualified reference whose definition is not loaded.
  MissingDef(String, String),
  /// JavaScript global accessed through the `js/` namespace or a JS default import.
  JsGlobal(String),
  /// Method dispatch `.name`.
  Method(String, MethodKind),
}

impl DefAnalysis {
  /// Whether `name` resolves to a parameter in the innermost scope that binds it.
  fn is_param(&self, name: &str) -> bool {
    self.scopes.iter().rev().find_map(|scope| scope.get(name).copied()).unwrap_or(false)
  }
}

/// True when a one-argument `hint-fn` schema marks the enclosing function async.
/// Nested function types (such as an async callback parameter) do not count.
fn hint_marks_async(list: &calcit_core::calcit::CalcitList) -> bool {
  CalcitTypeAnnotation::hint_form_marks_async(&Calcit::List(std::sync::Arc::new(list.clone())))
}

/// Collect symbols bound by a parameter list, a binding name or a destructuring pattern.
fn collect_bound_names(form: &Calcit, is_param: bool, scope: &mut HashMap<String, bool>) {
  match form {
    Calcit::Symbol { sym, .. } if !matches!(sym.as_ref(), "&" | "?" | "[]" | "{}" | ",") => {
      scope.insert(sym.to_string(), is_param);
    }
    Calcit::Local(local) => {
      scope.insert(local.sym.to_string(), is_param);
    }
    Calcit::List(items) => {
      for item in items.iter() {
        collect_bound_names(item, is_param, scope);
      }
    }
    _ => {}
  }
}

/// Index of the first clause in `case value clauses...`, `match value clauses...` and
/// `cond clauses...` forms.
fn clause_form_start(head: &Calcit) -> Option<usize> {
  let name = match head {
    Calcit::Symbol { sym, .. } => sym.to_string(),
    Calcit::Syntax(syntax, _) => syntax.to_string(),
    _ => return None,
  };
  match name.as_str() {
    "case" | "match" | "tag-match" | "struct-match" => Some(2),
    "cond" => Some(1),
    _ => None,
  }
}

enum BindingForm {
  /// `&let (name value) ...`, `if-let (name value) ...`, `when-let (name value) ...`,
  /// `&doseq (name xs) ...`, `doseq (name xs) ...`
  Single,
  /// `let[] (a b) value ...`
  Destructure,
  /// `let ((name value) ...) ...`, `loop ((name value) ...) ...`
  Many,
}

fn binding_form_kind(head: &Calcit) -> Option<BindingForm> {
  let name = match head {
    Calcit::Symbol { sym, .. } => sym.to_string(),
    Calcit::Syntax(syntax, _) => syntax.to_string(),
    _ => return None,
  };
  match name.as_str() {
    "&let" | "if-let" | "when-let" | "&doseq" | "doseq" => Some(BindingForm::Single),
    "let[]" | "let{}" => Some(BindingForm::Destructure),
    "let" | "loop" => Some(BindingForm::Many),
    _ => None,
  }
}

/// Index of the parameter list in `defn name (args) ...`, `defmacro name (args) ...` and
/// `fn (args) ...` forms.
fn fn_form_args_index(head: &Calcit) -> Option<usize> {
  let name = match head {
    Calcit::Symbol { sym, .. } => sym.to_string(),
    Calcit::Syntax(syntax, _) => syntax.to_string(),
    _ => return None,
  };
  match name.as_str() {
    "defn" | "defmacro" => Some(2),
    "fn" => Some(1),
    _ => None,
  }
}

/// Display a method call with the same prefix the source uses (`.name`, `.!name`, `.?!name`).
fn method_call_label(name: &str, kind: &MethodKind) -> String {
  let prefix = match kind {
    MethodKind::InvokeNative => ".!",
    MethodKind::InvokeNativeOptional => ".?!",
    MethodKind::Access => ".-",
    MethodKind::AccessOptional => ".?-",
    MethodKind::TagAccess => ".:",
    _ => ".",
  };
  format!("{prefix}{name}")
}

fn def_call_head(ns: &str, def: &str) -> CallHead {
  if ns == "calcit.core" {
    return CallHead::Core(def.to_string());
  }
  // JS module imports keep their string namespace, e.g. `(|os :as os)`.
  if let Some(module) = ns.strip_prefix('|').or_else(|| ns.strip_prefix('"')) {
    return CallHead::JsGlobal(format!("{module}/{def}"));
  }
  let loaded = PROGRAM_CODE_DATA
    .read()
    .is_ok_and(|program_code| program_code.get(ns).is_some_and(|file| file.defs.contains_key(def)));
  if loaded {
    CallHead::Def(ns.to_string(), def.to_string())
  } else {
    CallHead::MissingDef(ns.to_string(), def.to_string())
  }
}

/// Resolve a call head to what it refers to. Bare symbols that resolve to nothing are local
/// bindings or parameters (calls through function values), which are not classified.
fn resolve_call_head(head: &Calcit, current_ns: &str) -> Option<CallHead> {
  match head {
    Calcit::Proc(proc) => Some(CallHead::Core(proc.to_string())),
    Calcit::Syntax(syntax, _) => Some(CallHead::Core(syntax.to_string())),
    Calcit::Registered(name) => Some(CallHead::Registered(name.to_string())),
    Calcit::Import(import) => Some(def_call_head(&import.ns, &import.def)),
    Calcit::Method(name, kind) => Some(CallHead::Method(name.to_string(), kind.clone())),
    Calcit::Fn { info, .. } => info
      .def_ref
      .as_ref()
      .map(|def_ref| def_call_head(&def_ref.def_ns, &def_ref.def_name)),
    Calcit::Symbol { sym, .. } => resolve_symbol_head(sym, current_ns),
    _ => None,
  }
}

fn resolve_symbol_head(sym: &str, current_ns: &str) -> Option<CallHead> {
  let program_code = PROGRAM_CODE_DATA.read().ok()?;
  if let Some(file) = program_code.get(current_ns) {
    if file.defs.contains_key(sym) {
      drop(program_code);
      return Some(def_call_head(current_ns, sym));
    }
    if let Some(rule) = file.import_map.get(sym) {
      let rule = rule.clone();
      drop(program_code);
      return match &*rule {
        ImportRule::NsReferDef(ns, def) => Some(def_call_head(ns, def)),
        ImportRule::NsDefault(ns) => Some(CallHead::JsGlobal(format!("{}/default", ns.trim_start_matches(['|', '"'])))),
        ImportRule::NsAs(_) => None,
      };
    }
  }
  if program_code.get("calcit.core").is_some_and(|core| core.defs.contains_key(sym)) {
    return Some(CallHead::Core(sym.to_string()));
  }
  if CalcitProc::parse_source_proc(sym).is_some() {
    return Some(CallHead::Core(sym.to_string()));
  }
  if builtins::is_registered_proc(sym) {
    return Some(CallHead::Registered(sym.to_string()));
  }
  if sym.starts_with("js/") {
    return Some(CallHead::JsGlobal(sym.to_string()));
  }
  let (alias, def) = sym.split_once('/')?;
  if alias.is_empty() || def.is_empty() {
    return None;
  }
  let target_ns = match program_code.get(current_ns).and_then(|file| file.import_map.get(alias)) {
    Some(rule) => match &**rule {
      ImportRule::NsAs(ns) => ns.to_string(),
      ImportRule::NsDefault(ns) => return Some(CallHead::JsGlobal(format!("{}/{def}", ns.trim_start_matches(['|', '"'])))),
      ImportRule::NsReferDef(..) => return None,
    },
    None => alias.to_string(),
  };
  drop(program_code);
  Some(def_call_head(&target_ns, def))
}

fn resolve_def_call(head: &Calcit, current_ns: &str) -> Option<(String, String)> {
  if !matches!(head, Calcit::Import(_) | Calcit::Symbol { .. } | Calcit::Fn { .. }) {
    return None;
  }
  match resolve_call_head(head, current_ns)? {
    CallHead::Def(ns, def) | CallHead::MissingDef(ns, def) => Some((ns, def)),
    CallHead::Core(name) => {
      let program_code = PROGRAM_CODE_DATA.read().ok()?;
      let is_core_def = program_code
        .get("calcit.core")
        .is_some_and(|core| core.defs.contains_key(name.as_str()));
      is_core_def.then(|| ("calcit.core".to_string(), name))
    }
    _ => None,
  }
}

fn extract_call_targets(code: &Calcit, current_ns: &str) -> Vec<(String, String)> {
  let mut calls = vec![];
  extract_call_targets_recursive(code, current_ns, &mut calls);
  let mut seen = HashSet::new();
  calls.retain(|item| seen.insert(item.clone()));
  calls
}

fn extract_call_targets_recursive(code: &Calcit, current_ns: &str, calls: &mut Vec<(String, String)>) {
  if let Some(pair) = resolve_def_call_from_expr(code, current_ns) {
    calls.push(pair);
  }
  match code {
    Calcit::List(list) => {
      let _ = list.traverse_result::<String>(&mut |item| {
        extract_call_targets_recursive(item, current_ns, calls);
        Ok(())
      });
    }
    Calcit::Fn { info, .. } => {
      for expr in info.body.iter() {
        extract_call_targets_recursive(expr, current_ns, calls);
      }
    }
    Calcit::Macro { info, .. } => {
      for expr in info.body.iter() {
        extract_call_targets_recursive(expr, current_ns, calls);
      }
    }
    Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => {
      extract_call_targets_recursive(code, current_ns, calls);
    }
    Calcit::Enum(enum_value) => {
      for item in enum_value.extra.iter() {
        extract_call_targets_recursive(item, current_ns, calls);
      }
    }
    Calcit::Map(map) => {
      for (k, v) in map.iter() {
        extract_call_targets_recursive(k, current_ns, calls);
        extract_call_targets_recursive(v, current_ns, calls);
      }
    }
    Calcit::Set(set) => {
      for item in set.iter() {
        extract_call_targets_recursive(item, current_ns, calls);
      }
    }
    _ => {}
  }
}

fn resolve_def_call_from_expr(code: &Calcit, current_ns: &str) -> Option<(String, String)> {
  match code {
    Calcit::Import(import) => Some((import.ns.to_string(), import.def.to_string())),
    Calcit::List(list) => list.first().and_then(|head| resolve_def_call(head, current_ns)),
    _ => None,
  }
}

fn is_state_operator(name: &str) -> bool {
  matches!(
    name,
    "defref" | "reset!" | "swap!" | "ref" | "deref" | "add-watch!" | "remove-watch!" | "set!"
  )
}

fn record_state_operator(
  op_name: &str,
  target: &str,
  list: Option<&calcit_core::calcit::CalcitList>,
  current_ns: &str,
  state: &mut Vec<StateItem>,
) {
  let kind = match op_name {
    "defref" | "ref" => "atom-def",
    "reset!" | "swap!" => "atom-write",
    "add-watch!" | "remove-watch!" => "watch",
    "deref" => "atom-read",
    "set!" => "local-write",
    _ => "state",
  };
  let type_hint = if kind == "atom-def" {
    list
      .and_then(|items| ref_constructor_init_index(op_name).and_then(|idx| items.get(idx)))
      .and_then(|init| summarize_init_expr(init, current_ns))
      .map(|raw| finalize_schema_hint(&raw, current_ns))
      .or_else(|| lookup_atom_schema(current_ns, target))
  } else if kind == "watch" && target.starts_with('*') {
    lookup_atom_schema(current_ns, target)
  } else {
    None
  };
  state.push(StateItem {
    kind: kind.into(),
    name: target.into(),
    type_hint,
  });
}

/// Extract the atom name from a state-operator call like `(swap! *store ...)`.
fn extract_state_target(list: Option<&calcit_core::calcit::CalcitList>, op_name: &str) -> String {
  let Some(list) = list else {
    return op_name.to_string();
  };
  match op_name {
    "swap!" | "reset!" | "deref" | "add-watch!" | "remove-watch!" | "set!" => {
      list.get(1).and_then(extract_symbol_name).unwrap_or_else(|| op_name.to_string())
    }
    "defref" => list.get(1).and_then(extract_symbol_name).unwrap_or_else(|| "?".to_string()),
    // A local `(ref init)` has no name of its own; index 1 is the initializer.
    "ref" => "?".to_string(),
    _ => op_name.to_string(),
  }
}

/// Position of the initial value in a Ref constructor call:
/// `(defref name init)` takes it at index 2,
/// local `(ref init)` at index 1.
fn ref_constructor_init_index(op_name: &str) -> Option<usize> {
  match op_name {
    "defref" => Some(2),
    "ref" => Some(1),
    _ => None,
  }
}

fn extract_symbol_name(calcit: &Calcit) -> Option<String> {
  match calcit {
    Calcit::Symbol { sym, .. } => Some(sym.to_string()),
    Calcit::Str(s) => Some(s.to_string()),
    _ => None,
  }
}

fn record_control_head(head: &Calcit, control: &mut Vec<String>) {
  let label = match head {
    Calcit::Syntax(CalcitSyntax::If, _) => Some("if"),
    Calcit::Syntax(CalcitSyntax::CoreLet, _) => Some("let"),
    Calcit::Syntax(CalcitSyntax::Match, _) => Some("match"),
    Calcit::Syntax(CalcitSyntax::Try, _) => Some("try"),
    Calcit::Proc(CalcitProc::Foldl) => Some("foldl"),
    Calcit::Symbol { sym, .. } if matches!(sym.as_ref(), "fold" | "foldl" | "map" | "filter") => Some(sym.as_ref()),
    _ => None,
  };
  if let Some(name) = label {
    control.push(name.to_string());
  }
}

/// Effect kinds for a core or host-registered call target, taken only from declared tags.
///
/// Registered host procs use their descriptor tags; a descriptor that declares no tags at all is
/// reported as `unknown`. Core definitions use their Snapshot `:tags` (or the hidden proc table);
/// a core definition without effect tags is effect-free by contract.
pub fn classify_call(name: &str, tags: Option<&HashSet<EdnTag>>) -> Vec<String> {
  if let Some(tag_set) = tags {
    return tags_to_effect_kinds(tag_set);
  }
  if let Some(descriptor) = builtins::registered_proc_descriptor(name) {
    if descriptor.tags.is_empty() {
      return vec![UNKNOWN_EFFECT_KIND.to_string()];
    }
    return tags_to_effect_kinds(&descriptor.tags);
  }
  vec![UNKNOWN_EFFECT_KIND.to_string()]
}

fn tags_to_effect_kinds(tags: &HashSet<EdnTag>) -> Vec<String> {
  let mut kinds = vec![];
  if tags.contains(&EdnTag::new("log")) {
    kinds.push("console".into());
  }
  if tags.contains(&EdnTag::new("file")) {
    kinds.push("io/file".into());
  }
  if tags.contains(&EdnTag::new("env")) {
    kinds.push("env".into());
  }
  if tags.contains(&EdnTag::new("control")) {
    kinds.push("control".into());
  }
  if tags.contains(&EdnTag::new("interop")) {
    kinds.push("interop/host".into());
  }
  if tags.contains(&EdnTag::new("async")) {
    kinds.push("async".into());
  }
  if tags.contains(&EdnTag::new("watch")) {
    kinds.push("state/watch".into());
  }
  if tags.contains(&EdnTag::new("io")) && kinds.is_empty() {
    kinds.push("io".into());
  }
  if tags.contains(&EdnTag::new("effect")) {
    kinds.push("effect".into());
  }
  kinds.sort();
  kinds.dedup();
  kinds
}

fn format_type_hint(schema: &std::sync::Arc<CalcitTypeAnnotation>) -> Option<String> {
  format_schema_annotation(schema, "", MAX_SCHEMA_DEPTH)
}

const MAX_SCHEMA_DEPTH: usize = 4;

fn is_informative_schema(hint: &str) -> bool {
  !matches!(
    hint,
    "dynamic" | ":dynamic" | "ref" | ":ref" | "ref<:dynamic>" | "map<dynamic,dynamic>" | "map<:dynamic,:dynamic>"
  )
}

fn is_coarse_schema_hint(hint: &str) -> bool {
  matches!(
    hint,
    "dynamic" | ":dynamic" | "ref" | ":ref" | "ref<:dynamic>" | "map<dynamic,dynamic>" | "map<:dynamic,:dynamic>" | ":map"
  )
}

fn finalize_schema_hint(raw: &str, context_ns: &str) -> String {
  if raw.starts_with('{') || raw.contains(":states") || raw.contains(":records") {
    return raw.to_string();
  }
  expand_type_ref_path(raw, context_ns, MAX_SCHEMA_DEPTH).unwrap_or_else(|| raw.to_string())
}

fn resolve_type_ref_path(ref_path: &str, context_ns: &str) -> Option<(String, String)> {
  let (ns_part, def) = ref_path.split_once('/')?;
  if let Some(real_ns) = lookup_ns_target_in_import(context_ns, ns_part) {
    return Some((real_ns.to_string(), def.to_string()));
  }
  let program = PROGRAM_CODE_DATA.read().ok()?;
  if program.get(ns_part).is_some() {
    return Some((ns_part.to_string(), def.to_string()));
  }
  if ns_part.contains('.') {
    return Some((ns_part.to_string(), def.to_string()));
  }
  let dotted = format!("{context_ns}.{ns_part}");
  if program.get(dotted.as_str()).is_some() {
    return Some((dotted, def.to_string()));
  }
  None
}

fn expand_type_ref_path(ref_path: &str, context_ns: &str, depth: usize) -> Option<String> {
  if depth == 0 {
    return None;
  }
  let (ns, def) = resolve_type_ref_path(ref_path, context_ns)?;
  let template = expand_from_def_template(&ns, &def, context_ns, depth);
  let annotated = expand_from_type_annotation(&ns, &def, context_ns, depth);
  match (template, annotated) {
    (Some(t), Some(a)) if is_coarse_schema_hint(&a) => Some(t),
    (Some(t), Some(a)) => Some(pick_richer_schema(Some(&a), &t)),
    (Some(t), None) => Some(t),
    (None, Some(a)) => Some(a),
    (None, None) => None,
  }
}

fn expand_from_type_annotation(ns: &str, def: &str, context_ns: &str, depth: usize) -> Option<String> {
  let schema = lookup_codegen_type_hint(ns, def).unwrap_or_else(|| lookup_def_schema(ns, def));
  format_schema_annotation(&schema, context_ns, depth)
}

fn format_schema_annotation(schema: &std::sync::Arc<CalcitTypeAnnotation>, context_ns: &str, depth: usize) -> Option<String> {
  if depth == 0 {
    return None;
  }
  match schema.as_ref() {
    CalcitTypeAnnotation::Dynamic => None,
    CalcitTypeAnnotation::Ref(inner, _) => format_schema_annotation(inner, context_ns, depth - 1),
    CalcitTypeAnnotation::TypeRef(name, _) => {
      let stripped = name.trim_start_matches('\'').trim_start_matches(':');
      expand_type_ref_path(stripped, context_ns, depth - 1)
    }
    CalcitTypeAnnotation::Fn(fn_type) => Some(fn_type.return_type.to_brief_string()),
    CalcitTypeAnnotation::Map(key, value)
      if matches!(key.as_ref(), CalcitTypeAnnotation::Dynamic) && matches!(value.as_ref(), CalcitTypeAnnotation::Dynamic) =>
    {
      None
    }
    CalcitTypeAnnotation::Map(key, value) => {
      let k = format_schema_annotation(key, context_ns, depth - 1).unwrap_or_else(|| key.to_brief_string());
      let v = format_schema_annotation(value, context_ns, depth - 1).unwrap_or_else(|| value.to_brief_string());
      Some(format!("map<{k},{v}>"))
    }
    CalcitTypeAnnotation::List(inner) => format_schema_annotation(inner, context_ns, depth - 1).map(|t| format!("list<{t}>")),
    CalcitTypeAnnotation::Nullable(inner, NullableOrigin::Inferred) => {
      format_schema_annotation(inner, context_ns, depth - 1).map(|t| format!("{t}?"))
    }
    CalcitTypeAnnotation::Nullable(inner, NullableOrigin::JsHost) => {
      format_schema_annotation(inner, context_ns, depth - 1).map(|t| format!("js-nullish<{t}>"))
    }
    _ => {
      if let Some(st) = schema.resolve_to_struct() {
        return Some(format_struct_fields(&st, context_ns, depth));
      }
      let brief = schema.to_brief_string();
      if is_informative_schema(&brief) { Some(brief) } else { None }
    }
  }
}

fn format_struct_fields(st: &CalcitStructDef, context_ns: &str, depth: usize) -> String {
  let fields: Vec<String> = st
    .fields
    .iter()
    .zip(st.field_types.iter())
    .map(|(field, ty)| {
      let ty_str = format_schema_annotation(ty, context_ns, depth.saturating_sub(1)).unwrap_or_else(|| ty.to_brief_string());
      format!(":{field} {ty_str}")
    })
    .collect();
  if fields.is_empty() {
    format!("struct {}", st.name)
  } else {
    format!("{{ {} }}", fields.join(", "))
  }
}

fn expand_from_def_template(ns: &str, def: &str, context_ns: &str, depth: usize) -> Option<String> {
  if depth == 0 {
    return None;
  }
  let code = lookup_def_code(ns, def)?;
  let fields = find_best_struct_template(&code)?;
  Some(format_struct_template_fields(&fields, context_ns, depth - 1))
}

fn find_best_struct_template(code: &Calcit) -> Option<Vec<(String, String)>> {
  let mut best: Option<Vec<(String, String)>> = None;
  walk_for_struct_templates(code, &mut best);
  best
}

fn walk_for_struct_templates(code: &Calcit, best: &mut Option<Vec<(String, String)>>) {
  if let Some(fields) = parse_struct_field_pairs(code)
    && fields.len() >= 2
    && best.as_ref().is_none_or(|current| current.len() < fields.len())
  {
    *best = Some(fields);
  }
  match code {
    Calcit::List(list) => {
      for item in list.iter() {
        walk_for_struct_templates(item, best);
      }
    }
    Calcit::Fn { info, .. } => {
      for expr in info.body.iter() {
        walk_for_struct_templates(expr, best);
      }
    }
    Calcit::Macro { info, .. } => {
      for expr in info.body.iter() {
        walk_for_struct_templates(expr, best);
      }
    }
    Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => walk_for_struct_templates(code, best),
    Calcit::Struct(struct_value) => {
      if let Some(fields) = struct_fields_from_calcit(struct_value)
        && fields.len() >= 2
        && best.as_ref().is_none_or(|current| current.len() < fields.len())
      {
        *best = Some(fields);
      }
    }
    Calcit::Map(map) => {
      for (k, v) in map.iter() {
        walk_for_struct_templates(k, best);
        walk_for_struct_templates(v, best);
      }
    }
    _ => {}
  }
}

fn format_struct_template_fields(fields: &[(String, String)], context_ns: &str, depth: usize) -> String {
  let parts: Vec<String> = fields
    .iter()
    .map(|(key, hint)| {
      let expanded = if depth > 0 && hint.contains('/') {
        finalize_schema_hint(hint, context_ns)
      } else {
        hint.clone()
      };
      format!(":{key} {expanded}")
    })
    .collect();
  format!("{{ {} }}", parts.join(", "))
}

fn parse_struct_field_pairs(expr: &Calcit) -> Option<Vec<(String, String)>> {
  if let Calcit::Struct(struct_value) = expr {
    return struct_fields_from_calcit(struct_value);
  }
  let Calcit::List(list) = expr else {
    return None;
  };
  let start = if is_struct_literal_head(list.first()) { 1 } else { 0 };
  parse_flat_struct_pairs(list, start).or_else(|| parse_nested_struct_entries(list, start))
}

fn parse_flat_struct_pairs(list: &calcit_core::calcit::CalcitList, start: usize) -> Option<Vec<(String, String)>> {
  if start >= list.len() {
    return None;
  }
  extract_field_key(list.get(start)?)?;
  let mut fields = vec![];
  let mut idx = start;
  while idx + 1 < list.len() {
    let key = extract_field_key(list.get(idx)?)?;
    let value_hint = value_shape_hint(list.get(idx + 1)?);
    fields.push((key, value_hint));
    idx += 2;
  }
  if fields.is_empty() { None } else { Some(fields) }
}

fn parse_nested_struct_entries(list: &calcit_core::calcit::CalcitList, start: usize) -> Option<Vec<(String, String)>> {
  let mut fields = vec![];
  for idx in start..list.len() {
    let Some(entry) = list.get(idx) else { continue };
    let Calcit::List(entry_list) = entry else { continue };
    if entry_list.len() < 2 {
      continue;
    }
    let key = extract_field_key(entry_list.get(0)?)?;
    let value_hint = value_shape_hint(entry_list.get(1)?);
    fields.push((key, value_hint));
  }
  if fields.is_empty() { None } else { Some(fields) }
}

fn struct_fields_from_calcit(struct_value: &calcit_core::calcit::CalcitStructValue) -> Option<Vec<(String, String)>> {
  let fields = struct_value.fields();
  let values = struct_value.values.as_ref();
  if fields.is_empty() || fields.len() != values.len() {
    return None;
  }
  Some(
    fields
      .iter()
      .zip(values.iter())
      .map(|(field, value)| (field.to_string(), value_shape_hint(value)))
      .collect(),
  )
}

fn is_struct_literal_head(head: Option<&Calcit>) -> bool {
  match head {
    Some(Calcit::Proc(CalcitProc::NativeLooseStruct)) => true,
    Some(Calcit::Proc(CalcitProc::NativeEnum)) => true,
    Some(Calcit::Symbol { sym, .. }) => matches!(sym.as_ref(), "{}" | "?{}" | "::"),
    _ => false,
  }
}

fn extract_field_key(calcit: &Calcit) -> Option<String> {
  match calcit {
    Calcit::Tag(tag) => Some(tag.to_string()),
    Calcit::Symbol { sym, .. } if sym.starts_with(':') => Some(sym[1..].to_string()),
    Calcit::Symbol { sym, .. } => Some(sym.to_string()),
    Calcit::Str(s) => Some(s.to_string()),
    _ => None,
  }
}

fn value_shape_hint(value: &Calcit) -> String {
  match value {
    Calcit::Nil => ":nil".into(),
    Calcit::Bool(_) => ":bool".into(),
    Calcit::Number(_) => ":number".into(),
    Calcit::Str(_) => ":string".into(),
    Calcit::Tag(_) => ":tag".into(),
    Calcit::Import(import) => format!("{}/{}", import.ns, import.def),
    Calcit::Symbol { sym, .. } if sym.contains('/') => sym.to_string(),
    Calcit::Map(map) if map.is_empty() => ":map {}".into(),
    Calcit::List(list) if list.is_empty() => ":list []".into(),
    Calcit::List(list) if list.len() == 1 && matches!(list.first(), Some(Calcit::Proc(CalcitProc::List))) => ":list []".into(),
    Calcit::List(_) => parse_struct_field_pairs(value)
      .map(|fields| format_struct_template_fields(&fields, "", 1))
      .unwrap_or_else(|| ":struct".into()),
    _ => "…".into(),
  }
}

fn lookup_atom_schema(context_ns: &str, atom_name: &str) -> Option<String> {
  if !atom_name.starts_with('*') {
    return None;
  }
  let program_code = PROGRAM_CODE_DATA.read().ok()?;
  let mut best: Option<String> = None;
  if program_code.get(context_ns).is_some_and(|file| file.defs.contains_key(atom_name))
    && let Some(hint) = schema_hint_for_atom_def(context_ns, atom_name, context_ns)
  {
    best = Some(pick_richer_schema(best.as_deref(), &hint));
  }
  for (ns, file) in program_code.iter() {
    if ns.as_ref() != context_ns
      && file.defs.contains_key(atom_name)
      && let Some(hint) = schema_hint_for_atom_def(ns, atom_name, context_ns)
    {
      best = Some(pick_richer_schema(best.as_deref(), &hint));
    }
  }
  best.filter(|hint| is_informative_schema(hint))
}

fn pick_richer_option(current: Option<&str>, next: Option<&str>) -> Option<String> {
  match (current, next) {
    (Some(cur), Some(nxt)) => Some(pick_richer_schema(Some(cur), nxt)),
    (Some(cur), None) => Some(cur.to_string()),
    (None, Some(nxt)) => Some(nxt.to_string()),
    (None, None) => None,
  }
}

struct MergedStateItem {
  key: String,
  kind_label: String,
  kind: String,
  name: String,
  type_hint: Option<String>,
  count: usize,
}

fn state_item_key(item: &StateItem) -> String {
  format!("{}::{}", item.kind, item.name)
}

fn state_kind_label(kind: &str) -> &'static str {
  match kind {
    "param" => "in",
    "return" => "out",
    "atom-def" => "define",
    "atom" | "atom-read" | "atom-write" => "atom",
    "watch" => "watch",
    _ => "state",
  }
}

fn merge_state_items(items: Vec<(&str, &StateItem)>) -> Vec<MergedStateItem> {
  let mut merged: Vec<MergedStateItem> = vec![];
  for (label, item) in items {
    let key = state_item_key(item);
    if let Some(entry) = merged.iter_mut().find(|entry| entry.key == key) {
      entry.count += 1;
      entry.type_hint = pick_richer_option(entry.type_hint.as_deref(), item.type_hint.as_deref());
      continue;
    }
    merged.push(MergedStateItem {
      key,
      kind_label: label.to_string(),
      kind: item.kind.clone(),
      name: item.name.clone(),
      type_hint: item.type_hint.clone(),
      count: 1,
    });
  }
  merged
}

fn schema_kind_shows_subtree(kind: &str) -> bool {
  matches!(kind, "atom-def" | "watch")
}

fn pick_richer_schema(current: Option<&str>, next: &str) -> String {
  match current {
    Some(cur) if cur.len() >= next.len() => cur.to_string(),
    _ => next.to_string(),
  }
}

fn schema_hint_for_atom_def(ns: &str, def: &str, context_ns: &str) -> Option<String> {
  let mut raw_candidates: Vec<String> = vec![];

  if let Some(code) = lookup_def_code(ns, def)
    && let Some(raw) = extract_defref_init_from_code(&code, context_ns)
  {
    raw_candidates.push(raw);
  }

  if let Some(schema) = lookup_codegen_type_hint(ns, def)
    && let Some(hint) = format_schema_annotation(&schema, context_ns, MAX_SCHEMA_DEPTH)
  {
    raw_candidates.push(hint);
  }
  if let Some(hint) = format_schema_annotation(&lookup_def_schema(ns, def), context_ns, MAX_SCHEMA_DEPTH) {
    raw_candidates.push(hint);
  }

  raw_candidates
    .into_iter()
    .map(|raw| finalize_schema_hint(&raw, context_ns))
    .filter(|hint| is_informative_schema(hint))
    .max_by_key(|hint| hint.len())
}

fn enrich_atom_def_state(ns: &str, def: &str, state: &mut Vec<StateItem>) {
  let Some(schema) = lookup_atom_schema(ns, def) else {
    return;
  };
  if let Some(item) = state.iter_mut().find(|item| item.kind == "atom-def" && item.name == def) {
    item.type_hint = Some(pick_richer_schema(item.type_hint.as_deref(), &schema));
    return;
  }
  state.insert(
    0,
    StateItem {
      kind: "atom-def".into(),
      name: def.to_string(),
      type_hint: Some(schema),
    },
  );
}

fn extract_defref_init_from_code(code: &Calcit, context_ns: &str) -> Option<String> {
  match code {
    Calcit::List(list) => {
      let head = list.first()?;
      let op = call_operator_name(head)?;
      if let Some(idx) = ref_constructor_init_index(&op) {
        return list
          .get(idx)
          .and_then(|init| summarize_init_expr(init, context_ns))
          .map(|raw| finalize_schema_hint(&raw, context_ns));
      }
      for item in list.iter() {
        if let Some(hint) = extract_defref_init_from_code(item, context_ns) {
          return Some(hint);
        }
      }
      None
    }
    Calcit::Fn { info, .. } => {
      for expr in info.body.iter() {
        if let Some(hint) = extract_defref_init_from_code(expr, context_ns) {
          return Some(hint);
        }
      }
      None
    }
    Calcit::Macro { info, .. } => {
      for expr in info.body.iter() {
        if let Some(hint) = extract_defref_init_from_code(expr, context_ns) {
          return Some(hint);
        }
      }
      None
    }
    Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => extract_defref_init_from_code(code, context_ns),
    _ => None,
  }
}

fn call_operator_name(head: &Calcit) -> Option<String> {
  match head {
    Calcit::Syntax(syntax, _) => Some(syntax.to_string()),
    Calcit::Proc(proc) => Some(proc.to_string()),
    Calcit::Registered(name) => Some(name.to_string()),
    Calcit::Import(import) => Some(import.def.to_string()),
    Calcit::Symbol { sym, .. } => Some(sym.to_string()),
    _ => None,
  }
}

fn summarize_init_expr(expr: &Calcit, current_ns: &str) -> Option<String> {
  match expr {
    Calcit::Number(n) => Some(format!(":number  init={n}")),
    Calcit::Nil => Some(":nil".into()),
    Calcit::Str(_) => Some(":string".into()),
    Calcit::Tag(tag) => Some(format!(":{tag}")),
    Calcit::Import(import) => Some(format!("{}/{}", import.ns, import.def)),
    Calcit::Symbol { sym, .. } if sym.contains('/') => Some(sym.to_string()),
    Calcit::Map(map) if map.is_empty() => Some(":map {}".into()),
    Calcit::List(list) if list.is_empty() => Some(":list []".into()),
    Calcit::List(list) => summarize_call_init(list, current_ns),
    _ => None,
  }
}

fn summarize_type_ref_expr(expr: &Calcit, current_ns: &str) -> Option<String> {
  match expr {
    Calcit::Import(import) => Some(format!("{}/{}", import.ns, import.def)),
    Calcit::Symbol { sym, .. } if sym.contains('/') => Some(sym.to_string()),
    _ => summarize_init_expr(expr, current_ns),
  }
}

fn expand_arrow_init(list: &calcit_core::calcit::CalcitList, context_ns: &str) -> Option<String> {
  let base = list.get(1)?;
  let base_hint = summarize_type_ref_expr(base, context_ns)?;
  let mut overlays: Vec<String> = vec![];
  for idx in 2..list.len() {
    if let Some(item) = list.get(idx)
      && let Some(overlay) = extract_assoc_overlay(item, context_ns)
    {
      overlays.push(overlay);
    }
  }
  let base_expanded = finalize_schema_hint(&base_hint, context_ns);
  if overlays.is_empty() {
    Some(if base_expanded == base_hint {
      base_expanded
    } else {
      format!("{base_hint} = {base_expanded}")
    })
  } else {
    let base_label = if base_expanded == base_hint {
      base_hint
    } else {
      format!("{base_hint} = {base_expanded}")
    };
    Some(format!("{base_label} {{ {} }}", overlays.join(", ")))
  }
}

fn extract_assoc_overlay(expr: &Calcit, context_ns: &str) -> Option<String> {
  let Calcit::List(list) = expr else {
    return None;
  };
  let head = call_operator_name(list.first()?)?;
  if head != "assoc" {
    return None;
  }
  let key = extract_field_key(list.get(1)?)?;
  let val = list.get(2)?;
  let val_hint = summarize_type_ref_expr(val, context_ns)?;
  let val_expanded = finalize_schema_hint(&val_hint, context_ns);
  Some(format!(":{key} {val_expanded}"))
}

fn summarize_call_init(list: &calcit_core::calcit::CalcitList, current_ns: &str) -> Option<String> {
  let head = list.first()?;

  if is_thread_first_head(head)
    && let Some(second) = list.get(1)
  {
    if is_arrow_head(second) {
      return list.get(2).and_then(|expr| summarize_init_expr(expr, current_ns));
    }
    return summarize_init_expr(second, current_ns);
  }

  if is_arrow_head(head) {
    return expand_arrow_init(list, current_ns);
  }

  if let Some((ns, def)) = resolve_def_call(head, current_ns) {
    return Some(format!("{ns}/{def}"));
  }
  if let Calcit::Symbol { sym, .. } = head {
    return Some(sym.to_string());
  }
  None
}

fn is_thread_first_head(head: &Calcit) -> bool {
  match head {
    Calcit::Symbol { sym, .. } => sym.as_ref() == "$",
    _ => false,
  }
}

fn is_arrow_head(head: &Calcit) -> bool {
  match head {
    Calcit::Symbol { sym, .. } => sym.as_ref() == "->",
    Calcit::Syntax(syntax, _) => syntax.to_string() == "->",
    Calcit::Import(import) => import.def.as_ref() == "->" || import.def.as_ref() == "$",
    _ => false,
  }
}

fn doc_or_generated_summary(doc: Option<&str>, control: &[String], calls: &[String]) -> String {
  if let Some(text) = doc {
    let trimmed = text.lines().next().unwrap_or(text).trim();
    if !trimmed.is_empty() {
      return trimmed.to_string();
    }
  }
  let mut parts = vec![];
  if !control.is_empty() {
    let mut counts: HashMap<&str, usize> = HashMap::new();
    for item in control {
      *counts.entry(item.as_str()).or_default() += 1;
    }
    let control_summary: Vec<String> = counts
      .into_iter()
      .map(|(name, count)| if count > 1 { format!("{name}×{count}") } else { name.to_string() })
      .collect();
    parts.push(format!("control: {}", control_summary.join(", ")));
  }
  if !calls.is_empty() {
    parts.push(format!("calls: {}", calls.len()));
  }
  if parts.is_empty() { "transform".into() } else { parts.join("; ") }
}

fn prune_tree_by_ns_prefix(mut node: EffectsGraphNode, prefix: &str) -> EffectsGraphNode {
  let children = std::mem::take(&mut node.children);
  node.children = children
    .into_iter()
    .map(|child| prune_tree_by_ns_prefix(child, prefix))
    .filter(|child| tree_contains_ns_prefix(child, prefix))
    .collect();
  node
}

fn tree_contains_ns_prefix(node: &EffectsGraphNode, prefix: &str) -> bool {
  if node.ns.starts_with(prefix) {
    return true;
  }
  node.children.iter().any(|child| tree_contains_ns_prefix(child, prefix))
}

pub fn analyze_effects_graph(
  entry_ns: &str,
  entry_def: &str,
  include_core: bool,
  max_depth: usize,
  ns_prefix: Option<String>,
  detail: EffectsGraphDetail,
) -> Result<EffectsGraphResult, String> {
  let config = EffectsGraphConfig {
    include_core,
    max_depth,
    ns_prefix,
    detail,
  };
  let mut analyzer = EffectsGraphAnalyzer::new(config)?;
  analyzer.analyze(entry_ns, entry_def)
}

fn is_meaningful_call_target(ns: &str, def: &str, include_core: bool) -> bool {
  if matches!(
    def,
    "defn" | "defmacro" | "def" | "deftrait" | "defenum" | "defref" | "reset!" | "swap!" | "deref" | "ref"
  ) {
    return false;
  }
  if !include_core && (ns == "calcit.core" || ns.starts_with("calcit.")) {
    return false;
  }
  true
}

fn is_analyzed_node(node: &EffectsGraphNode) -> bool {
  !node.state.is_empty()
    || !node.effects.is_empty()
    || !node.transform.summary.is_empty()
    || !node.transform.calls.is_empty()
    || !node.transform.control.is_empty()
    || !node.children.is_empty()
    || node.circular
    || node.depth_exceeded
}

fn count_subgraph_nodes(tree: &EffectsGraphNode) -> usize {
  collect_analyzed_subgraphs(tree).len()
}

fn collect_analyzed_subgraphs(tree: &EffectsGraphNode) -> Vec<&EffectsGraphNode> {
  let mut nodes = vec![];
  let mut queue: Vec<&EffectsGraphNode> = tree.children.iter().collect();
  while let Some(node) = queue.first().copied() {
    queue.remove(0);
    if is_analyzed_node(node) && !node.seen {
      nodes.push(node);
    }
    queue.extend(node.children.iter());
  }
  nodes
}

// ═══════════════════════════════════════════════════════════════════════════════
// STE tree format — per-function State / Transform / Effect decomposition
// ═══════════════════════════════════════════════════════════════════════════════

fn infer_package_root(entry_ns: &str, ns_prefix: &Option<String>) -> Option<String> {
  if let Some(prefix) = ns_prefix {
    let root = prefix.strip_suffix('.').unwrap_or(prefix.as_str());
    if root.is_empty() {
      return None;
    }
    return Some(root.to_string());
  }
  calcit_core::util::string::extract_pkg_from_ns(entry_ns.into()).map(|s| s.to_string())
}

fn shorten_fqn(fqn: &str, package_root: &str) -> String {
  let ns_prefix = format!("{package_root}.");
  let Some((ns, def)) = fqn.split_once('/') else {
    return fqn.to_string();
  };
  if ns.starts_with(&ns_prefix) {
    format!("{}/{}", &ns[ns_prefix.len()..], def)
  } else {
    fqn.to_string()
  }
}

struct SteDisplay<'a> {
  package_root: Option<&'a str>,
  color: SteColor,
}

struct SteColor {
  enabled: bool,
}

impl SteColor {
  fn new(enabled: bool) -> Self {
    if !enabled {
      colored::control::set_override(false);
    }
    Self { enabled }
  }

  fn plain(&self, text: &str) -> String {
    text.to_string()
  }

  fn paint<'a>(&self, text: &'a str, style: impl Fn(&'a str) -> colored::ColoredString) -> String {
    if self.enabled { style(text).to_string() } else { text.to_string() }
  }

  fn title(&self, text: &str) -> String {
    self.paint(text, |s| s.cyan().bold())
  }

  fn meta(&self, text: &str) -> String {
    self.paint(text, |s| s.dimmed())
  }

  fn connector(&self, text: &str) -> String {
    self.paint(text, |s| s.dimmed())
  }

  fn node_fqn(&self, text: &str, depth: usize) -> String {
    self.paint(text, |s| match depth {
      0 => s.green().bold(),
      1 => s.cyan(),
      2 => s.yellow(),
      _ => s.normal(),
    })
  }

  fn kind_label(&self, label: &str, node: &EffectsGraphNode) -> String {
    self.paint(label, |s| {
      let styled = if node.depth_exceeded {
        s.yellow()
      } else if node.circular {
        s.red()
      } else if node.source == "core" {
        s.cyan()
      } else if node.def.starts_with('*') {
        s.magenta()
      } else if node.effects.is_empty() {
        s.blue()
      } else {
        s.green()
      };
      styled.dimmed()
    })
  }

  fn schema(&self, text: &str) -> String {
    self.paint(text, |s| s.green().dimmed())
  }

  fn section_state(&self, text: &str) -> String {
    self.paint(text, |s| s.magenta().bold())
  }

  fn section_inputs(&self, text: &str) -> String {
    self.paint(text, |s| s.cyan().bold())
  }

  fn section_output(&self, text: &str) -> String {
    self.paint(text, |s| s.green().bold())
  }

  fn section_transform(&self, text: &str) -> String {
    self.paint(text, |s| s.blue().bold())
  }

  fn section_effects(&self, text: &str) -> String {
    self.paint(text, |s| s.yellow().bold())
  }

  fn state_kind(&self, text: &str) -> String {
    self.paint(text, |s| s.dimmed())
  }

  fn state_name(&self, text: &str) -> String {
    self.paint(text, |s| s.white().bold())
  }

  fn transform_arrow(&self, text: &str) -> String {
    self.paint(text, |s| s.blue())
  }

  fn effect_kind(&self, text: &str) -> String {
    self.paint(text, |s| s.yellow())
  }

  fn effect_target(&self, text: &str) -> String {
    self.plain(text)
  }

  fn collapsed(&self, text: &str) -> String {
    self.paint(text, |s| s.dimmed())
  }
}

impl<'a> SteDisplay<'a> {
  fn from_result(result: &'a EffectsGraphResult, color: bool) -> Self {
    SteDisplay {
      package_root: result.display.package_root.as_deref(),
      color: SteColor::new(color),
    }
  }

  fn fqn(&self, fqn: &str) -> String {
    match self.package_root {
      Some(root) => shorten_fqn(fqn, root),
      None => fqn.to_string(),
    }
  }
}

const SCHEMA_INLINE_MAX: usize = 72;

struct SchemaHintParts {
  label: Option<String>,
  segments: Vec<String>,
}

fn schema_should_embed(hint: &str) -> bool {
  hint.len() > SCHEMA_INLINE_MAX || (hint.contains('{') && hint.len() > 48)
}

fn split_schema_hint(hint: &str) -> SchemaHintParts {
  let hint = hint.trim();
  if let Some((label, rest)) = hint.split_once(" = ") {
    let segments = extract_brace_blocks(rest);
    if segments.is_empty() && !rest.trim().is_empty() {
      return SchemaHintParts {
        label: Some(label.trim().to_string()),
        segments: vec![rest.trim().to_string()],
      };
    }
    return SchemaHintParts {
      label: Some(label.trim().to_string()),
      segments,
    };
  }
  let segments = extract_brace_blocks(hint);
  if segments.is_empty() {
    SchemaHintParts {
      label: None,
      segments: vec![hint.to_string()],
    }
  } else {
    SchemaHintParts { label: None, segments }
  }
}

fn extract_brace_blocks(s: &str) -> Vec<String> {
  let mut blocks = Vec::new();
  let mut depth = 0usize;
  let mut start: Option<usize> = None;
  for (idx, ch) in s.char_indices() {
    match ch {
      '{' => {
        if depth == 0 {
          start = Some(idx);
        }
        depth += 1;
      }
      '}' => {
        if depth == 0 {
          continue;
        }
        depth -= 1;
        if depth == 0
          && let Some(from) = start
        {
          blocks.push(s[from..=idx].to_string());
          start = None;
        }
      }
      _ => {}
    }
  }
  blocks
}

fn parse_schema_segment(segment: &str) -> Option<Edn> {
  parse_schema_value(segment.trim())
}

fn parse_schema_value(raw: &str) -> Option<Edn> {
  let s = raw.trim();
  if s.is_empty() {
    return Some(Edn::Nil);
  }
  if s.starts_with('{') {
    return parse_schema_map(s);
  }
  if s.starts_with('[') {
    return parse_schema_list(s);
  }
  if s == "nil" {
    return Some(Edn::Nil);
  }
  if let Some(body) = s.strip_prefix(':') {
    let body = body.trim();
    if let Some(split_at) = body.find(char::is_whitespace) {
      let tag = &body[..split_at];
      let rest = body[split_at..].trim();
      let value = parse_schema_value(rest)?;
      let mut combo = EdnListView::default();
      combo.push(Edn::Tag(EdnTag::from(tag)));
      combo.push(value);
      return Some(combo.into());
    }
    return Some(Edn::Tag(EdnTag::from(body)));
  }
  Some(Edn::Symbol(s.into()))
}

fn parse_schema_map(s: &str) -> Option<Edn> {
  let inner = s.trim();
  if !inner.starts_with('{') || !inner.ends_with('}') {
    return None;
  }
  let body = inner[1..inner.len() - 1].trim();
  let mut map = EdnMapView::default();
  for field in split_top_level_commas(body) {
    let (key, value_raw) = split_field_key_value(field)?;
    let key_name = key.trim_start_matches(':');
    let value = parse_schema_value(value_raw)?;
    map.insert(Edn::Tag(EdnTag::from(key_name)), value);
  }
  Some(map.into())
}

fn parse_schema_list(s: &str) -> Option<Edn> {
  let inner = s.trim();
  if inner == "[]" {
    return Some(EdnListView::default().into());
  }
  if !inner.starts_with('[') || !inner.ends_with(']') {
    return None;
  }
  let body = inner[1..inner.len() - 1].trim();
  if body.is_empty() {
    return Some(EdnListView::default().into());
  }
  let mut list = EdnListView::default();
  for item in split_top_level_commas(body) {
    list.push(parse_schema_value(item)?);
  }
  Some(list.into())
}

fn split_field_key_value(field: &str) -> Option<(&str, &str)> {
  let field = field.trim();
  if !field.starts_with(':') {
    return None;
  }
  let rest = field[1..].trim_start();
  let key_end = rest.find(char::is_whitespace).unwrap_or(rest.len());
  let key = &field[..1 + key_end];
  let value = rest[key_end..].trim();
  Some((key, value))
}

fn split_top_level_commas(s: &str) -> Vec<&str> {
  let mut parts = Vec::new();
  let mut start = 0usize;
  let mut brace = 0usize;
  let mut bracket = 0usize;
  for (idx, ch) in s.char_indices() {
    match ch {
      '{' => brace += 1,
      '}' => brace = brace.saturating_sub(1),
      '[' => bracket += 1,
      ']' => bracket = bracket.saturating_sub(1),
      ',' if brace == 0 && bracket == 0 => {
        let part = s[start..idx].trim();
        if !part.is_empty() {
          parts.push(part);
        }
        start = idx + 1;
      }
      _ => {}
    }
  }
  let part = s[start..].trim();
  if !part.is_empty() {
    parts.push(part);
  }
  parts
}

fn format_schema_edn_lines(edn: &Edn) -> Vec<String> {
  cirru_edn::format(edn, true)
    .map(|text| {
      text
        .lines()
        .map(|line| line.trim_end().to_string())
        .filter(|line| !line.trim().is_empty())
        .collect()
    })
    .unwrap_or_else(|_| vec![edn.to_string()])
}

fn render_schema_subtree(hint: &str, prefix: &str, display: &SteDisplay<'_>, out: &mut String) {
  let parts = split_schema_hint(hint);
  out.push_str(&format!(
    "{}{}\n",
    display.color.connector(prefix),
    display.color.schema("└── schema")
  ));
  let inner = format!("{prefix}    ");

  if let Some(label) = parts.label {
    out.push_str(&format!(
      "{}{}\n",
      display.color.connector(&inner),
      display.color.schema(&format!("{label} ="))
    ));
  }

  let segments = if parts.segments.is_empty() {
    vec![hint.to_string()]
  } else {
    parts.segments
  };

  for segment in segments {
    if let Some(edn) = parse_schema_segment(&segment) {
      for line in format_schema_edn_lines(&edn) {
        out.push_str(&format!("{}{}\n", display.color.connector(&inner), display.color.schema(&line)));
      }
    } else {
      out.push_str(&format!("{}{}\n", display.color.connector(&inner), display.color.schema(&segment)));
    }
  }
}

fn inline_schema_suffix(hint: &str, display: &SteDisplay<'_>) -> String {
  if schema_should_embed(hint) {
    return String::new();
  }
  format!("  {}", display.color.schema(&format!("schema: {hint}")))
}

fn node_atom_schema_hint(node: &EffectsGraphNode) -> Option<String> {
  if !node.def.starts_with('*') {
    return None;
  }
  node
    .state
    .iter()
    .find(|item| item.kind == "atom-def")
    .and_then(|item| item.type_hint.clone())
    .or_else(|| lookup_atom_schema(&node.ns, &node.def))
}

/// Format entry point for CLI banners and headers.
pub fn format_entry_label(entry_ns: &str, entry_def: &str, ns_prefix: Option<&str>) -> String {
  let fqn = format!("{entry_ns}/{entry_def}");
  match infer_package_root(entry_ns, &ns_prefix.map(|s| s.to_string())) {
    Some(root) => shorten_fqn(&fqn, &root),
    None => fqn,
  }
}

/// Render per-function STE decomposition tree.
pub fn format_as_ste_tree(result: &EffectsGraphResult, color: bool) -> String {
  let display = SteDisplay::from_result(result, color);
  let mut out = String::new();
  out.push_str(&format!(
    "{}\n\n",
    display.color.title(&format!("# Effects Graph: `{}`", display.fqn(&result.entry)))
  ));

  if let Some(root) = display.package_root {
    out.push_str(&format!("{}\n", display.color.meta(&format!("Package: `{root}.*`"))));
  }

  let depth_limited = count_depth_limited(&result.tree);
  if depth_limited > 0 {
    out.push_str(&format!(
      "{}\n\n",
      display.color.meta(&format!(
        "Max depth: {}  ({} nodes truncated; rerun with larger --max-depth to expand)",
        result.display.max_depth_limit, depth_limited
      ))
    ));
  } else if result.display.max_depth_limit > 0 {
    out.push_str(&format!(
      "{}\n\n",
      display.color.meta(&format!("Max depth: {}", result.display.max_depth_limit))
    ));
  } else if display.package_root.is_some() {
    out.push('\n');
  }

  render_ste_node(&result.tree, &mut out, "", true, 0, &display);
  out
}

fn count_depth_limited(node: &EffectsGraphNode) -> usize {
  let mut count = if node.depth_exceeded { 1 } else { 0 };
  for child in &node.children {
    count += count_depth_limited(child);
  }
  count
}

fn render_ste_node(node: &EffectsGraphNode, out: &mut String, prefix: &str, is_last: bool, depth: usize, display: &SteDisplay<'_>) {
  if node.seen {
    return;
  }

  let connector = if is_last { "└── " } else { "├── " };
  let (kind_label, is_collapsed) = ste_kind_label(node);
  let summary = node_transform_summary(node);
  let fqn = display.fqn(&node.fqn);

  out.push_str(&format!(
    "{}{}{}  {}{}\n",
    display.color.connector(prefix),
    display.color.connector(connector),
    display.color.node_fqn(&fqn, depth),
    display.color.kind_label(kind_label, node),
    node_schema_suffix(node, display)
  ));

  let child_prefix = format!("{prefix}{}   ", if is_last { " " } else { "│" });

  if is_collapsed {
    if !summary.is_empty() {
      out.push_str(&format!(
        "{}{}\n",
        display.color.connector(&child_prefix),
        display.color.collapsed(&format!("({summary})"))
      ));
    }
    return;
  }

  render_ste_inputs(node, out, &child_prefix, display);
  render_ste_output(node, out, &child_prefix, display);
  render_ste_state(node, out, &child_prefix, display);
  render_ste_transform(node, out, &child_prefix, display);
  render_ste_effects(node, out, &child_prefix, display);

  if !node.children.is_empty() {
    out.push_str(&format!(
      "{}{}\n",
      display.color.connector(&child_prefix),
      display.color.connector("│")
    ));
  }
  for (idx, child) in node.children.iter().enumerate() {
    let is_last_child = idx + 1 == node.children.len();
    render_ste_node(child, out, &child_prefix, is_last_child, depth + 1, display);
  }
}

fn node_schema_suffix(node: &EffectsGraphNode, display: &SteDisplay<'_>) -> String {
  node_atom_schema_hint(node)
    .as_deref()
    .map(|hint| inline_schema_suffix(hint, display))
    .unwrap_or_default()
}

fn ste_kind_label(node: &EffectsGraphNode) -> (&'static str, bool) {
  if node.depth_exceeded {
    ("[depth limit ↑]", true)
  } else if node.circular {
    ("[circular]", true)
  } else if node.source == "core" {
    ("[core]", true)
  } else if !is_analyzed_node(node) {
    ("[no analysis]", true)
  } else if node.def.starts_with('*') {
    ("[state]", false)
  } else if node.effects.is_empty() {
    ("[transform]", false)
  } else {
    ("[program]", false)
  }
}

fn node_transform_summary(node: &EffectsGraphNode) -> String {
  let mut parts: Vec<String> = vec![];

  let doc_line = node.doc.as_ref().and_then(|doc| {
    let line = doc.lines().next().unwrap_or(doc).trim();
    if line.is_empty() { None } else { Some(line.to_string()) }
  });

  if let Some(ref line) = doc_line {
    parts.push(line.clone());
  }

  let summary = &node.transform.summary;
  if !summary.is_empty() && summary != "transform" && doc_line.as_ref() != Some(summary) {
    parts.push(summary.clone());
  }

  if !node.effects.is_empty() {
    let kinds: Vec<String> = node.effects.iter().map(|e| e.kind.clone()).collect();
    let mut unique: Vec<String> = kinds;
    unique.sort();
    unique.dedup();
    let effect_part = format!("effects: {}", unique.join(", "));
    if !parts.iter().any(|p| p.contains("effects:")) {
      parts.push(effect_part);
    }
  }

  truncate_summary(parts.join("; "), 120)
}

/// Truncate to at most `max_chars` characters (not bytes), appending `…` when cut,
/// so multi-byte text such as Chinese docs never splits a UTF-8 char boundary.
fn truncate_summary(text: String, max_chars: usize) -> String {
  if text.chars().count() <= max_chars {
    return text;
  }
  let keep = max_chars.saturating_sub(3);
  let cut = text.char_indices().nth(keep).map(|(idx, _)| idx).unwrap_or(text.len());
  format!("{}…", &text[..cut])
}

fn render_ste_inputs(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
  let params: Vec<&StateItem> = node.state.iter().filter(|item| item.kind == "param").collect();
  if params.is_empty() {
    return;
  }
  let entries = merge_state_items(params.into_iter().map(|item| (state_kind_label(&item.kind), item)).collect());
  render_ste_entry_section(
    "├── Inputs",
    |color, text| color.section_inputs(text),
    &entries,
    prefix,
    display,
    out,
  );
}

fn render_ste_output(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
  let returns: Vec<&StateItem> = node.state.iter().filter(|item| item.kind == "return").collect();
  if returns.is_empty() {
    return;
  }
  let entries = merge_state_items(returns.into_iter().map(|item| (state_kind_label(&item.kind), item)).collect());
  render_ste_entry_section(
    "├── Output",
    |color, text| color.section_output(text),
    &entries,
    prefix,
    display,
    out,
  );
}

fn render_ste_state(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
  let mut raw: Vec<(&str, &StateItem)> = vec![];
  for item in &node.state {
    match item.kind.as_str() {
      "param" | "return" => {}
      "atom-def" | "atom" | "atom-read" | "atom-write" => {
        raw.push((state_kind_label(&item.kind), item));
      }
      "watch" => raw.push(("watch", item)),
      _ => raw.push((state_kind_label(&item.kind), item)),
    }
  }
  if raw.is_empty() {
    return;
  }
  let entries = merge_state_items(raw);
  render_ste_entry_section("├── State", |color, text| color.section_state(text), &entries, prefix, display, out);
}

fn render_ste_entry_section(
  header: &str,
  header_style: impl Fn(&SteColor, &str) -> String,
  entries: &[MergedStateItem],
  prefix: &str,
  display: &SteDisplay<'_>,
  out: &mut String,
) {
  out.push_str(&format!(
    "{}{}\n",
    display.color.connector(prefix),
    header_style(&display.color, header)
  ));
  let item_prefix = format!("{prefix}│   ");
  for (idx, entry) in entries.iter().enumerate() {
    let is_last = idx + 1 == entries.len();
    let conn = if is_last { "└── " } else { "├── " };
    let line = ste_merged_state_line(entry, display);
    out.push_str(&format!(
      "{}{}{}\n",
      display.color.connector(&item_prefix),
      display.color.connector(conn),
      line
    ));
    if schema_kind_shows_subtree(&entry.kind)
      && let Some(hint) = entry.type_hint.as_deref().filter(|hint| schema_should_embed(hint))
    {
      let sub_prefix = format!("{item_prefix}{}", if is_last { "    " } else { "│   " });
      render_schema_subtree(hint, &sub_prefix, display, out);
    }
  }
}

fn ste_merged_state_line(entry: &MergedStateItem, display: &SteDisplay<'_>) -> String {
  let kind = if entry.kind_label.is_empty() {
    state_kind_label(&entry.kind)
  } else {
    entry.kind_label.as_str()
  };

  if entry.kind == "return" {
    let value = entry.type_hint.as_deref().unwrap_or(&entry.name);
    return format!(
      "{} {}",
      display.color.state_kind(&format!("{kind:<8}")),
      display.color.state_name(value)
    );
  }

  if entry.kind == "param" {
    let type_part = entry
      .type_hint
      .as_deref()
      .map(|hint| format!("  {}", display.color.schema(hint)))
      .unwrap_or_default();
    return format!(
      "{} {}{type_part}",
      display.color.state_kind(&format!("{kind:<8}")),
      display.color.state_name(&entry.name)
    );
  }

  let mut name = display.color.state_name(&entry.name);
  if entry.kind == "atom-write" {
    name.push_str(&display.color.meta(" (write)"));
  } else if entry.kind == "atom-read" {
    name.push_str(&display.color.meta(" (read)"));
  } else if entry.kind == "local-write" {
    name.push_str(&display.color.meta(" (set!)"));
  }
  if entry.count > 1 {
    name.push_str(&display.color.meta(&format!(" (×{})", entry.count)));
  }

  let schema = entry
    .type_hint
    .as_deref()
    .filter(|_| schema_kind_shows_subtree(&entry.kind))
    .map(|hint| inline_schema_suffix(hint, display))
    .unwrap_or_default();

  format!("{} {}{schema}", display.color.state_kind(&format!("{kind:<8}")), name)
}

fn render_ste_transform(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
  let has_control = !node.transform.control.is_empty();
  let has_calls = !node.transform.calls.is_empty();
  let summary = if node.transform.summary.is_empty() || node.transform.summary == "transform" {
    String::new()
  } else {
    format!("  ({})", node.transform.summary)
  };

  if !has_control && !has_calls {
    out.push_str(&format!(
      "{}{}{}\n",
      display.color.connector(prefix),
      display.color.section_transform("├── Transform"),
      display.color.meta(&summary)
    ));
    out.push_str(&format!(
      "{}{}{}\n",
      display.color.connector(prefix),
      display.color.connector("│   └── "),
      display.color.collapsed("(no calls)")
    ));
    return;
  }

  out.push_str(&format!(
    "{}{}{}\n",
    display.color.connector(prefix),
    display.color.section_transform("├── Transform"),
    display.color.meta(&summary)
  ));
  let item_prefix = format!("{prefix}│   ");
  let mut lines: Vec<String> = vec![];

  if has_control {
    let mut counts: HashMap<&str, usize> = HashMap::new();
    for item in &node.transform.control {
      *counts.entry(item.as_str()).or_default() += 1;
    }
    let control_summary: Vec<String> = counts
      .into_iter()
      .map(|(name, count)| if count > 1 { format!("{name}×{count}") } else { name.to_string() })
      .collect();
    lines.push(display.color.meta(&format!("control: {}", control_summary.join(", "))));
  }

  for call in &node.transform.calls {
    lines.push(format!(
      "{} {}",
      display.color.transform_arrow("→"),
      display.color.node_fqn(&display.fqn(call), 1)
    ));
  }

  for (idx, line) in lines.iter().enumerate() {
    let conn = if idx + 1 == lines.len() { "└── " } else { "├── " };
    out.push_str(&format!(
      "{}{}{}\n",
      display.color.connector(&item_prefix),
      display.color.connector(conn),
      line
    ));
  }
}

fn render_ste_effects(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
  if node.effects.is_empty() {
    out.push_str(&format!(
      "{}{}\n",
      display.color.connector(prefix),
      display.color.section_effects("└── Effects")
    ));
    out.push_str(&format!(
      "{}{}{}\n",
      display.color.connector(prefix),
      display.color.connector("    └── "),
      display.color.collapsed("(none — pure transform)")
    ));
    return;
  }

  out.push_str(&format!(
    "{}{}\n",
    display.color.connector(prefix),
    display.color.section_effects("└── Effects")
  ));
  let item_prefix = format!("{prefix}    ");

  let mut seen: HashSet<String> = HashSet::new();
  let mut unique_effects: Vec<&EffectItem> = vec![];
  for effect in &node.effects {
    if seen.insert(format!("{}::{}", effect.kind, effect.target)) {
      unique_effects.push(effect);
    }
  }
  unique_effects.sort_by(|a, b| a.kind.cmp(&b.kind).then(a.target.cmp(&b.target)));

  for (idx, effect) in unique_effects.iter().enumerate() {
    let conn = if idx + 1 == unique_effects.len() {
      "└── "
    } else {
      "├── "
    };
    let count_suffix = if effect.count > 1 {
      display.color.meta(&format!(" (×{})", effect.count))
    } else {
      String::new()
    };
    out.push_str(&format!(
      "{}{}{} {}{}\n",
      display.color.connector(&item_prefix),
      display.color.connector(conn),
      display.color.effect_kind(&format!("{:<14}", effect.kind)),
      display.color.effect_target(&effect.target),
      count_suffix
    ));
  }
}

pub fn format_as_json(result: &EffectsGraphResult) -> Result<String, String> {
  serde_json::to_string_pretty(result).map_err(|e| format!("Failed to serialize to JSON: {e}"))
}

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

  fn core_kinds(index: &TagIndex, name: &str) -> Vec<String> {
    classify_call(name, index.tags_for(name))
  }

  fn strings(items: &[&str]) -> Vec<String> {
    items.iter().map(|item| item.to_string()).collect()
  }

  #[test]
  fn truncate_summary_respects_char_boundaries() {
    let short = "短文档".to_string();
    assert_eq!(truncate_summary(short.clone(), 120), short);
    // 200 three-byte chars: byte slicing at 117 would land mid-char and panic.
    let long: String = "中".repeat(200);
    let cut = truncate_summary(long, 120);
    assert_eq!(cut.chars().count(), 118);
    assert!(cut.ends_with('…'));
    let mixed: String = format!("{}{}", "a".repeat(116), "文".repeat(10));
    assert_eq!(truncate_summary(mixed, 120), format!("{}文…", "a".repeat(116)));
    let ascii = "x".repeat(120);
    assert_eq!(truncate_summary(ascii.clone(), 120), ascii);
  }

  #[test]
  fn core_effects_come_from_declared_tags() {
    let index = TagIndex::load().expect("load core tags");
    assert_eq!(core_kinds(&index, "read-file"), strings(&["io/file"]));
    assert_eq!(core_kinds(&index, "&read-file"), strings(&["io/file"]));
    assert_eq!(core_kinds(&index, "&read-dir"), strings(&["io/file"]));
    for name in ["add-watch!", "remove-watch!"] {
      assert!(is_state_operator(name));
      assert_eq!(core_kinds(&index, name), strings(&["state/watch"]), "{name}");
    }
    for name in ["monotonic-time-ms", "unix-time-ms", "wait-ms", "read-stdin-text", "generate-id!"] {
      assert_eq!(core_kinds(&index, name), strings(&["io"]), "{name}");
    }
    assert_eq!(core_kinds(&index, "get-env"), strings(&["env"]));
    assert_eq!(core_kinds(&index, "quit!"), strings(&["control"]));
    for name in ["unreachable!", "&unreachable!"] {
      assert_eq!(core_kinds(&index, name), strings(&["control"]), "{name}");
    }
    assert_eq!(core_kinds(&index, "try-read-dir"), strings(&["io/file"]));
    assert_eq!(core_kinds(&index, "&init-builtin-impls!"), strings(&["effect"]));
    assert_eq!(core_kinds(&index, "&reset-gensym-index!"), strings(&["effect"]));
  }

  #[test]
  fn unmarked_lifecycle_methods_are_effects_through_core_impl_tags() {
    let index = TagIndex::load().expect("load core tags");
    for method in ["cancel!", "cancel-with!", "resolve!", "reject!"] {
      assert_eq!(index.core_methods.get(method), Some(&strings(&["effect"])), "{method}");
    }
    for method in ["write-text!", "read-text", "read-dir", "walk-dir"] {
      assert_eq!(index.core_methods.get(method), Some(&strings(&["io/file"])), "{method}");
    }
    // `empty?` / `contains?` include inline enum/struct impls; they inherit the owner's tags.
    for method in ["map", "get", "unwrap", "to-string", "empty?", "contains?"] {
      assert_eq!(index.core_methods.get(method), Some(&vec![]), "{method}");
    }
  }

  #[test]
  fn name_spelling_no_longer_decides_effects() {
    let index = TagIndex::load().expect("load core tags");
    // These names contain `init` / `load`, which used to be reported as `io`.
    for name in ["data-definition-form", "enum-definition", "&struct:definition", "&enum:definition"] {
      assert!(core_kinds(&index, name).is_empty(), "{name}");
    }
    // An undeclared target is `unknown`, whatever its spelling.
    for name in ["load-config", "setup-app!", "render!"] {
      assert_eq!(classify_call(name, None), strings(&[UNKNOWN_EFFECT_KIND]), "{name}");
    }
  }

  #[test]
  fn registered_procs_use_descriptor_tags_or_report_unknown() {
    fn noop(_xs: Vec<Calcit>, _call_stack: &calcit_core::call_stack::CallStackList) -> Result<Calcit, calcit_core::calcit::CalcitErr> {
      Ok(Calcit::Nil)
    }
    let tagged = "effects-graph-test-tagged-proc";
    let untagged = "effects-graph-test-untagged-proc";
    builtins::register_import_proc_with_descriptor(
      tagged,
      noop,
      builtins::RegisteredProcDescriptor {
        tags: proc_tags(["log", "io"]),
        ..Default::default()
      },
    );
    builtins::register_import_proc_with_descriptor(untagged, noop, builtins::RegisteredProcDescriptor::default());
    assert_eq!(classify_call(tagged, None), strings(&["console"]));
    assert_eq!(classify_call(untagged, None), strings(&[UNKNOWN_EFFECT_KIND]));
  }

  #[test]
  fn core_procs_and_syntax_declare_effect_tags() {
    use strum::IntoEnumIterator;
    let snapshot = calcit_core::load_core_snapshot().expect("load core");
    let core = snapshot.files.get("calcit.core").expect("calcit.core");
    let hidden_procs: HashSet<&str> = HIDDEN_CORE_PROC_TAGS.iter().map(|(proc, _)| proc.as_ref()).collect();
    for proc in CalcitProc::iter() {
      let name = proc.as_ref();
      assert_eq!(
        core.defs.contains_key(name),
        !hidden_procs.contains(name),
        "proc `{proc}` needs exactly one effect declaration: a calcit.core entry or HIDDEN_CORE_PROC_TAGS"
      );
    }
    let hidden_syntax: HashSet<String> = HIDDEN_CORE_SYNTAX_TAGS.iter().map(|(syntax, _)| syntax.to_string()).collect();
    for syntax in CalcitSyntax::iter() {
      let name = syntax.to_string();
      assert_eq!(
        core.defs.contains_key(&name),
        !hidden_syntax.contains(&name),
        "syntax `{name}` needs exactly one effect declaration: a calcit.core entry or HIDDEN_CORE_SYNTAX_TAGS"
      );
    }
  }

  fn collect_node_effects(node: &EffectsGraphNode, out: &mut HashMap<String, Vec<(String, String)>>) {
    if !node.circular && !node.seen {
      out
        .entry(node.def.clone())
        .or_insert_with(|| node.effects.iter().map(|e| (e.kind.clone(), e.target.clone())).collect());
    }
    for child in &node.children {
      collect_node_effects(child, out);
    }
  }

  #[test]
  fn fixture_reports_declared_effects_and_unknown_targets() {
    let _guard = calcit_core::program::lock_program_test_state();
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../calcit/test-effects-graph.cirru");
    let content = std::fs::read_to_string(&path).expect("read effects-graph fixture");
    let data = cirru_edn::parse(&content).expect("parse fixture");
    let mut snapshot = calcit_core::snapshot::load_snapshot_data(&data, path.to_string_lossy().as_ref()).expect("load fixture");
    let core = calcit_core::load_core_snapshot().expect("load core");
    for (k, v) in core.files {
      snapshot.files.insert(k, v);
    }
    {
      let mut program = calcit_core::program::PROGRAM_CODE_DATA.write().expect("program data");
      *program = calcit_core::program::extract_program_data(&snapshot).expect("extract program");
    }

    let result =
      analyze_effects_graph("test-effects-graph.main", "main!", false, 0, None, EffectsGraphDetail::Summary).expect("analyze fixture");
    let mut effects = HashMap::new();
    collect_node_effects(&result.tree, &mut effects);
    let pair = |kind: &str, target: &str| vec![(kind.to_string(), target.to_string())];

    assert_eq!(effects["io-helper"], pair("io/file", "read-file"));
    // Neither a `load-` prefix nor a trailing `!` makes a pure definition effectful.
    assert_eq!(effects["load-config"], vec![]);
    assert_eq!(effects["setup!"], vec![]);
    // Unmarked writes are found through core tags.
    assert_eq!(effects["watch-helper"], pair("state/watch", "remove-watch!"));
    assert_eq!(effects["cancel-helper"], pair("effect", ".cancel!"));
    assert_eq!(effects["write-helper"], pair("io/file", ".write-text!"));
    // Calling a parameter calls a function value supplied by the caller.
    assert_eq!(effects["call-through"], pair(UNKNOWN_EFFECT_KIND, "f"));
    assert_eq!(effects["js-helper"], pair("interop/js", "js/console.log"));
    assert_eq!(effects["native-method-helper"], pair("interop/js", ".!focus"));
    assert_eq!(effects["missing-helper"], pair(UNKNOWN_EFFECT_KIND, "missing.ns/thing"));
    // Core collection methods stay declared when the project has no same-name defimpl.
    assert_eq!(effects["collection-helper"], vec![]);
    // Only `(:async true)` in a `hint-fn` schema declares async.
    assert_eq!(effects["sync-hint-helper"], vec![]);
    assert_eq!(effects["async-hint-helper"], pair("async", "hint-fn"));
    // Parameter lists, binding pairs and `case` clauses that start with a parameter are not calls.
    assert_eq!(effects["binding-helper"], vec![]);
    // An async callback type in `:args` does not make the enclosing function async.
    assert_eq!(effects["nested-async-hint-helper"], vec![]);
    // A parameter of an inner `fn` is scoped to that `fn`; the outer call still reaches the definition.
    assert_eq!(effects["scope-helper"], pair(UNKNOWN_EFFECT_KIND, "io-helper"));
    let scope_node = find_node(&result.tree, "scope-helper").expect("scope-helper node");
    assert_eq!(scope_node.effects[0].count, 1);
    assert!(
      scope_node
        .transform
        .calls
        .contains(&"test-effects-graph.main/io-helper".to_string())
    );
    // `let`, `let[]` and `&doseq` bindings shadow parameters; only `&doseq`'s own tag remains.
    assert_eq!(effects["shadow-helper"], pair("effect", "&doseq"));
    // `:tags` on a project definition is an explicit declaration, reported at its call sites;
    // the callee's own pure body adds nothing.
    assert_eq!(
      effects["declared-caller"],
      pair("effect", "test-effects-graph.main/declared-helper")
    );
    assert_eq!(effects["declared-helper"], vec![]);
    // A non-effect tag is ignored; an effect tag next to it is recorded; a definition in another
    // namespace is reported as `ns/def`. Rows come out sorted by kind.
    assert_eq!(
      effects["tag-caller"],
      vec![
        ("console".to_string(), "test-effects-graph.main/mixed-tagged".to_string()),
        ("io/file".to_string(), "test-effects-graph.lib/lib-effect".to_string()),
      ]
    );
    assert_eq!(effects["deprecated-only"], vec![]);
    assert_eq!(effects["mixed-tagged"], vec![]);
  }

  fn find_node<'a>(node: &'a EffectsGraphNode, def: &str) -> Option<&'a EffectsGraphNode> {
    if node.def == def && !node.seen {
      return Some(node);
    }
    node.children.iter().find_map(|child| find_node(child, def))
  }

  fn parse_ref_call(head: &str, args: &[&str]) -> Calcit {
    let mut items = vec![cirru_parser::Cirru::leaf(head)];
    items.extend(args.iter().map(|a| cirru_parser::Cirru::leaf(*a)));
    calcit_core::data::cirru::code_to_calcit(&cirru_parser::Cirru::List(items), "app.main", "demo", vec![]).expect("parse ref call")
  }

  #[test]
  fn ref_constructors_read_initializer_at_their_own_position() {
    for (head, args, name) in [("ref", vec!["1"], "?"), ("defref", vec!["*counter", "1"], "*counter")] {
      let code = parse_ref_call(head, &args);
      let Calcit::List(list) = &code else {
        panic!("expected list for {head}");
      };
      let target = extract_state_target(Some(list), head);
      assert_eq!(target, name, "target for {head}");
      let mut state = vec![];
      record_state_operator(head, &target, Some(list), "app.main", &mut state);
      assert_eq!(state.len(), 1);
      assert_eq!(state[0].kind, "atom-def");
      assert_eq!(state[0].type_hint.as_deref(), Some(":number  init=1"), "state hint for {head}");
      assert_eq!(
        extract_defref_init_from_code(&code, "app.main").as_deref(),
        Some(":number  init=1"),
        "schema hint for {head}"
      );
    }
  }

  #[test]
  fn summarize_number_init_expr() {
    let init = Calcit::Number(0.0);
    assert_eq!(summarize_init_expr(&init, "app.main").as_deref(), Some(":number  init=0"));
  }

  #[test]
  fn expand_store_schema_when_msg_buffer_available() {
    let _guard = calcit_core::program::lock_program_test_state();
    let path = std::path::Path::new("/Users/jon.chen/repo/termina/msg-buffer/calcit.cirru");
    if !path.exists() {
      return;
    }
    let content = std::fs::read_to_string(path).expect("read msg-buffer snapshot");
    let data = cirru_edn::parse(&content).expect("parse snapshot");
    let mut snapshot = calcit_core::snapshot::load_snapshot_data(&data, path.to_string_lossy().as_ref()).expect("load snapshot");
    let core = calcit_core::load_core_snapshot().expect("load core");
    for (k, v) in core.files {
      snapshot.files.insert(k, v);
    }
    {
      let mut prgm = calcit_core::program::PROGRAM_CODE_DATA.write().expect("program data");
      *prgm = calcit_core::program::extract_program_data(&snapshot).expect("extract program");
    }

    let resolved = resolve_type_ref_path("schema/store", "app.main").expect("resolve schema/store");
    assert_eq!(resolved.0, "app.schema");
    assert_eq!(resolved.1, "store");

    let code = lookup_def_code(&resolved.0, &resolved.1).expect("lookup store code");
    let template = find_best_struct_template(&code);
    assert!(template.is_some(), "struct template not found in code: {code:?}");

    let expanded = expand_type_ref_path("schema/store", "app.main", MAX_SCHEMA_DEPTH).expect("expand schema/store");
    assert!(expanded.contains(":states"), "expected store fields, got: {expanded}");
  }

  #[test]
  fn schema_hint_parses_segment_to_edn() {
    let hint = "{ :records :list [], :base :nil, :stopped? :bool }";
    let edn = parse_schema_segment(hint).expect("parse struct");
    let lines = format_schema_edn_lines(&edn);
    let joined = lines.join("\n");
    assert!(joined.contains(":records"));
    assert!(joined.contains(":list"));
    assert!(joined.contains(":base"));
  }

  #[test]
  fn schema_edn_preserves_indentation() {
    let hint = "{ :base { :cursor :list [], :count :number }, :store :nil }";
    let edn = parse_schema_segment(hint).expect("parse nested struct");
    let raw = cirru_edn::format(&edn, true).expect("format edn");
    assert!(
      raw.lines().any(|line| line.starts_with(' ') || line.starts_with('\t')),
      "expected cirru edn indent, got:\n{raw}"
    );

    let lines = format_schema_edn_lines(&edn);
    assert!(
      lines.iter().any(|line| line.starts_with(' ') || line.starts_with('\t')),
      "expected preserved indent, got:\n{}",
      lines.join("\n")
    );
  }

  #[test]
  fn long_schema_renders_as_indented_subtree() {
    let hint = "reel-schema/reel = { :records :list [], :base :nil, :store :nil, :pointer :nil, :stopped? :bool, :display? :bool, :merged? :bool } { :base { :states { :cursor :list [] }, :sessions :list [] }, :store { :states { :cursor :list [] } } }";
    assert!(schema_should_embed(hint));

    let result = EffectsGraphResult {
      entry: "app.main/main!".into(),
      tree: EffectsGraphNode {
        ns: "app.main".into(),
        def: "main!".into(),
        fqn: "app.main/main!".into(),
        doc: None,
        source: "project".into(),
        state: vec![StateItem {
          kind: "watch".into(),
          name: "*reel".into(),
          type_hint: Some(hint.to_string()),
        }],
        transform: TransformInfo::default(),
        effects: vec![],
        children: vec![],
        circular: false,
        seen: false,
        depth_exceeded: false,
      },
      stats: EffectsGraphStats {
        reachable_count: 1,
        effect_sites: 0,
        state_items: 1,
        max_depth: 0,
        subgraph_count: 1,
      },
      display: EffectsGraphDisplayMeta {
        max_depth_limit: 2,
        detail: "summary".into(),
        include_core: false,
        ns_prefix: None,
        package_root: Some("app".into()),
      },
    };

    let text = format_as_ste_tree(&result, false);
    assert!(text.contains("watch    *reel\n"));
    assert!(!text.contains("schema: reel-schema"));
    assert!(text.contains("└── schema"));
    assert!(text.contains("reel-schema/reel ="));
    assert!(text.contains(":records"));
    assert!(text.contains(":base"));
  }

  #[test]
  fn duplicate_atom_reads_merge_in_display() {
    let result = EffectsGraphResult {
      entry: "app.main/render!".into(),
      tree: EffectsGraphNode {
        ns: "app.main".into(),
        def: "render!".into(),
        fqn: "app.main/render!".into(),
        doc: None,
        source: "project".into(),
        state: vec![
          StateItem {
            kind: "atom-read".into(),
            name: "*reel".into(),
            type_hint: None,
          },
          StateItem {
            kind: "atom-read".into(),
            name: "*reel".into(),
            type_hint: None,
          },
        ],
        transform: TransformInfo::default(),
        effects: vec![],
        children: vec![],
        circular: false,
        seen: false,
        depth_exceeded: false,
      },
      stats: EffectsGraphStats {
        reachable_count: 1,
        effect_sites: 0,
        state_items: 2,
        max_depth: 0,
        subgraph_count: 1,
      },
      display: EffectsGraphDisplayMeta {
        max_depth_limit: 2,
        detail: "summary".into(),
        include_core: false,
        ns_prefix: None,
        package_root: Some("app".into()),
      },
    };

    let text = format_as_ste_tree(&result, false);
    assert_eq!(text.matches("atom     *reel (read)").count(), 1);
    assert!(text.contains("(×2)"));
  }

  #[test]
  fn ste_tree_shows_inputs_and_output_sections() {
    let result = EffectsGraphResult {
      entry: "app.main/main!".into(),
      tree: EffectsGraphNode {
        ns: "app.main".into(),
        def: "dispatch!".into(),
        fqn: "app.main/dispatch!".into(),
        doc: None,
        source: "project".into(),
        state: vec![
          StateItem {
            kind: "param".into(),
            name: "event".into(),
            type_hint: Some(":map".into()),
          },
          StateItem {
            kind: "return".into(),
            name: "return".into(),
            type_hint: Some(":nil".into()),
          },
        ],
        transform: TransformInfo::default(),
        effects: vec![],
        children: vec![],
        circular: false,
        seen: false,
        depth_exceeded: false,
      },
      stats: EffectsGraphStats {
        reachable_count: 1,
        effect_sites: 0,
        state_items: 2,
        max_depth: 0,
        subgraph_count: 1,
      },
      display: EffectsGraphDisplayMeta {
        max_depth_limit: 2,
        detail: "summary".into(),
        include_core: false,
        ns_prefix: None,
        package_root: Some("app".into()),
      },
    };

    let text = format_as_ste_tree(&result, false);
    assert!(text.contains("├── Inputs"));
    assert!(text.contains("in       event"));
    assert!(text.contains("├── Output"));
    assert!(text.contains("out      :nil"));
  }

  #[test]
  fn ste_tree_contains_core_sections() {
    let result = EffectsGraphResult {
      entry: "app.main/main!".into(),
      tree: EffectsGraphNode {
        ns: "app.main".into(),
        def: "main!".into(),
        fqn: "app.main/main!".into(),
        doc: None,
        source: "project".into(),
        state: vec![],
        transform: TransformInfo::default(),
        effects: vec![EffectItem {
          kind: "console".into(),
          target: "println".into(),
          count: 1,
        }],
        children: vec![EffectsGraphNode {
          ns: "app.main".into(),
          def: "dispatch!".into(),
          fqn: "app.main/dispatch!".into(),
          doc: Some("state update handler".into()),
          source: "project".into(),
          state: vec![],
          transform: TransformInfo::default(),
          effects: vec![],
          children: vec![],
          circular: false,
          seen: false,
          depth_exceeded: false,
        }],
        circular: false,
        seen: false,
        depth_exceeded: false,
      },
      stats: EffectsGraphStats {
        reachable_count: 2,
        effect_sites: 1,
        state_items: 0,
        max_depth: 1,
        subgraph_count: 1,
      },
      display: EffectsGraphDisplayMeta {
        max_depth_limit: 2,
        detail: "summary".into(),
        include_core: false,
        ns_prefix: None,
        package_root: Some("app".into()),
      },
    };

    let text = format_as_ste_tree(&result, false);
    assert!(text.contains("# Effects Graph"));
    assert!(text.contains("main/main!"));
    assert!(!text.contains("app.main/main!"));
    assert!(text.contains("console"));
    assert!(text.contains("println"));
    assert!(text.contains("[program]"));
  }
}