bat-cli 0.32.0

Blockchain Auditor Toolkit (BAT)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
//! Which contracts talk to which, on one frame.
//!
//! The question this answers is the one a reader cannot get from reading functions: a function
//! calls here and there, and after forty of them you still do not know that three different
//! contracts write to the same one, or that a contract you thought was a leaf is wired into
//! five others at construction. `deploy` shows one entry point in full depth; this shows the
//! system's shape and nothing else.
//!
//! An edge is a RELATION, not a count. One call is a relation; forty calls are the same
//! relation, and how many there are is a question for the entry point's own diagram. What the
//! edge does carry is its KIND — an ordinary call, an address fixed at construction, or a
//! binding nobody has resolved yet — because those are three different facts about the system.

use std::collections::{BTreeMap, BTreeSet};

use colored::Colorize;
use error_stack::{Report, Result, ResultExt};

use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata};
use crate::batbelt::evm::miro::auto_deploy::matches_ignore;
use crate::batbelt::evm::miro::EvmMiroError;
use crate::batbelt::miro::client::{ArrowEnd, ConnectorStroke, ConnectorStyle, MiroClient};
use crate::batbelt::miro::layout::{GraphLayout, PlacedNode};

pub struct MapOptions {
    /// Write a PNG of the map here instead of drawing it, so a layout can be judged without
    /// a board. Every change to how the arrows run used to cost a deployment to look at.
    pub preview: Option<String>,
    /// Print the relations and stop, touching no board.
    pub dry_run: bool,
    /// Draw only this contract's frame — "what does X talk to", on its own.
    ///
    /// The map is one frame per top caller, and most readings are about one of them. Drawing
    /// the whole block to look at one contract costs the board a dozen frames nobody asked for.
    pub contract: Option<String>,
    /// List which contracts are the hierarchy's two ends and stop, touching no board.
    ///
    /// The top callers are the frames the map has; the foundations are what everything else
    /// needs in order to exist. Both are read off the relations, and neither is something the
    /// auditor can get by reading the file tree.
    pub hierarchy: bool,
    /// Leave out the contracts with no source in this repository.
    ///
    /// They are drawn by default. They used to be a text panel on the grounds that giving
    /// somebody else's token the same shape as the code under review is misleading — but what
    /// the audit actually asks is "what does this thing touch that I cannot read", and a name
    /// in a list beside the picture is not an answer to that. They are boxes now, grey ones,
    /// and the flag is for the rare read where only this repository matters.
    pub no_boundaries: bool,
}

/// What kind of relation one contract has with another.
///
/// Ordered by how sure we are of it, which is also the order they are drawn in: a call the
/// scan pinned, then an address fixed at construction, then a binding that is still a guess.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Relation {
    /// A call whose target this scan pinned to one contract.
    Calls,
    /// `new X(...)`: this contract DEPLOYS that one. A fact nothing else on the map carries —
    /// a factory is why its product exists at all, and the address came from here rather than
    /// from a constructor argument.
    Creates,
    /// An address this contract fixes when it is built — `immutable vault = …` in a
    /// constructor. It is a relation even if no call to it survived the pruning: it says the
    /// two are wired together.
    WiresAtConstruction,
    /// A call on an interface with more than one implementer and no `bat-cli resolve` for it.
    /// Drawn dashed: there IS a relation here, and its far end is not known.
    Unresolved,
    /// A call leaving the audited code: a contract with no source in this repository.
    Boundary,
}

impl Relation {
    fn label(self) -> &'static str {
        match self {
            Self::Calls => "calls",
            Self::Creates => "creates",
            Self::WiresAtConstruction => "wires at construction",
            Self::Unresolved => "unresolved binding",
            Self::Boundary => "leaves the code",
        }
    }
}

/// `from` → `to`, and what kind of relation it is. One per pair and kind, never one per call.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Edge {
    pub from: String,
    pub to: String,
    pub relation: Relation,
}

pub async fn run(options: MapOptions) -> Result<(), EvmMiroError> {
    // Timed out loud. "It takes a while" is not something to guess about: each phase says how
    // long it took, so the next question is about a number instead of a feeling.
    let started = std::time::Instant::now();
    let mut mark = |what: &str, since: &mut std::time::Instant| {
        println!("    {:>6.1}s  {what}", since.elapsed().as_secs_f64());
        *since = std::time::Instant::now();
    };
    let mut phase = started;
    let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    mark("reading the metadata", &mut phase);
    // A scan from before the `vendored` flag marks nothing as vendored, so `lib/` — forge-std,
    // OpenZeppelin, the test harnesses — is "in scope" and the map is a map of the test
    // framework. That is not a map with a few extra boxes; it is the wrong picture, and the
    // only honest answer is to stop and say what to run.
    if let Some(count) = predates_vendored(&metadata) {
        return Err(Report::new(EvmMiroError).attach_printable(format!(
            "this scan predates the `vendored` flag: {count} contract(s) under lib/ are marked \
             as in scope — run `bat-cli sonar` to rescan before drawing the map"
        )));
    }
    // The hierarchy, and nothing else: which contracts the map makes a frame for, and which
    // ones everything else needs in order to exist. Answered from the relations, before any
    // layout, because it is a question about the system and not about a picture.
    if options.hierarchy {
        for line in hierarchy(&relations(&metadata), options.no_boundaries) {
            println!("{line}");
        }
        return Ok(());
    }
    let mut prepared = prepare(&metadata, &options)?;
    // One contract's frame, when that is what was asked for. Named rather than silently
    // ignored: a flag that matches nothing and draws everything is worse than an error.
    if let Some(wanted) = options.contract.as_deref() {
        prepared.keep_only(wanted)?;
    }
    let edges = prepared.edges.clone();
    mark("working out the relations, laying out and rendering", &mut phase);

    for line in report(&edges) {
        println!("{line}");
    }
    // An interface declared in this repository that nothing in scope says it implements is
    // drawn as the outside — which is right for `IMirrorFactory` and wrong for an
    // `IListingLaunchpad` that `ListingDesk` implements without `is`. The source cannot tell
    // the two apart; the auditor can, and the line says how to record it.
    let undeclared = undeclared_interfaces(&metadata);
    if !undeclared.is_empty() {
        println!();
        println!(
            "{} interface(s) of this repository nothing in scope declares to implement — \
             treated as outside the code:",
            undeclared.len()
        );
        for name in &undeclared {
            println!("  {name:<28} if a contract here implements it: bat-cli resolve {name} <Contract>");
        }
    }
    // Calls the scan could not type as a contract are not on the map, and a map that leaves
    // something out without saying so is a map the reader trusts more than it deserves.
    let alone = unconnected(&metadata, &prepared.edges);
    if !alone.is_empty() {
        println!();
        println!(
            "{} deployable contract(s) with no relation at all — in the strip at the right, \
             apart from the diagram:",
            alone.len()
        );
        for name in &alone {
            println!("  {name}");
        }
    }
    let created_elsewhere = vendored_creations(&metadata);
    if !created_elsewhere.is_empty() {
        println!();
        println!(
            "{} `new` of code this repository does not own — not drawn:",
            created_elsewhere.len()
        );
        for line in &created_elsewhere {
            println!("  {line}");
        }
    }
    let untyped = untyped_receivers(&metadata);
    if !untyped.is_empty() {
        println!();
        println!(
            "{} call(s) whose receiver the scan could not type as a contract — not drawn:",
            untyped.len()
        );
        for line in &untyped {
            println!("  {line}");
        }
    }
    println!();
    for line in prepared.estimate() {
        println!("  {line}");
    }
    let calls = prepared.calls;

    if let Some(path) = options.preview.as_deref() {
        preview(&prepared, path)?;
    }
    if options.dry_run {
        prepared.discard();
        return Ok(());
    }

    let client = MiroClient::new_refreshed().await.change_context(EvmMiroError)?;
    mark("opening the Miro session", &mut phase);
    let board = client.list_frames().await.change_context(EvmMiroError)?;
    mark(&format!("reading the board ({} frames)", board.len()), &mut phase);
    // To the LEFT of everything. The deployments march rightwards, so a map put on that side
    // ends up wedged between two groups it has nothing to do with, and stays there as the
    // board grows. The left edge is the one side nothing else claims.
    //
    // Nothing is replaced: a second `map` is a second frame, and where it belongs on the board
    // is the auditor's call, not this tool's.
    let obstacles: Vec<crate::batbelt::miro::layout::Rect> = board
        .iter()
        .map(|frame| crate::batbelt::miro::layout::Rect {
            x: frame.x,
            y: frame.y,
            width: frame.width,
            height: frame.height,
        })
        .collect();
    // Measured first, because opening on the left means knowing how wide the thing is.

    let (left, top) =
        crate::batbelt::miro::layout::ColumnLayout::new().open_left(&obstacles, prepared.width);
    let outcome = draw(&client, prepared, left, top).await;
    mark("drawing it", &mut phase);

    // What was drawn goes into the registry, and the clusters get their cards — both only for
    // a FULL map: `--contract` draws one frame, and rewriting every cluster's cards from it
    // would leave each cluster pointing at the one frame that happened to be redrawn.
    if let Ok(drawn) = outcome.as_ref() {
        let whole_map = options.contract.is_none();
        match record_map(drawn.clone(), whole_map, &client).await {
            Ok(cards) if whole_map => {
                println!("    {} {cards} card(s) on the clusters", "✓".green())
            }
            Ok(_) => {}
            // The picture is on the board either way; a registry that could not be written is
            // worth a line, not a failed command.
            Err(report) => println!(
                "    {} the map is drawn, but the registry was not updated: {}",
                "note:".yellow(),
                report.current_context()
            ),
        }
        mark("recording it", &mut phase);
    }

    let (retries, waits) = client.stats();
    println!(
        "    {:>6.1}s  in total  ({} API call(s), {retries} retr(ies), {waits} budget wait(s))",
        started.elapsed().as_secs_f64(),
        calls.total()
    );
    outcome.map(|_| ())
}

/// What a card is: how far above the cluster's label it sits, and how big.
///
/// Above the shape, because the shape is the group's anchor — read from the board every run,
/// since the auditor moves it — and because the column under it is where the deployments go.
/// Sized to be read at the zoom where a whole group fits, which is the only zoom anybody looks
/// at a cluster's heading from. The first try was 2 600 × 260 with 90-point text — legible with
/// the board at 100%, a chip at any useful distance, next to a name shape 1 200 units tall.
const CARD_HEIGHT: f64 = 560.0;
const CARD_WIDTH: f64 = 4_600.0;
const CARD_GAP: f64 = 200.0;
const CARD_FONT: usize = 180;
const CARD_FILL: &str = "#ffffff";
/// The one colour on the board that means "go there".
const CARD_BORDER: &str = "#1a73e8";
/// At most this many cards over one cluster; past it the last one counts the rest.
const MAX_CARDS: usize = 4;

/// Record what the map drew, and give every cluster a card per frame that shows its contract.
///
/// Returns how many cards were created.
///
/// Three rules the auditor set, and they are the whole design:
/// - a card per FRAME, because the frame is where the hierarchy is read — parents and children
///   are in the picture, so the card only has to take you there;
/// - the cluster must NOT depend on the map: no record, no cards, no error;
/// - a redrawn map replaces its own cards rather than stacking new ones on the old.
async fn record_map(
    frames: Vec<crate::batbelt::evm::metadata::bat_metadata::MapFrameRef>,
    whole_map: bool,
    client: &MiroClient,
) -> Result<usize, EvmMiroError> {
    use crate::batbelt::evm::metadata::bat_metadata::{MapCardRef, MapFrameRef};

    let mut metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    if !whole_map {
        // One frame redrawn: keep it in the registry by its root, and leave the cards alone —
        // they describe a map this run did not replace.
        let mut kept: Vec<MapFrameRef> = metadata
            .miro
            .map
            .iter()
            .filter(|old| !frames.iter().any(|new| new.root == old.root))
            .cloned()
            .collect();
        kept.extend(frames);
        metadata.miro.map = kept;
        metadata.save_metadata().change_context(EvmMiroError)?;
        return Ok(0);
    }

    // The cards this tool put up last time, gone before new ones go up: a card pointing at a
    // frame that no longer exists is worse than no card, and they would otherwise stack.
    //
    // Found on the BOARD and not only in the registry. The registry is a convenience and it can
    // be lost — a binary that did not know the `miro.map` field rewrote `BatMetadata.json`
    // without it, and the next run drew a second set of cards on top of the first, which is
    // exactly what the auditor saw. A card carries its own signature in its text, so the board
    // can always be asked.
    let mut stale: Vec<String> = metadata
        .miro
        .map
        .iter()
        .flat_map(|frame| frame.cards.iter().map(|card| card.item_id.clone()))
        .collect();
    if let Ok(loose) = client.list_loose_shapes().await {
        stale.extend(
            loose
                .into_iter()
                .filter(|(_, content)| is_map_card(content))
                .map(|(id, _)| id),
        );
    }
    stale.sort();
    stale.dedup();
    let mut removing = tokio::task::JoinSet::new();
    for id in stale {
        let client = client.clone();
        removing.spawn(async move { client.delete_item(&id).await });
    }
    while removing.join_next().await.is_some() {}

    // Where each cluster's cards go: above its label shape, which is read from the board
    // because the auditor drags groups around. Every geometry asked for at once.
    let columns: Vec<(String, String)> = metadata
        .miro
        .auto
        .columns
        .iter()
        .filter(|column| !column.label_id.is_empty())
        .map(|column| (column.contract.clone(), column.label_id.clone()))
        .collect();
    let made = draw_cards(&columns, &frames, client).await;
    metadata.miro.map = frames
        .into_iter()
        .map(|mut frame| {
            frame.cards = made
                .iter()
                .filter(|(_, root, _)| *root == frame.root)
                .map(|(contract, _, id)| MapCardRef {
                    contract: contract.clone(),
                    item_id: id.clone(),
                })
                .collect();
            frame
        })
        .collect();
    metadata.save_metadata().change_context(EvmMiroError)?;
    Ok(made.len())
}

/// Put one card per frame over each of these clusters, and say which card is whose.
///
/// Returns `(cluster contract, frame root, item id)` per card made. Everything it can ask for
/// at once it asks for at once: the geometries in one wave, the cards in batches of twenty.
async fn draw_cards(
    columns: &[(String, String)],
    frames: &[crate::batbelt::evm::metadata::bat_metadata::MapFrameRef],
    client: &MiroClient,
) -> Vec<(String, String, String)> {
    let mut asking = tokio::task::JoinSet::new();
    for (contract, label_id) in columns {
        let client = client.clone();
        let (contract, label_id) = (contract.clone(), label_id.clone());
        asking.spawn(async move { (contract, client.item_geometry(&label_id).await) });
    }
    let mut anchors: BTreeMap<String, (f64, f64)> = BTreeMap::new();
    while let Some(Ok((contract, geometry))) = asking.join_next().await {
        if let Some((x, y, _, height)) = geometry {
            anchors.insert(contract, (x, y - height / 2.0));
        }
    }

    struct Planned {
        contract: String,
        root: String,
        item: serde_json::Value,
    }
    let mut planned: Vec<Planned> = Vec::new();
    for (contract, (centre, top)) in &anchors {
        let showing = frames_showing(frames, contract);
        if showing.is_empty() {
            continue;
        }
        let drawn = showing.len().min(MAX_CARDS);
        let span = drawn as f64 * CARD_WIDTH + (drawn as f64 - 1.0) * CARD_GAP;
        for (index, frame) in showing.iter().take(MAX_CARDS).enumerate() {
            let x = centre - span / 2.0 + CARD_WIDTH / 2.0 + index as f64 * (CARD_WIDTH + CARD_GAP);
            let y = top - CARD_GAP - CARD_HEIGHT / 2.0;
            // The words carry the fact, the anchor carries the jump. A map can be deleted and
            // the card still says which frame showed this contract — `linkedTo` is not
            // reachable from the REST API, so the link has always been an `<a href>` in the
            // text (see CLAUDE.md).
            let left = showing.len().saturating_sub(MAX_CARDS);
            let text = if index + 1 == MAX_CARDS && left > 0 {
                format!("map · {} (+{left} more)", frame.root)
            } else {
                format!("map · {}", frame.root)
            };
            planned.push(Planned {
                contract: contract.clone(),
                root: frame.root.clone(),
                item: MiroClient::link_card_item(
                    &text,
                    &client.frame_url(&frame.frame_id),
                    x,
                    y,
                    CARD_WIDTH,
                    CARD_HEIGHT,
                    CARD_FONT,
                    CARD_FILL,
                    CARD_BORDER,
                ),
            });
        }
    }

    const BATCH: usize = 20;
    let mut making = tokio::task::JoinSet::new();
    for chunk in planned.chunks(BATCH) {
        let client = client.clone();
        let keys: Vec<(String, String)> = chunk
            .iter()
            .map(|card| (card.contract.clone(), card.root.clone()))
            .collect();
        let items: Vec<serde_json::Value> = chunk.iter().map(|card| card.item.clone()).collect();
        making.spawn(async move { (keys, client.create_items_bulk(items).await) });
    }
    let mut made: Vec<(String, String, String)> = Vec::new();
    while let Some(joined) = making.join_next().await {
        if let Ok((keys, Ok(ids))) = joined {
            for ((contract, root), id) in keys.into_iter().zip(ids) {
                made.push((contract, root, id));
            }
        }
    }
    made
}

/// Is this loose shape one of the map's cards?
///
/// Its own signature and nothing looser: the `map · ` prefix the card is written with AND a link
/// to a frame. A shape an auditor wrote by hand does not carry both, and deleting one of theirs
/// would be unforgivable — this is the only place this tool removes something it is not holding
/// an id for.
fn is_map_card(content: &str) -> bool {
    content.contains("map · ") && content.contains("moveToWidget=")
}

/// The frames that draw this contract — the ones its cluster gets a card for.
fn frames_showing<'a>(
    frames: &'a [crate::batbelt::evm::metadata::bat_metadata::MapFrameRef],
    contract: &str,
) -> Vec<&'a crate::batbelt::evm::metadata::bat_metadata::MapFrameRef> {
    frames
        .iter()
        .filter(|frame| frame.contracts.iter().any(|name| name == contract))
        .collect()
}

/// Give ONE cluster its cards, from the map already in the registry.
///
/// Called by `deploy` when a group is drawn, because a cluster deployed after the map had no
/// way to get them: `map` draws the cards, and when it last ran this column did not exist.
/// Treasury's group went up with none.
///
/// Silent and harmless when there is no map: a cluster must never depend on one.
pub async fn cards_for(contract: &str, client: &MiroClient) -> Result<usize, EvmMiroError> {
    use crate::batbelt::evm::metadata::bat_metadata::MapCardRef;

    let mut metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    if metadata.miro.map.is_empty() {
        return Ok(0);
    }
    let Some(label_id) = metadata
        .miro
        .auto
        .columns
        .iter()
        .find(|column| column.contract == contract)
        .map(|column| column.label_id.clone())
        .filter(|id| !id.is_empty())
    else {
        return Ok(0);
    };

    // This cluster's own old cards, and only its own: another column's are none of this
    // deployment's business.
    let mut removing = tokio::task::JoinSet::new();
    for frame in &metadata.miro.map {
        for card in frame.cards.iter().filter(|card| card.contract == contract) {
            let (client, id) = (client.clone(), card.item_id.clone());
            removing.spawn(async move { client.delete_item(&id).await });
        }
    }
    while removing.join_next().await.is_some() {}

    let frames = metadata.miro.map.clone();
    let made = draw_cards(&[(contract.to_string(), label_id)], &frames, client).await;
    for frame in &mut metadata.miro.map {
        frame.cards.retain(|card| card.contract != contract);
        frame.cards.extend(
            made.iter()
                .filter(|(_, root, _)| root == &frame.root)
                .map(|(contract, _, id)| MapCardRef {
                    contract: contract.clone(),
                    item_id: id.clone(),
                }),
        );
    }
    metadata.save_metadata().change_context(EvmMiroError)?;
    Ok(made.len())
}

/// Size of a contract's box, and the room left around the drawing.
/// Sized for the NAME, not for a frame: a box that fits `StakingQuoteOracle` at a readable
/// size and no more. The first version gave every contract a 2600×700 box with 72-point text
/// in it, so the map was mostly empty box and the arrows between them were hairlines.
const NODE_HEIGHT: f64 = 320.0;
/// What a box that is NOT this repository's code takes: half the height, half the type, and
/// padding to match — see `node_height`.
const OUTSIDE_HEIGHT: f64 = 160.0;
const OUTSIDE_FONT: usize = 60;
const OUTSIDE_CHAR: f64 = 35.0;
const OUTSIDE_PAD: f64 = 80.0;
const NODE_FONT: usize = 120;
/// Roughly the width one character takes at that font, plus room on both sides.
const NODE_CHAR: f64 = 70.0;
const NODE_PAD: f64 = 160.0;
const MAP_MARGIN: f64 = 600.0;
/// Thick enough to read at the zoom where the whole map fits, which is the only zoom it is
/// for. Miro refuses anything from 24 up.
const EDGE_WIDTH: &str = "16";
/// The invisible square a leg lands on, as the deploy sizes it.
const MARKER_SIZE: f64 = 8.0;

/// The one colour an arrow has.
///
/// Colour used to carry two things at once — what KIND of relation, and how SURE the scan
/// was — and four hues for five kinds was one too many to tell apart at the zoom where the
/// whole map fits, which is the only zoom it is for. The kind is the stroke now (`stroke_of`),
/// and colour is kept for the one thing worth a colour: an arrow that runs backwards.
const EDGE_COLOUR: &str = "#1a1a1a";
/// A cycle. Two contracts that each depend on the other is where re-entrancy and ordering
/// bugs live, so the arrow that closes the loop is the one mark on the map that is itself a
/// finding candidate — and it gets the only colour.
const CYCLE_COLOUR: &str = "#f24726";
/// `new X(...)`: this contract DEPLOYED that one, which is a different fact from calling it —
/// the address exists because of this line. It carried the word "creates" on the leg; a colour
/// says the same thing with nothing to read.
///
/// Yellow. A dark green read as a black line at the zoom where a whole frame fits, and a bright
/// one was still lost among the ordinary calls — the colour only earns its place if it is seen
/// before the line it is drawn on.
const CREATES_COLOUR: &str = "#fac710";
const BOX_FILL: &str = "#ffffff";
const BOX_BORDER: &str = "#1a1a1a";

/// A box that is NOT this repository's code, drawn only under `--with-boundaries`: grey, so
/// a token nobody here can read is never mistaken for a contract they can.
const OUTSIDE_FILL: &str = "#e6e6e6";

/// One fill per INTERFACE, per frame.
///
/// Every caller gets its own copy of what it calls outside, which is what keeps the arrows
/// short — but then four boxes reading `IERC20` are four boxes, and nothing says they are the
/// same thing. A colour does: within a frame, every copy of one interface carries one fill and
/// no two interfaces carry the same. Per FRAME and not per map, because a reader compares what
/// is in front of them; across frames the name is the identity.
///
/// Light tints on purpose — the name is read off the box, so the fill sits under black text
/// without competing with the arrows.
const OUTSIDE_FILLS: &[&str] = &[
    "#d9ecff", "#ffe0d6", "#e2f5cf", "#fdf0c2", "#ecdcff", "#cff3f5", "#ffe4cc", "#ffd9ec",
];

/// One border per CONTRACT that this frame draws more than once.
///
/// A frame is a tree, so a contract reached two ways is two boxes — which is what keeps the
/// arrows short, and leaves the reader with two boxes reading `Treasury` and nothing saying they
/// are the same address. The interfaces answer that with their fill; a contract cannot use the
/// fill too, or the two codes collide on a box that is both. So: a contract drawn ONCE keeps the
/// plain border, and one drawn twice or more takes a colour of its own, carried by every copy.
///
/// Saturated, because a 4-unit border has to carry the colour on its own — and neither green nor
/// red, which already mean `creates` and `a cycle` on the arrows.
/// How thick a border is drawn, plain and coloured.
///
/// A coloured border is a SIGNAL, and at 4 units it was invisible at the zoom where a whole
/// frame fits — which is the only zoom the map is read at. The plain one stays thin, because a
/// black border that thick reads as weight rather than as an edge. Miro's ceiling is 24.
const BORDER_WIDTH: usize = 4;
const REPEAT_BORDER_WIDTH: usize = 23;

const REPEAT_BORDERS: &[&str] = &[
    "#1a73e8", "#a259ff", "#00897b", "#e8710a", "#c2185b", "#5d4037", "#1a237e", "#827717",
];
/// The strip's own boxes: present, apart, and visibly not part of the diagram.
const STRIP_FILL: &str = "#f4f4f4";
/// Vertical distance between two arrows meeting the same side of one box. Five arrows into
/// one contract used to land on one point of its border and read as one.
const ANCHOR_PITCH: f64 = 40.0;
/// Kept clear at the top and bottom of a box's side, so no arrow grazes a corner.
const ANCHOR_INSET: f64 = 40.0;

/// The id of the strip's heading, which is a box like the others and must never be confused
/// with a contract that happens to carry that name.
const STRIP_HEADING: &str = "\u{0}not connected in scope";
/// Length of the sample leg beside a legend row.
const LEGEND_SAMPLE: f64 = 700.0;
/// How far under the lowest box a cycle's corridor runs, and how far apart two of them sit.
const CYCLE_GAP: f64 = 240.0;
const CYCLE_PITCH: f64 = 160.0;

/// How far under its box a contract's leaves sit, which is the room the arrows into them need.
const BADGE_GAP: f64 = 30.0;
/// The height a leaf's row takes under its caller, used when a frame is measured.
const BADGE_HEIGHT: f64 = 150.0;

fn node_width(name: &str) -> f64 {
    if is_outside(name) {
        return original_of(name).chars().count() as f64 * OUTSIDE_CHAR + OUTSIDE_PAD * 2.0;
    }
    name.chars().count() as f64 * NODE_CHAR + NODE_PAD * 2.0
}

/// The box an outside leaf gets: half the height, half the type.
///
/// They are the most numerous boxes on a frame — every caller carries its own copy — and the
/// least important: a reader does not scan for `IERC20` from across the board, they read it once
/// they have found the contract that calls it. At the contracts' own size they were most of the
/// frame's area.
fn node_height(id: &str) -> f64 {
    if is_outside(id) {
        OUTSIDE_HEIGHT
    } else {
        NODE_HEIGHT
    }
}

fn node_font(id: &str) -> usize {
    if is_outside(id) {
        OUTSIDE_FONT
    } else {
        NODE_FONT
    }
}

/// How a kind of relation is drawn: its stroke, and — where one word earns its cost — a
/// caption on the leg that carries the head. Three strokes a reader can tell apart at any
/// zoom: solid is a fact, dashed is a question, dotted is wiring nobody calls through.
fn stroke_of(relation: Relation) -> (ConnectorStroke, Option<&'static str>) {
    match relation {
        Relation::Calls => (ConnectorStroke::Solid, None),
        // No caption: a word hung on a leg is a word to read, and `new X(...)` is rare enough
        // that a colour of its own carries it. Green, which nothing else on the map uses.
        Relation::Creates => (ConnectorStroke::Solid, None),
        // Only ever drawn for a pair that is wired and NOT called — a call outranks it — so
        // the word marks the odd case worth a second look.
        Relation::WiresAtConstruction => (ConnectorStroke::Dotted, Some("wired")),
        Relation::Unresolved => (ConnectorStroke::Dashed, Some("?")),
        // The grey box at the far end already says it is outside; the arrow is a call.
        Relation::Boundary => (ConnectorStroke::Solid, None),
    }
}

/// The style of one arrow: its relation's stroke in the one colour, or red when it runs
/// backwards.
fn style_of(relation: Relation, backwards: bool) -> ConnectorStyle {
    let (stroke, caption) = stroke_of(relation);
    let colour = match (backwards, relation) {
        (true, _) => CYCLE_COLOUR,
        (false, Relation::Creates) => CREATES_COLOUR,
        (false, _) => EDGE_COLOUR,
    };
    ConnectorStyle {
        stroke_color: colour.to_string(),
        stroke_width: EDGE_WIDTH.to_string(),
        stroke,
        caption: caption.map(str::to_string),
        arrow: ArrowEnd::End,
    }
}

/// What a legend row shows beside its words.
#[derive(Debug, Clone)]
enum Sample {
    /// A short leg in this style: two markers and one connector, like any arrow.
    Leg(ConnectorStyle),
    /// A box with this fill and border, like any box.
    Box { fill: &'static str, border: &'static str },
}

/// One row of the legend: a box with the words, and beside it the thing the words name.
///
/// The old legend was five boxes each FILLED with its relation's colour, which made sense
/// while colour was the code. With one colour and three strokes a filled box says nothing;
/// the sample is a real leg in the real style, so the reader matches a line to a line.
#[derive(Debug, Clone)]
struct LegendRow {
    text: &'static str,
    sample: Sample,
    /// Frame-local centre of the words' box, and its width.
    x: f64,
    y: f64,
    width: f64,
    /// The sample's two ends, for a `Leg`; the words' own box doubles as the sample for a
    /// `Box` row.
    sample_from: (f64, f64),
    sample_to: (f64, f64),
}

/// The legend, placed: one row per thing a reader can see on the map, in the frame's
/// top-left corner above the first column.
fn legend_rows() -> Vec<LegendRow> {
    let rows: [(&'static str, Sample); 7] = [
        ("calls", Sample::Leg(style_of(Relation::Calls, false))),
        ("green: creates it — `new X(...)`", Sample::Leg(style_of(Relation::Creates, false))),
        ("wired at construction, never called", Sample::Leg(style_of(Relation::WiresAtConstruction, false))),
        ("unresolved binding — a question", Sample::Leg(style_of(Relation::Unresolved, false))),
        ("runs backwards — a cycle", Sample::Leg(style_of(Relation::Calls, true))),
        // Every box on a map is this repository's code now: what leaves it is the grey line
        // under a box, and a contract with a frame of its own is a card.
        ("tinted: no source here — one colour per interface", Sample::Box { fill: OUTSIDE_FILLS[0], border: BOX_BORDER }),
        ("coloured border: the same contract, drawn twice", Sample::Box { fill: BOX_FILL, border: REPEAT_BORDERS[0] }),
    ];
    rows.into_iter()
        .enumerate()
        .map(|(index, (text, sample))| {
            let width = node_width(text);
            let left = MAP_MARGIN / 2.0;
            let y = MAP_MARGIN / 2.0 + index as f64 * (NODE_HEIGHT + 60.0);
            let (sample_from, sample_to) = match sample {
                Sample::Leg(_) => ((left + width + 100.0, y), (left + width + 100.0 + LEGEND_SAMPLE, y)),
                Sample::Box { .. } => ((left, y), (left + width, y)),
            };
            LegendRow { text, sample, x: left + width / 2.0, y, width, sample_from, sample_to }
        })
        .collect()
}

/// One legend row per thing on the map — pinned by a test to `legend_rows()`, because the
/// layout reserves this many rows of height above the first column.
const LEGEND_ROWS: usize = 7;

/// One arrow as it will be drawn: which relation it is (if any — the legend's samples are
/// arrows too), its markers and legs, and its style.
pub(crate) struct RoutedArrow {
    /// Index into the drawn edges; `None` for a legend sample.
    pub(crate) edge: Option<usize>,
    pub(crate) plan: crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow,
    pub(crate) style: ConnectorStyle,
}

/// Where every arrow meets its boxes, and where it runs in between: lanes, corridors and
/// legs, decided with nothing on the board.
///
/// In `prepare` and not in `draw`, because the call count comes from here — an arrow that
/// skips `s` columns is `2s + 2` markers and `2s + 3` legs, and an estimate that assumes one
/// lane per arrow is an estimate that lies the moment the picture needs a corridor.
fn route_arrows(edges: &[Edge], layout: &GraphLayout, with_legend: bool) -> Vec<RoutedArrow> {
    use crate::batbelt::evm::miro::auto_deploy::{plan_lane_chain, LaneEnd, LaneSide, PlannedLaneArrow};
    use crate::batbelt::miro::client::RelativeAnchor;
    use crate::batbelt::miro::layout::{assign_lanes, LANE_PITCH};

    struct Forward<'a> {
        index: usize,
        edge: &'a Edge,
        from: &'a PlacedNode,
        to: &'a PlacedNode,
        /// The gutters crossed, caller's side first.
        gutters: Vec<usize>,
        /// The corridor heights, in the same order: the first is the column beside the caller.
        corridors: Vec<f64>,
    }

    let mut forward: Vec<Forward> = Vec::new();
    let mut backwards: Vec<(usize, &Edge, &PlacedNode, &PlacedNode)> = Vec::new();
    for (index, edge) in edges.iter().enumerate() {
        let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
            continue;
        };
        if to.layer <= from.layer {
            // A cycle: the layout had to reverse it, and it runs back towards the frame's own
            // contract. Drawn red, box to box, routed by Miro — the one arrow allowed to look
            // different is the one that is a finding. It used to be dropped here without a word.
            backwards.push((index, edge, from, to));
            continue;
        }
        // The corridors, CALLER FIRST — which is now the order `insert_bend_points` produces,
        // because the caller is the one in the lower layer. Walking them the other way round
        // put every arrow that skipped two columns through the wrong column's corridor at the
        // wrong height, which is to say through the boxes.
        let corridors: Vec<f64> = layout
            .routes
            .get(index)
            .map(|bends| bends.iter().map(|(_, y)| *y).collect())
            .unwrap_or_default();
        let gutters: Vec<usize> = (from.layer..to.layer).collect();
        forward.push(Forward { index, edge, from, to, gutters, corridors });
    }

    // Where each arrow meets its two boxes. Every arrow used to leave from the caller's
    // mid-height and land on the callee's, so five arrows into one contract were one point
    // on its border. Spread along the side instead, in the order they head off: an arrow
    // going up leaves from the upper part of the side, one going down from the lower, so none
    // crosses another in the first hundred units of its life.
    let spread = |mut ends: Vec<(usize, f64)>, height: f64| -> BTreeMap<usize, f64> {
        ends.sort_by(|a, b| {
            a.1.partial_cmp(&b.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(a.0.cmp(&b.0))
        });
        let count = ends.len();
        let step = if count > 1 {
            // The BOX's own height, not a constant: an outside leaf is half as tall, and five
            // arrows spread over a contract's height would have left its border.
            ANCHOR_PITCH.min((height - 2.0 * ANCHOR_INSET).max(0.0) / (count - 1) as f64)
        } else {
            0.0
        };
        ends.into_iter()
            .enumerate()
            .map(|(rank, (index, _))| (index, (rank as f64 - (count as f64 - 1.0) / 2.0) * step))
            .collect()
    };
    let mut leaving: BTreeMap<&str, (f64, Vec<(usize, f64)>)> = BTreeMap::new();
    let mut landing: BTreeMap<&str, (f64, Vec<(usize, f64)>)> = BTreeMap::new();
    for arrow in &forward {
        let heads_to = arrow.corridors.first().copied().unwrap_or(arrow.to.y);
        let comes_from = arrow.corridors.last().copied().unwrap_or(arrow.from.y);
        leaving
            .entry(arrow.from.id.as_str())
            .or_insert_with(|| (arrow.from.height, Vec::new()))
            .1
            .push((arrow.index, heads_to));
        landing
            .entry(arrow.to.id.as_str())
            .or_insert_with(|| (arrow.to.height, Vec::new()))
            .1
            .push((arrow.index, comes_from));
    }
    let mut start_offset: BTreeMap<usize, f64> = BTreeMap::new();
    for (height, ends) in leaving.into_values() {
        start_offset.extend(spread(ends, height));
    }
    let mut end_offset: BTreeMap<usize, f64> = BTreeMap::new();
    for (height, ends) in landing.into_values() {
        end_offset.extend(spread(ends, height));
    }

    // Which gutters each arrow crosses, and the y it enters and leaves each one at.
    let mut crossing: BTreeMap<usize, Vec<((usize, usize), f64, f64)>> = BTreeMap::new();
    for arrow in &forward {
        let start_y = arrow.from.y + start_offset.get(&arrow.index).copied().unwrap_or(0.0);
        let end_y = arrow.to.y + end_offset.get(&arrow.index).copied().unwrap_or(0.0);
        let mut enters = start_y;
        for (step, gutter) in arrow.gutters.iter().enumerate() {
            let leaves = arrow.corridors.get(step).copied().unwrap_or(end_y);
            crossing
                .entry(*gutter)
                .or_default()
                .push(((arrow.index, step), enters, leaves));
            enters = leaves;
        }
    }

    // The lane grid, per gutter: every arrow crossing it on one grid measured from the callee
    // column's edge, ordered so two arrows that need not cross do not.
    let mut lane_of: BTreeMap<(usize, usize), f64> = BTreeMap::new();
    for (gutter, arrows) in &crossing {
        let near = layout
            .nodes
            .iter()
            .filter(|node| node.layer == *gutter)
            .map(|node| node.x + node.width / 2.0)
            .fold(f64::MIN, f64::max);
        let far = layout
            .nodes
            .iter()
            .filter(|node| node.layer == gutter + 1)
            .map(|node| node.x - node.width / 2.0)
            .fold(f64::MAX, f64::min);
        // Unchanged by the flip: a gutter still runs between column `g` and column `g + 1`,
        // and a lane is still measured from the left of the two.

        if !near.is_finite() || !far.is_finite() {
            continue;
        }
        for (key, x) in assign_lanes(arrows, near, far, LANE_PITCH) {
            lane_of.insert(key, x);
        }
    }

    let mut planned: Vec<RoutedArrow> = Vec::new();
    for arrow in &forward {
        let lanes: Vec<f64> = arrow
            .gutters
            .iter()
            .enumerate()
            .filter_map(|(step, _)| lane_of.get(&(arrow.index, step)).copied())
            .collect();
        if lanes.is_empty() {
            continue;
        }
        let start_y = arrow.from.y + start_offset.get(&arrow.index).copied().unwrap_or(0.0);
        let end_y = arrow.to.y + end_offset.get(&arrow.index).copied().unwrap_or(0.0);
        planned.push(RoutedArrow {
            edge: Some(arrow.index),
            plan: plan_lane_chain(
                &LaneEnd::Point { x: arrow.from.x + arrow.from.width / 2.0, y: start_y },
                &LaneEnd::Point { x: arrow.to.x - arrow.to.width / 2.0, y: end_y },
                &lanes,
                &arrow.corridors,
            ),
            style: style_of(arrow.edge.relation, false),
        });
    }
    // A cycle goes back the SHORT way: out of the caller's left, one row down, across to the
    // lane outside the callee's column, up, and in at the callee's left.
    //
    // Two versions came before it. Miro's own routing drew it through the middle of the frame
    // and over two boxes. Sending it under the WHOLE diagram cleared the boxes and drew a lap
    // of the entire frame — it left the top-left box, crossed the full width twice and the full
    // height once, to reach a contract two rows above. The corridor only has to clear the
    // caller's own row, and the lane outside the callee's column is empty by construction.
    for (rank, (index, edge, from, to)) in backwards.into_iter().enumerate() {
        // Just under the caller's row, inside the gutter the layout already leaves there
        // (`gutter_y` is one and a half boxes), so nothing is crossed and nothing moves.
        let corridor = from.y + from.height / 2.0 + CYCLE_GAP + rank as f64 * CYCLE_PITCH;
        let anchor = RelativeAnchor::new(0.5, 0.5);
        // Out of the LEFT, because the callee is to the left: leaving right meant crossing the
        // caller's own column before turning round.
        let down_x = from.x - from.width / 2.0 - CYCLE_GAP;
        let up_x = to.x - to.width / 2.0 - CYCLE_GAP;
        planned.push(RoutedArrow {
            edge: Some(index),
            plan: PlannedLaneArrow {
                points: vec![
                    (from.x - from.width / 2.0, from.y),
                    (down_x, from.y),
                    (down_x, corridor),
                    (up_x, corridor),
                    (up_x, to.y),
                    (to.x - to.width / 2.0, to.y),
                ],
                legs: vec![
                    (LaneSide::Marker(0), anchor, LaneSide::Marker(1), anchor, false),
                    (LaneSide::Marker(1), anchor, LaneSide::Marker(2), anchor, false),
                    (LaneSide::Marker(2), anchor, LaneSide::Marker(3), anchor, false),
                    (LaneSide::Marker(3), anchor, LaneSide::Marker(4), anchor, false),
                    (LaneSide::Marker(4), anchor, LaneSide::Marker(5), anchor, true),
                ],
            },
            style: style_of(edge.relation, true),
        });
    }
    // The legend's samples are arrows like any other, so they are counted, drawn and
    // previewed by the same code — a legend drawn by its own path is a legend that drifts.
    // Only on the legend's own frame: appended to every frame, they drew five loose strokes
    // over the top-left corner of each contract's diagram.
    for row in legend_rows().into_iter().filter(|_| with_legend) {
        let Sample::Leg(style) = row.sample else { continue };
        planned.push(RoutedArrow {
            edge: None,
            plan: PlannedLaneArrow {
                points: vec![row.sample_from, row.sample_to],
                legs: vec![(
                    LaneSide::Marker(0),
                    RelativeAnchor::new(1.0, 0.5),
                    LaneSide::Marker(1),
                    RelativeAnchor::new(0.0, 0.5),
                    true,
                )],
            },
            style,
        });
    }

    // Every arrow, with its zero-length legs collapsed — see `tighten`.
    planned
        .into_iter()
        .map(|arrow| RoutedArrow { plan: tighten(arrow.plan), ..arrow })
        .collect()
}

/// Drop the zero-length legs of a planned arrow, and the markers they would have joined.
///
/// A lane chain places two markers per gutter — where the arrow enters it and where it leaves.
/// When the arrow runs level, those two are the same point, and two markers at identical
/// coordinates come back from the bulk endpoint as ONE item; Miro then refuses the connector
/// with `"The startitem id and enditem id cannot be the same"`. Four relations of a real board
/// were lost that way, silently until the failure learned to quote the API.
///
/// Merging them is also the right picture: a leg of no length is a leg nobody can see.
fn tighten(
    plan: crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow,
) -> crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow {
    use crate::batbelt::evm::miro::auto_deploy::{LaneSide, PlannedLaneArrow};

    let same = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 0.5 && (a.1 - b.1).abs() < 0.5;
    // Each old marker keeps its own new index, unless an EARLIER one already sits on that point.
    let mut points: Vec<(f64, f64)> = Vec::new();
    let mut moved: Vec<usize> = Vec::new();
    for point in &plan.points {
        match points.iter().position(|kept| same(*kept, *point)) {
            Some(index) => moved.push(index),
            None => {
                points.push(*point);
                moved.push(points.len() - 1);
            }
        }
    }
    let at = |side: &LaneSide| match side {
        LaneSide::Marker(index) => LaneSide::Marker(moved.get(*index).copied().unwrap_or(*index)),
        LaneSide::Item(id) => LaneSide::Item(id.clone()),
    };
    let mut legs: Vec<_> = plan
        .legs
        .iter()
        .map(|(from, from_anchor, to, to_anchor, head)| {
            (at(from), *from_anchor, at(to), *to_anchor, *head)
        })
        .filter(|(from, _, to, _, _)| match (from, to) {
            (LaneSide::Marker(a), LaneSide::Marker(b)) => a != b,
            _ => true,
        })
        .collect();
    // The head rides on the last leg: dropping the one that carried it would leave an arrow
    // with no point on it.
    if !legs.is_empty() && !legs.iter().any(|leg| leg.4) {
        let last = legs.len() - 1;
        legs[last].4 = true;
    }
    PlannedLaneArrow { points, legs }
}

/// Draw the planned map into a local PNG: every frame's border and title, its boxes, and every
/// leg of every arrow exactly where the board would put them.
///
/// It is the same plan the drawing transcribes, so what this shows is what would be drawn —
/// which is the point. Judging a layout by deploying it costs a minute and a board full of
/// frames nobody wants.
pub fn preview(prepared: &PreparedMap, path: &str) -> Result<(), EvmMiroError> {
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    use image::{Rgba, RgbaImage};

    let scale = (2_600.0 / prepared.width).min(1.0);
    let width = (prepared.width * scale).round().max(1.0) as u32;
    let height = (prepared.height * scale).round().max(1.0) as u32;
    let mut canvas = RgbaImage::from_pixel(width, height, Rgba([250, 250, 250, 255]));

    for frame in &prepared.frames {
        // Frame-local, exactly as Miro reads a child item's position, plus where the frame sits
        // in the block.
        let at = |x: f64, y: f64| {
            (
                ((frame.left + x) * scale) as i64,
                ((frame.top + y) * scale) as i64,
            )
        };
        let border = parse_colour(BOX_BORDER);
        let (frame_left, frame_top) = at(0.0, 0.0);
        let (frame_right, frame_bottom) = at(frame.width, frame.height);
        for (from, to) in [
            ((frame_left, frame_top), (frame_right, frame_top)),
            ((frame_right, frame_top), (frame_right, frame_bottom)),
            ((frame_right, frame_bottom), (frame_left, frame_bottom)),
            ((frame_left, frame_bottom), (frame_left, frame_top)),
        ] {
            draw_stroke(&mut canvas, from, to, border, ConnectorStroke::Solid);
        }

        // Every box with the fill and border the board will give it — what a box IS and what it
        // DOES are the two things a reader takes from it before reading its name, so the preview
        // has to show them or it is previewing a different picture.
        let mut boxes: Vec<(f64, f64, f64, f64, &str, &str, usize)> = Vec::new();
        for node in &frame.layout.nodes {
            let (border, thickness) = frame.border_of(&node.id);
            boxes.push((node.x, node.y, node.width, node.height, frame.fill_of(&node.id), border, thickness));
        }
        for node in &frame.strip {
            boxes.push((node.x, node.y, node.width, node.height, STRIP_FILL, BOX_BORDER, BORDER_WIDTH));
        }
        if frame.is_legend() {
            for row in legend_rows() {
                let (fill, border) = match row.sample {
                    Sample::Leg(_) => (BOX_FILL, BOX_BORDER),
                    Sample::Box { fill, border } => (fill, border),
                };
                let thickness = if border == BOX_BORDER { BORDER_WIDTH } else { REPEAT_BORDER_WIDTH };
                boxes.push((row.x, row.y, row.width, NODE_HEIGHT, fill, border, thickness));
            }
        }
        for (x, y, box_width, box_height, fill, box_border, thickness) in boxes {
            let (left, top) = at(x - box_width / 2.0, y - box_height / 2.0);
            let (right, bottom) = at(x + box_width / 2.0, y + box_height / 2.0);
            fill_rect(&mut canvas, (left, top), (right, bottom), parse_colour(fill));
            let edge = parse_colour(box_border);
            // Drawn as nested rectangles, one per unit of thickness at this scale, so a border
            // the board draws thick is thick in the preview too — otherwise the preview answers
            // a question about the picture that the picture answers differently.
            let rings = ((thickness as f64 * scale).round() as i64).max(1);
            for ring in 0..rings {
                for (from, to) in [
                    ((left + ring, top + ring), (right - ring, top + ring)),
                    ((right - ring, top + ring), (right - ring, bottom - ring)),
                    ((right - ring, bottom - ring), (left + ring, bottom - ring)),
                    ((left + ring, bottom - ring), (left + ring, top + ring)),
                ] {
                    draw_stroke(&mut canvas, from, to, edge, ConnectorStroke::Solid);
                }
            }
        }

        // Every leg of every arrow, in its stroke and colour, from the markers the plan places.
        for arrow in &frame.arrows {
            let colour = parse_colour(&arrow.style.stroke_color);
            for (from, _, to, _, _) in &arrow.plan.legs {
                let point = |side: &LaneSide| match side {
                    LaneSide::Marker(index) => arrow.plan.points.get(*index).copied(),
                    LaneSide::Item(_) => None,
                };
                let (Some((from_x, from_y)), Some((to_x, to_y))) = (point(from), point(to)) else {
                    continue;
                };
                draw_stroke(&mut canvas, at(from_x, from_y), at(to_x, to_y), colour, arrow.style.stroke);
            }
        }
    }

    canvas
        .save(path)
        .map_err(|error| {
            Report::new(EvmMiroError).attach_printable(format!("cannot write {path}: {error}"))
        })?;
    println!("  preview written to {}", path.bold());
    Ok(())
}

/// A line in one of the three strokes, so the preview tells a question from a fact the way
/// the board will. Lengths are in pixels of the scaled canvas: a dash long enough to read as
/// a dash at a sixth of board scale, a dot that is not a dash.
fn draw_stroke(
    canvas: &mut image::RgbaImage,
    from: (i64, i64),
    to: (i64, i64),
    colour: image::Rgba<u8>,
    stroke: ConnectorStroke,
) {
    let (on, off) = match stroke {
        ConnectorStroke::Solid => (usize::MAX, 0),
        ConnectorStroke::Dashed => (12, 8),
        ConnectorStroke::Dotted => (3, 6),
    };
    let mut walked = 0usize;
    for (x, y) in bresenham(from, to) {
        if walked % (on.saturating_add(off)) < on {
            for dy in -1..=1 {
                for dx in -1..=1 {
                    let (px, py) = (x + dx, y + dy);
                    if px >= 0 && py >= 0 && (px as u32) < canvas.width() && (py as u32) < canvas.height() {
                        canvas.put_pixel(px as u32, py as u32, colour);
                    }
                }
            }
        }
        walked += 1;
    }
}

/// Every pixel of the line from `from` to `to`, in order.
fn bresenham(from: (i64, i64), to: (i64, i64)) -> Vec<(i64, i64)> {
    let mut pixels = Vec::new();
    let (mut x, mut y) = from;
    let dx = (to.0 - x).abs();
    let dy = -(to.1 - y).abs();
    let step_x = if x < to.0 { 1 } else { -1 };
    let step_y = if y < to.1 { 1 } else { -1 };
    let mut error = dx + dy;
    loop {
        pixels.push((x, y));
        if x == to.0 && y == to.1 {
            break;
        }
        let double = 2 * error;
        if double >= dy {
            error += dy;
            x += step_x;
        }
        if double <= dx {
            error += dx;
            y += step_y;
        }
    }
    pixels
}

fn fill_rect(canvas: &mut image::RgbaImage, top_left: (i64, i64), bottom_right: (i64, i64), colour: image::Rgba<u8>) {
    for y in top_left.1.max(0)..bottom_right.1.min(canvas.height() as i64) {
        for x in top_left.0.max(0)..bottom_right.0.min(canvas.width() as i64) {
            canvas.put_pixel(x as u32, y as u32, colour);
        }
    }
}

/// `#rrggbb` as a pixel. A colour this tool did not write is not worth failing over, so an
/// unparseable one is drawn grey.
fn parse_colour(hex: &str) -> image::Rgba<u8> {
    let channel = |range: std::ops::Range<usize>| {
        hex.get(range)
            .and_then(|part| u8::from_str_radix(part, 16).ok())
            .unwrap_or(128)
    };
    image::Rgba([channel(1..3), channel(3..5), channel(5..7), 255])
}

/// Measure the map. Local: no client, no board, no renders.
///
/// One frame per top caller, plus a small frame for the legend and whatever is connected to
/// nothing — see `partition_frames`. The frames are packed into a block here, in frame-local
/// coordinates, so the only thing the board decides is where that block starts.
pub fn prepare(metadata: &EvmBatMetadata, options: &MapOptions) -> Result<PreparedMap, EvmMiroError> {
    let all = relations(metadata);
    let edges = drawn_edges(&all, options.no_boundaries);
    if edges.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("no relations between contracts — run `bat-cli sonar` first"));
    }


    let mut frames: Vec<PreparedFrame> = partition_frames(&edges)
        .into_iter()
        .map(|plan| {
            // No localizing: a frame is a tree, so nothing inside it is shared and nothing can
            // cross. The crossing count is still reported, as the certificate that it stays so.
            let mine = plan.edges;
            let layout = layout_tree(&plan.root, &mine);
            let arrows = route_arrows(&mine, &layout, false);
            // Tall enough for what the arrows actually use: a cycle's corridor runs under the
            // lowest box, and a frame measured from the boxes alone would cut it off.
            let used = arrows
                .iter()
                .flat_map(|arrow| arrow.plan.points.iter())
                .map(|(_, y)| *y)
                .fold(0.0_f64, f64::max);
            PreparedFrame {
                title: frame_title(&plan.root),
                fills: PreparedFrame::outside_fills(&mine),
                borders: PreparedFrame::repeat_borders(&mine),
                width: layout.frame_width,
                height: layout.frame_height.max(used + MAP_MARGIN),
                crossings: layout.crossings,
                edges: mine,
                layout,
                arrows,
                strip: Vec::new(),
                left: 0.0,
                top: 0.0,
            }
        })
        .collect();
    // The legend FIRST: it is the frame a reader opens to learn how to read the others, so it
    // takes the top-left of the block and is the first one created. It used to be appended, so
    // it landed wherever the packing had room — usually last, at the bottom right.
    frames.insert(0, legend_frame(&unconnected(metadata, &edges)));
    pack_frames(&mut frames);

    let width = frames
        .iter()
        .map(|frame| frame.left + frame.width)
        .fold(0.0_f64, f64::max);
    let height = frames
        .iter()
        .map(|frame| frame.top + frame.height)
        .fold(0.0_f64, f64::max);
    let calls = ApiCalls {
        frames: frames.len(),
        boxes: frames
            .iter()
            .map(|frame| frame.layout.nodes.len() + frame.boxes_of_its_own())
            .sum(),
        markers: frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .map(|arrow| arrow.plan.points.len())
            .sum(),
        connectors: frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .map(|arrow| arrow.plan.legs.len())
            .sum(),
    };

    Ok(PreparedMap { edges, frames, width, height, calls })
}

/// A frame's title: whose frame it is. One phrasing, used by the title, by `--contract` and by
/// the card that points at it, so the three can never drift apart.
fn frame_title(root: &str) -> String {
    format!("map: what {root} talks to")
}

/// The legend, and the contracts no relation touches, on a frame of their own.
///
/// One copy for the whole map rather than one per frame: seven rows repeated on every frame is
/// seven rows of noise per frame, and the reader needs them once.
fn legend_frame(alone: &[String]) -> PreparedFrame {
    let rows = legend_rows();
    let mut strip = strip_of(alone, rows.last().map(|row| row.y).unwrap_or(0.0) + NODE_HEIGHT * 2.0);
    let width = rows
        .iter()
        .map(|row| row.x + row.width / 2.0 + LEGEND_SAMPLE + MAP_MARGIN)
        .chain(strip.iter().map(|node| node.x + node.width / 2.0 + MAP_MARGIN))
        .fold(0.0_f64, f64::max);
    let height = rows
        .iter()
        .map(|row| row.y)
        .chain(strip.iter().map(|node| node.y))
        .fold(0.0_f64, f64::max)
        + NODE_HEIGHT / 2.0
        + MAP_MARGIN;
    // Its samples are arrows like any other, drawn and previewed by the same code.
    let arrows = route_arrows(&[], &crate::batbelt::miro::layout::GraphLayout {
        nodes: Vec::new(),
        routes: Vec::new(),
        back_edges: Vec::new(),
        bbox_width: 0.0,
        bbox_height: 0.0,
        frame_width: width,
        frame_height: height,
        crossings: 0,
    }, true);
    strip.shrink_to_fit();
    PreparedFrame {
        title: "map: legend".to_string(),
        fills: BTreeMap::new(),
        borders: BTreeMap::new(),
        edges: Vec::new(),
        layout: crate::batbelt::miro::layout::GraphLayout {
            nodes: Vec::new(),
            routes: Vec::new(),
            back_edges: Vec::new(),
            bbox_width: width,
            bbox_height: height,
            frame_width: width,
            frame_height: height,
            crossings: 0,
        },
        arrows,
        strip,
        width,
        height,
        crossings: 0,
        left: 0.0,
        top: 0.0,
    }
}

/// Place the frames in rows, left to right, wrapping at a width that keeps the block roughly
/// as wide as it is tall.
///
/// Miro refuses a frame that overlaps another with a 500, so this is not cosmetic. Rows rather
/// than one long line because a map of eight frames in a row is a map nobody can see at once —
/// the whole reason there are frames at all.
fn pack_frames(frames: &mut [PreparedFrame]) {
    let area: f64 = frames.iter().map(|frame| frame.width * frame.height).sum();
    let widest = frames.iter().map(|frame| frame.width).fold(0.0_f64, f64::max);
    // Two of the widest frames side by side, at least: `sqrt(area)` alone is the width of the
    // single widest frame whenever one frame dominates, which lays every other frame out in a
    // column one frame wide and makes the block a mile tall.
    let target = area.sqrt().max(widest * 2.0 + MAP_MARGIN);
    let (mut x, mut y, mut row_height) = (0.0_f64, 0.0_f64, 0.0_f64);
    for frame in frames.iter_mut() {
        if x > 0.0 && x + frame.width > target {
            x = 0.0;
            y += row_height + MAP_MARGIN;
            row_height = 0.0;
        }
        frame.left = x;
        frame.top = y;
        x += frame.width + MAP_MARGIN;
        row_height = row_height.max(frame.height);
    }
}

/// The strip's boxes: a heading, then one box per unconnected contract, stacked in a column
/// under the legend's rows.
fn strip_of(names: &[String], top: f64) -> Vec<PlacedNode> {
    if names.is_empty() {
        return Vec::new();
    }
    let heading = strip_heading_text();
    let width = names
        .iter()
        .map(|name| node_width(name))
        .fold(node_width(heading), f64::max);
    std::iter::once(STRIP_HEADING.to_string())
        .chain(names.iter().cloned())
        .enumerate()
        .map(|(row, id)| PlacedNode {
            id,
            layer: 0,
            x: MAP_MARGIN / 2.0 + width / 2.0,
            y: top + row as f64 * (NODE_HEIGHT + 60.0),
            width,
            height: NODE_HEIGHT,
        })
        .collect()
}

/// The words on the strip's heading box.
fn strip_heading_text() -> &'static str {
    STRIP_HEADING.trim_start_matches('\u{0}')
}

/// The words a box carries: a contract's name, or the strip's heading.
fn box_text(id: &str) -> &str {
    if id == STRIP_HEADING {
        strip_heading_text()
    } else {
        original_of(id)
    }
}
/// The deployable contracts that have no relation at all, and so no box.
///
/// A contract nothing calls and that calls nothing is not a contract the map can place — but
/// it IS part of the system, and a map that simply omits it is a map the reader trusts more
/// than it deserves. Listed in the report instead.
pub fn unconnected(metadata: &EvmBatMetadata, edges: &[Edge]) -> Vec<String> {
    use crate::batbelt::evm::types::EvmContractType;
    let drawn: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [edge.from.as_str(), edge.to.as_str()])
        .collect();
    metadata
        .contracts
        .iter()
        .filter(|contract| {
            !contract.vendored
                && matches!(contract.contract_type, EvmContractType::Contract)
                && !drawn.contains(contract.name.as_str())
        })
        .map(|contract| contract.name.clone())
        .collect()
}

/// `new X(...)` of code this repository does not own.
///
/// A factory that deploys somebody else's contract is worth a line even though the thing it
/// deploys gets no box: it is still the system creating an address at runtime.
pub fn vendored_creations(metadata: &EvmBatMetadata) -> Vec<String> {
    let mut found: BTreeSet<String> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        for function in &contract.functions {
            for callee in callees_of(metadata, &function.metadata_id) {
                let Some(name) = callee.strip_suffix(".constructor") else {
                    continue;
                };
                let vendored = metadata
                    .contract_in_scope(name, &contract.file_path)
                    .map(|target| target.vendored)
                    .unwrap_or(true);
                if vendored {
                    found.insert(format!("{}.{} creates {name}", contract.name, function.name));
                }
            }
        }
    }
    found.into_iter().collect()
}

/// Everything the drawing needs, measured, with nothing on the board yet.
///
/// The same split `storage` and `effects` have, and for the same two reasons: a frame has to be
/// created at its final size, and a failure must leave nothing half-drawn. It also lets
/// `--dry-run` say what a real run would cost, because the call count is arithmetic over this
/// value and not something only the drawing knows.
pub struct PreparedMap {
    /// Every relation, before any frame copied one: what the terminal reports.
    edges: Vec<Edge>,
    /// One per top caller, plus the legend's. Their `left`/`top` are inside the block.
    frames: Vec<PreparedFrame>,
    pub width: f64,
    pub height: f64,
    pub calls: ApiCalls,
}

/// One frame of the map: what one contract talks to, laid out on its own.
pub struct PreparedFrame {
    title: String,
    /// This frame's relations, with the copies `localize` made — not the map's.
    edges: Vec<Edge>,
    layout: GraphLayout,
    arrows: Vec<RoutedArrow>,
    /// One fill per interface drawn here, so every copy of one interface looks like the others
    /// and no two interfaces look alike.
    fills: BTreeMap<String, &'static str>,
    /// One border per contract drawn here MORE THAN ONCE, so its copies read as one address.
    borders: BTreeMap<String, &'static str>,
    /// Only the legend frame has these: the contracts no relation touches.
    strip: Vec<PlacedNode>,
    width: f64,
    height: f64,
    /// Arrow pairs that still cross after localizing — the certificate, printed per frame so a
    /// change to the layout is judged by a number instead of by looking at a PNG.
    crossings: usize,
    /// Inside the block, before the board says where the block starts.
    left: f64,
    top: f64,
}

impl PreparedFrame {
    /// Whose frame this is, read back off its title.
    fn root(&self) -> &str {
        self.title
            .strip_prefix("map: what ")
            .and_then(|rest| rest.strip_suffix(" talks to"))
            .unwrap_or(&self.title)
    }

    /// Every contract drawn here, by its real name and once: a frame draws a contract twice on
    /// purpose, and for "where is this shown" the two copies are one frame.
    fn contracts_shown(&self) -> Vec<String> {
        let mut names: BTreeSet<&str> = BTreeSet::new();
        for node in &self.layout.nodes {
            if !is_outside(&node.id) {
                names.insert(original_of(&node.id));
            }
        }
        names.into_iter().map(str::to_string).collect()
    }

    /// One fill per interface this frame draws, by the order the names sort in — so the same
    /// frame drawn twice gives the same colours, and two interfaces never share one.
    fn outside_fills(edges: &[Edge]) -> BTreeMap<String, &'static str> {
        let names: BTreeSet<&str> = edges
            .iter()
            .filter(|edge| is_outside(&edge.to))
            .map(|edge| original_of(&edge.to))
            .collect();
        names
            .into_iter()
            .enumerate()
            .map(|(index, name)| {
                // Past the palette, grey: a ninth colour nobody can tell from the first is
                // worse than a box that plainly says "outside and not colour-coded".
                (name.to_string(), OUTSIDE_FILLS.get(index).copied().unwrap_or(OUTSIDE_FILL))
            })
            .collect()
    }

    /// One border per contract this frame draws more than once, by the order the names sort in.
    fn repeat_borders(edges: &[Edge]) -> BTreeMap<String, &'static str> {
        // Count the distinct BOXES per contract: `Treasury` and `Treasury#2` are two, while two
        // arrows into the same box are one.
        let mut boxes: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for edge in edges {
            for id in [edge.from.as_str(), edge.to.as_str()] {
                if !is_outside(id) {
                    boxes.entry(original_of(id)).or_default().insert(id);
                }
            }
        }
        boxes
            .into_iter()
            .filter(|(_, copies)| copies.len() > 1)
            .enumerate()
            .filter_map(|(index, (name, _))| {
                // Past the palette, the plain border: a ninth colour nobody can tell from the
                // first says less than saying nothing.
                REPEAT_BORDERS.get(index).map(|colour| (name.to_string(), *colour))
            })
            .collect()
    }

    /// The border a box of this frame gets, and how thick: its contract's own colour, drawn
    /// thick enough to read at the zoom where the frame fits, when that contract is drawn here
    /// more than once — and the plain thin one otherwise.
    fn border_of(&self, id: &str) -> (&'static str, usize) {
        if is_outside(id) {
            return (BOX_BORDER, BORDER_WIDTH);
        }
        match self.borders.get(original_of(id)) {
            Some(colour) => (colour, REPEAT_BORDER_WIDTH),
            None => (BOX_BORDER, BORDER_WIDTH),
        }
    }

    /// The fill a box of this frame gets: white for this repository's code, and the interface's
    /// own colour for a leaf that leaves it.
    fn fill_of(&self, id: &str) -> &'static str {
        if !is_outside(id) {
            return BOX_FILL;
        }
        self.fills.get(original_of(id)).copied().unwrap_or(OUTSIDE_FILL)
    }

    /// Boxes this frame draws that are not its laid-out contracts: the legend's rows and the
    /// strip.
    fn boxes_of_its_own(&self) -> usize {
        self.strip.len() + if self.is_legend() { LEGEND_ROWS } else { 0 }
    }

    /// Is this the legend's frame? It carries no relations of its own.
    fn is_legend(&self) -> bool {
        self.edges.is_empty()
    }
}

impl PreparedMap {
    /// How many drawn relations run against the hierarchy — the red arrows.
    fn backwards(&self) -> usize {
        self.frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .filter(|arrow| arrow.edge.is_some() && arrow.style.stroke_color == CYCLE_COLOUR)
            .count()
    }

    /// Keep only the frame of one contract, and the legend.
    ///
    /// The frames were all measured, which costs nothing but arithmetic; what is expensive is
    /// drawing them, and that is what this prevents. The block is repacked, so a single frame
    /// opens where a single frame belongs rather than in the corner of a block-sized hole.
    pub fn keep_only(&mut self, contract: &str) -> Result<(), EvmMiroError> {
        let wanted = frame_title(contract);
        if !self.frames.iter().any(|frame| frame.title == wanted) {
            let known: Vec<&str> = self
                .frames
                .iter()
                .filter(|frame| !frame.is_legend())
                .filter_map(|frame| frame.title.strip_prefix("map: what "))
                .filter_map(|rest| rest.strip_suffix(" talks to"))
                .collect();
            return Err(Report::new(EvmMiroError)
                .attach_printable(format!("no frame for `{contract}`: it is not a top caller"))
                .attach_printable(format!("the map has frames for: {}", known.join(", "))));
        }
        self.frames.retain(|frame| frame.title == wanted || frame.is_legend());
        pack_frames(&mut self.frames);
        self.width = self.frames.iter().map(|frame| frame.left + frame.width).fold(0.0, f64::max);
        self.height = self.frames.iter().map(|frame| frame.top + frame.height).fold(0.0, f64::max);
        self.calls = ApiCalls {
            frames: self.frames.len(),
            boxes: self
                .frames
                .iter()
                .map(|frame| frame.layout.nodes.len() + frame.boxes_of_its_own())
                .sum(),
            markers: self
                .frames
                .iter()
                .flat_map(|frame| frame.arrows.iter())
                .map(|arrow| arrow.plan.points.len())
                .sum(),
            connectors: self
                .frames
                .iter()
                .flat_map(|frame| frame.arrows.iter())
                .map(|arrow| arrow.plan.legs.len())
                .sum(),
        };
        Ok(())
    }

    /// Nothing is rendered any more, so there is nothing to throw away — kept so a dry run and
    /// a failure path read the same as the deploy's.
    pub fn discard(&self) {}

    /// What a real run would cost, in the terminal, before it costs it.
    pub fn estimate(&self) -> Vec<String> {
        let mut lines = vec![format!(
            "{} frame(s), {} box(es), {} relation(s) ({} backwards), {} crossing(s) left",
            self.frames.len(),
            self.calls.boxes,
            self.edges.len(),
            self.backwards(),
            self.frames.iter().map(|frame| frame.crossings).sum::<usize>(),
        )];
        // Per frame, because "which frame is still a mesh" is the question a total cannot
        // answer, and the only one worth asking of a map that has been redrawn five times.
        for frame in &self.frames {
            if frame.is_legend() {
                continue;
            }
            lines.push(format!(
                "  {:<46} {} box(es), {} relation(s), {} crossing(s)",
                frame.title,
                frame.layout.nodes.len(),
                frame.edges.len(),
                frame.crossings
            ));
        }
        lines.push(format!(
            "block: {} × {} board units — API calls: {} frames + {} boxes + {} markers + {} connectors = {}",
            self.width.round(),
            self.height.round(),
            self.calls.frames,
            self.calls.boxes,
            self.calls.markers,
            self.calls.connectors,
            self.calls.total()
        ));
        lines.push(format!(
            "       {:.1}s at Miro's ceiling of 16.7 writes a second, if nothing else limits it",
            self.calls.seconds_at_the_ceiling()
        ));
        lines.push("placement: needs the board, which a dry run does not read".to_string());
        lines
    }
}

/// What a real run will ask of Miro, counted before it asks.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct ApiCalls {
    pub frames: usize,
    pub boxes: usize,
    pub markers: usize,
    pub connectors: usize,
}

impl ApiCalls {
    pub fn total(&self) -> usize {
        self.frames + self.boxes + self.markers + self.connectors
    }

    /// How long that many writes take at Miro's own ceiling.
    ///
    /// The budget is 100 000 credits a minute and a level-2 write costs 100, so 16.7 writes a
    /// second is the wall nothing gets past — the deploy measured 16.2 with 24 permits and no
    /// retries, which is that wall. Anything slower than this estimate is latency or an error,
    /// and that is what makes the number worth printing.
    pub fn seconds_at_the_ceiling(&self) -> f64 {
        self.total() as f64 / 16.7
    }
}

/// The two ends of the hierarchy, as lines for the terminal.
///
/// A TOP CALLER is a contract nothing in scope depends on: where a reader starts, and what the
/// map makes a frame for. A FOUNDATION is one that depends on nothing: what has to exist before
/// any of the others, which is the order the board reads left to right.
///
/// Neither is in the file tree, and neither is a guess — both fall straight out of the
/// relations.
pub fn hierarchy(all: &[Edge], no_boundaries: bool) -> Vec<String> {
    // The TOP CALLERS are read off the same edges the map frames, so the list and the frames
    // cannot disagree: a contract whose only relation leaves the repository is still a contract
    // nothing in scope depends on, and it still gets a frame.
    let framed = drawn_edges(all, no_boundaries);
    // The FOUNDATIONS are read off this repository's own relations: what leaves the code is a
    // leaf of whoever calls it, never a rung of the hierarchy, and listing `IERC20` as
    // something "everything else needs" said nothing true about the system.
    let edges: Vec<Edge> = all
        .iter()
        .filter(|edge| edge.relation != Relation::Boundary)
        .cloned()
        .collect();
    let names: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [edge.from.as_str(), edge.to.as_str()])
        .collect();
    let called: BTreeSet<&str> = edges.iter().map(|edge| edge.to.as_str()).collect();
    let calls: BTreeSet<&str> = edges.iter().map(|edge| edge.from.as_str()).collect();
    let out = |name: &str| edges.iter().filter(|edge| edge.from == name).count();
    let into = |name: &str| edges.iter().filter(|edge| edge.to == name).count();

    let framed_names: BTreeSet<&str> = framed.iter().map(|edge| edge.from.as_str()).collect();
    let framed_called: BTreeSet<&str> = framed.iter().map(|edge| edge.to.as_str()).collect();
    let mut tops: Vec<&str> = framed_names
        .iter()
        .copied()
        .filter(|name| !framed_called.contains(name))
        .collect();
    tops.sort_by(|a, b| out(b).cmp(&out(a)).then(a.cmp(b)));
    let mut foundations: Vec<&str> = names.iter().copied().filter(|n| !calls.contains(n)).collect();
    foundations.sort_by(|a, b| into(b).cmp(&into(a)).then(a.cmp(b)));

    let mut lines = vec![format!(
        "{} top caller(s) — nothing in scope depends on them, and the map gives each one a frame:",
        tops.len()
    )];
    for name in &tops {
        lines.push(format!("  {name:<28} talks to {} contract(s)   bat-cli map --contract {name}", out(name)));
    }
    lines.push(String::new());
    lines.push(format!(
        "{} foundation(s) — they depend on nothing, so they exist before the rest:",
        foundations.len()
    ));
    for name in &foundations {
        lines.push(format!("  {name:<28} {} contract(s) depend on it", into(name)));
    }
    lines
}

/// Split the whole graph into one frame per TOP CALLER, the way a deployment is one frame per
/// entry point.
///
/// Sixteen contracts and twenty relations on one frame is a mesh whichever way it is laid out,
/// and no amount of colour fixes it: the reader cannot follow a single arrow. The entry-point
/// diagrams hit this years ago and the answer there (`docs/diagram-deploy-design.md` §4) was to
/// partition and REPEAT — a callee drawn in two frames is drawn twice on purpose, because a
/// repeated box is cheap and a crossing arrow is not.
///
/// A top caller is a contract nothing in scope depends on: the place a reader starts. Its
/// frame holds everything it reaches, so the frame answers one question — "what does this
/// contract talk to" — and a contract everyone uses appears in each frame that uses it.
///
/// Anything left over (a cycle nothing points into) gets a frame of its own rather than being
/// dropped, picked by the contract with the most relations.
fn partition_frames(edges: &[Edge]) -> Vec<FramePlan> {
    let names: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [edge.from.as_str(), edge.to.as_str()])
        .collect();
    let called: BTreeSet<&str> = edges.iter().map(|edge| edge.to.as_str()).collect();
    let out_degree = |name: &str| edges.iter().filter(|edge| edge.from == name).count();
    let mut roots: Vec<String> = names
        .iter()
        .copied()
        .filter(|name| !called.contains(name))
        .map(str::to_string)
        .collect();
    // Deterministic, and the busiest first so the frame a reader opens first says the most.
    roots.sort_by(|a, b| out_degree(b).cmp(&out_degree(a)).then(a.cmp(b)));

    let mut frames: Vec<FramePlan> = Vec::new();
    let mut covered: BTreeSet<(String, String)> = BTreeSet::new();
    let mut plan = |root: &str, frames: &mut Vec<FramePlan>, covered: &mut BTreeSet<(String, String)>| {
        let mine = unfold(root, edges);
        for edge in &mine {
            covered.insert((original_of(&edge.from).to_string(), original_of(&edge.to).to_string()));
        }
        if !mine.is_empty() {
            frames.push(FramePlan { root: root.to_string(), edges: mine });
        }
    };
    for root in &roots {
        plan(root, &mut frames, &mut covered);
    }
    // A cycle with nothing above it has no top caller, and is every bit as much part of the
    // system: it gets a frame of its own rather than being dropped. `StakingFeeConverter` is
    // one — `StakingFeeTreasury` calls back into it, so nothing in scope sits above it.
    let mut tried: BTreeSet<String> = roots.iter().cloned().collect();
    // Compared by ORIGINAL name on both ends, because a drawn edge carries the id of a copy
    // (`IERC20@YieldRouter`, `Treasury#2`) and the raw relation carries the name. Comparing the
    // two made every call that leaves the repository look undrawn, and every contract that
    // makes one became a root of its own: fourteen frames for five systems.
    while let Some(orphan) = edges
        .iter()
        .filter(|edge| {
            !covered.contains(&(
                original_of(&edge.from).to_string(),
                original_of(&edge.to).to_string(),
            ))
        })
        .map(|edge| edge.from.clone())
        // Every contract whose own relations are still undrawn is a candidate, and already
        // being somebody's root disqualifies it, or the loop re-roots the same contract for
        // ever. Among the rest the root is THE ONE THAT CALLS THE MOST, not the first one the
        // relations happen to list: a cycle has no top caller, so some member has to be picked,
        // and the member with the most outgoing relations is the one whose frame tells the most
        // of the story. Ties go to the name, so the same system always draws the same frames.
        .filter(|name| !tried.contains(name))
        .max_by(|a, b| out_degree(a).cmp(&out_degree(b)).then_with(|| b.cmp(a)))
    {
        tried.insert(orphan.clone());
        plan(&orphan, &mut frames, &mut covered);
    }
    frames
}

/// A frame is a TREE: everything its contract reaches, with anything shared DRAWN AGAIN rather
/// than pointed at from two places.
///
/// The rule this replaced cut a contract two frames both reached into a frame of its own and
/// left a card behind. It optimised the right thing — no box drawn twice — and the wrong goal:
/// `ListingDesk` is an intermediate contract, not a system worth opening on its own, and a
/// reader asking what `AscendCtoRegistry` does was sent through three frames to find out. Fewer
/// frames, each self-contained, is worth more than fewer boxes.
///
/// Unfolding a shared graph into a tree is also what makes a frame readable with no localizing
/// machinery at all: nothing is shared, so nothing can cross. It can in principle blow up — a
/// diamond is drawn twice, a diamond of diamonds four times — so it is bounded. On the systems
/// this is pointed at today (16 contracts, 20 relations) it does not come close; when it does,
/// that is the moment to start recycling a box, which is intense logic for a problem nobody has.
fn unfold(root: &str, edges: &[Edge]) -> Vec<Edge> {
    /// Enough for any audit this has been pointed at, and a wall rather than a hang.
    const MAX_BOXES: usize = 400;

    let mut drawn: Vec<Edge> = Vec::new();
    let mut copies: BTreeMap<String, usize> = [(root.to_string(), 1)].into_iter().collect();
    // (name, the id of the copy being expanded): the path from the root, which is what tells a
    // cycle from a share — a node already on the path is a loop, one seen anywhere else is not.
    let mut path: Vec<(String, String)> = vec![(root.to_string(), root.to_string())];
    // An explicit stack of (depth, which child is next), because the recursion depth here is the
    // audit's own call depth and a frame is not worth a blown stack.
    let mut stack: Vec<(usize, usize)> = vec![(0, 0)];

    while let Some((depth, next)) = stack.pop() {
        let (name, id) = path[depth].clone();
        let outgoing: Vec<&Edge> = edges.iter().filter(|edge| edge.from == name).collect();
        let Some(edge) = outgoing.get(next) else {
            path.truncate(depth + 1);
            continue;
        };
        stack.push((depth, next + 1));
        if let Some((_, ancestor)) = path.iter().take(depth + 1).find(|(on_path, _)| on_path == &edge.to) {
            // Back to something this path came through: a cycle, drawn as the one red arrow
            // rather than unfolded for ever.
            drawn.push(Edge { from: id, to: ancestor.clone(), relation: edge.relation });
            continue;
        }
        if copies.values().sum::<usize>() >= MAX_BOXES {
            continue;
        }
        let seen = copies.entry(edge.to.clone()).or_insert(0);
        *seen += 1;
        let child = if *seen == 1 {
            edge.to.clone()
        } else {
            format!("{}{COPY_MARK}{}", edge.to, seen)
        };
        drawn.push(Edge { from: id, to: child.clone(), relation: edge.relation });
        path.truncate(depth + 1);
        path.push((edge.to.clone(), child));
        stack.push((depth + 1, 0));
    }
    drawn
}

/// One frame before it is laid out: whose frame it is, what it draws, and which of its boxes
/// are cards standing for a frame of their own.
#[derive(Debug)]
pub struct FramePlan {
    root: String,
    edges: Vec<Edge>,
}

/// A contract drawn more than once in one frame: `Treasury#2` is a second box for `Treasury`.
const COPY_MARK: char = '#';
/// A box for something OUTSIDE the repository, private to the contract that calls it:
/// `IERC20@YieldRouter` is `YieldRouter`'s own copy of `IERC20`.
const OUTSIDE_MARK: char = '@';

/// The original a box stands for, which is its own name unless it is a copy.
fn original_of(id: &str) -> &str {
    id.split([COPY_MARK, OUTSIDE_MARK]).next().unwrap_or(id)
}

/// Is this box something with no source in this repository?
fn is_outside(id: &str) -> bool {
    id.contains(OUTSIDE_MARK)
}

/// Lay a frame out as a TREE: each contract at the height of the children it talks to.
///
/// The layered engine packs every column from the top, which is right when a column holds
/// unrelated boxes — and wrong here. A frame IS a tree now, and packing from the top put a
/// contract's own callees level with somebody else's: following one arrow meant scrolling up
/// and down a frame whose answer was two boxes apart. Reingold–Tilford instead: leaves take the
/// next free row, a parent sits at the middle of its children, so a box is always beside the
/// boxes it points at.
///
/// It costs what the deploy rejected it for — a parent's band is its whole subtree, so a light
/// sibling after a heavy one starts low. On a map that is cheap: the boxes are a name each, and
/// the outside leaves are half-height.
///
/// Every edge of a tree joins adjacent columns, so there are no bend points and nothing to
/// route through a corridor; crossings are 0 by construction, which the certificate still
/// reports rather than assumes.
fn layout_tree(root: &str, edges: &[Edge]) -> GraphLayout {
    /// Between two boxes stacked in the same column.
    const ROW_GAP: f64 = 220.0;
    /// Between one column and the next: room for the arrows' lanes.
    const COLUMN_GAP: f64 = 900.0;

    // The tree: the first arrow into a box is the one that owns it. Anything else is a back
    // edge — `unfold` only emits one when it reaches a box already on the path — and takes no
    // part in the placement.
    let mut children: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    let mut parented: BTreeSet<&str> = BTreeSet::new();
    let mut order: Vec<&str> = Vec::new();
    for edge in edges {
        for id in [edge.from.as_str(), edge.to.as_str()] {
            if !order.contains(&id) {
                order.push(id);
            }
        }
    }
    for edge in edges {
        // Never the root: the frame of a cycle has an arrow back INTO its own root, and taking
        // that one for the tree made the root somebody's child — so no box was left without a
        // parent, the layout found no root at all, and the whole frame came out empty. It
        // reached the board as a titled frame with nothing in it.
        if edge.to == root || parented.contains(edge.to.as_str()) {
            continue;
        }
        parented.insert(edge.to.as_str());
        children.entry(edge.from.as_str()).or_default().push(edge.to.as_str());
    }
    let Some(root) = order.iter().copied().find(|id| *id == root).or_else(|| {
        // The caller's root is normally one of the boxes; if it somehow is not, anything
        // without a parent will do before drawing nothing at all.
        order.iter().copied().find(|id| !parented.contains(id))
    }) else {
        return GraphLayout {
            nodes: Vec::new(),
            routes: vec![Vec::new(); edges.len()],
            back_edges: Vec::new(),
            bbox_width: 0.0,
            bbox_height: 0.0,
            frame_width: MAP_MARGIN * 2.0,
            frame_height: MAP_MARGIN * 2.0,
            crossings: 0,
        };
    };

    // Depth per box, and the widest box of each depth: a column is as wide as its widest name.
    let mut depth: BTreeMap<&str, usize> = BTreeMap::new();
    let mut stack = vec![(root, 0usize)];
    while let Some((id, at)) = stack.pop() {
        depth.insert(id, at);
        for child in children.get(id).into_iter().flatten() {
            stack.push((child, at + 1));
        }
    }
    let deepest = depth.values().copied().max().unwrap_or(0);
    let mut column_width = vec![0.0_f64; deepest + 1];
    for (id, at) in &depth {
        column_width[*at] = column_width[*at].max(node_width(id));
    }
    let mut column_x = vec![0.0_f64; deepest + 1];
    let mut left = MAP_MARGIN;
    for (at, width) in column_width.iter().enumerate() {
        column_x[at] = left + width / 2.0;
        left += width + COLUMN_GAP;
    }

    // Rows: a leaf takes the next one, a parent the middle of its children. Explicit stack, two
    // passes per node (down, then up), because the depth here is the audit's own call depth.
    let mut y: BTreeMap<&str, f64> = BTreeMap::new();
    let mut cursor = MAP_MARGIN;
    let mut walk: Vec<(&str, bool)> = vec![(root, false)];
    while let Some((id, done)) = walk.pop() {
        let mine = children.get(id).cloned().unwrap_or_default();
        if mine.is_empty() {
            y.insert(id, cursor + node_height(id) / 2.0);
            cursor += node_height(id) + ROW_GAP;
            continue;
        }
        if done {
            let first = y.get(mine.first().expect("checked")).copied().unwrap_or(cursor);
            let last = y.get(mine.last().expect("checked")).copied().unwrap_or(cursor);
            y.insert(id, (first + last) / 2.0);
            continue;
        }
        walk.push((id, true));
        for child in mine.iter().rev() {
            walk.push((child, false));
        }
    }

    let nodes: Vec<PlacedNode> = order
        .iter()
        .filter_map(|id| {
            Some(PlacedNode {
                id: id.to_string(),
                layer: *depth.get(id)?,
                x: column_x[*depth.get(id)?],
                y: *y.get(id)?,
                width: node_width(id),
                height: node_height(id),
            })
        })
        .collect();
    let width = nodes
        .iter()
        .map(|node| node.x + node.width / 2.0)
        .fold(0.0_f64, f64::max)
        + MAP_MARGIN;
    let height = nodes
        .iter()
        .map(|node| node.y + node.height / 2.0)
        .fold(0.0_f64, f64::max)
        + MAP_MARGIN;
    GraphLayout {
        nodes,
        routes: vec![Vec::new(); edges.len()],
        back_edges: Vec::new(),
        bbox_width: width - MAP_MARGIN * 2.0,
        bbox_height: height - MAP_MARGIN * 2.0,
        frame_width: width,
        frame_height: height,
        crossings: 0,
    }
}

/// Lay the map out: one box per contract, the deploy's own engine, callers above callees.
///
/// Pure, and done before anything is placed, because where the map goes on the board depends
/// on how wide it is — it opens to the LEFT of everything, and that edge can only be found
/// once the width is known.
/// The edges that get a box and an arrow, with what leaves the repository given a box of its
/// own — one PER CALLER.
///
/// A call out of the code is a call, and an audit's question about it ("what does this touch
/// that I cannot read") deserves an arrow like any other. What it must not be is a SHARED node:
/// `IERC20` is reached by seven contracts, and one box for all of them pulled seven long arrows
/// across the frame and was, alone, the busiest thing on the map. So every caller gets its own
/// copy, which is §5's localize taken to the end — an outside box has no chain under it, so a
/// copy costs one box and saves a crossing every time.
fn drawn_edges(edges: &[Edge], no_boundaries: bool) -> Vec<Edge> {
    edges
        .iter()
        .filter(|edge| !no_boundaries || edge.relation != Relation::Boundary)
        .map(|edge| match edge.relation {
            Relation::Boundary => Edge {
                from: edge.from.clone(),
                to: format!("{}{OUTSIDE_MARK}{}", edge.to, edge.from),
                relation: edge.relation,
            },
            _ => edge.clone(),
        })
        .collect()
}

fn layout_map(edges: &[Edge]) -> crate::batbelt::miro::layout::GraphLayout {
    use crate::batbelt::miro::layout::{layout_graph, LayoutConfig, LayoutEdge, LayoutNode};

    let mut names: Vec<String> = edges
        .iter()
        .flat_map(|edge| [edge.from.clone(), edge.to.clone()])
        .collect();
    names.sort();
    names.dedup();
    let nodes: Vec<LayoutNode> = names
        .iter()
        .map(|name| LayoutNode {
            id: name.clone(),
            width: node_width(name),
            height: node_height(name),
        })
        .collect();
    // The frame's own contract first, and the chain growing rightwards from it.
    //
    // The edges used to be fed REVERSED, so that the contract everything needs — `Treasury` —
    // landed leftmost and the deployment order read left to right. That was the right rule for
    // one frame of the whole system. It is the wrong one now that a frame is one contract's
    // story: its subject ended up at the far RIGHT, every arrow ran right to left, and the
    // reader started at the end. The hierarchy of the system is answered by `--hierarchy` and
    // by which contracts have a frame at all, not by where a box sits inside one.
    let laid_edges: Vec<LayoutEdge> = edges
        .iter()
        .map(|edge| LayoutEdge {
            from: edge.from.clone(),
            to: edge.to.clone(),
            from_line_fraction: 0.5,
        })
        .collect();

    // The root is the frame's own contract: what nothing here calls.
    let called: BTreeSet<&str> = edges.iter().map(|edge| edge.to.as_str()).collect();
    let root = names
        .iter()
        .find(|name| !called.contains(name.as_str()))
        .cloned()
        .unwrap_or_else(|| names[0].clone());

    // Laid out TWICE, and the second time is the point. The first tells us which column each
    // contract lands in; from that we can count how many arrows cross each gutter, and a
    // gutter has to be wide enough to hold them all a full pitch apart. Squeezing the lanes
    // instead is how a picture stops saying which arrow is which — so the gutter widens and
    // the layout is asked again. It is pure, so asking twice costs nothing but arithmetic, and
    // the second answer differs only in x.
    let config = |gutter_x: f64| LayoutConfig {
        padding_x: MAP_MARGIN,
        // No room reserved for a legend: it has a frame of its own now, and reserving its
        // height here left every contract's frame opening with a screen of nothing.
        padding_y: MAP_MARGIN,
        gutter_x,
        // Boxes of a map are a name each, a fraction of the height of a screenshot, so the
        // deploy's gap between them leaves six rows crammed into the top of the frame while
        // every arrow queues through the same strip of middle. Spread vertically, an arrow has
        // room to travel at its own height.
        gutter_y: NODE_HEIGHT * 1.5,
        ..Default::default()
    };
    let first = layout_graph(&root, &nodes, &laid_edges, config(LayoutConfig::default().gutter_x));
    let busiest = busiest_gutter(edges, &first);
    let wanted = crate::batbelt::miro::layout::gutter_for(busiest);
    let mut layout = if wanted <= LayoutConfig::default().gutter_x {
        first
    } else {
        layout_graph(&root, &nodes, &laid_edges, config(wanted))
    };
    order_hub_column(&mut layout, edges);
    layout
}

/// Put the most-called contracts of the first column in the MIDDLE of it, and the rest
/// outwards from there.
///
/// The first column is what calls nothing in scope: the contracts everything else depends on.
/// The barycentre sweep orders it to cut crossings between the first two columns, which is
/// the right rule everywhere else — but the thing a reader asks of this column is "which one
/// does everybody write to", and the answer should be where the eye lands first. A hub in the
/// middle also takes its arrows from above and below, half each, instead of all of them
/// running the height of the frame to reach a box the sweep left at the top.
///
/// Only the first column, and only by swapping the y's it already has: every box is one
/// height, so the slots are interchangeable and nothing else in the layout moves.
fn order_hub_column(layout: &mut GraphLayout, edges: &[Edge]) {
    // Column 0 is the frame's own contract now — one box — so this returns immediately on a
    // map and stays only for the case of a frame whose root is a cycle with several entries.

    let mut incoming: BTreeMap<&str, usize> = BTreeMap::new();
    for edge in edges {
        *incoming.entry(edge.to.as_str()).or_default() += 1;
    }
    let mut members: Vec<usize> = (0..layout.nodes.len())
        .filter(|&index| layout.nodes[index].layer == 0)
        .collect();
    if members.len() < 2 {
        return;
    }
    let mut slots: Vec<f64> = members.iter().map(|&index| layout.nodes[index].y).collect();
    slots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    // Most called first, then by name so two equally popular contracts always come out the
    // same way round.
    members.sort_by(|&a, &b| {
        let calls = |index: usize| incoming.get(layout.nodes[index].id.as_str()).copied().unwrap_or(0);
        calls(b).cmp(&calls(a)).then_with(|| layout.nodes[a].id.cmp(&layout.nodes[b].id))
    });
    for (rank, index) in members.into_iter().enumerate() {
        layout.nodes[index].y = slots[centre_out(rank, slots.len())];
    }
}

/// The slot the `rank`-th item takes when `count` slots are filled from the middle outwards:
/// the middle, then one below, one above, two below, two above.
fn centre_out(rank: usize, count: usize) -> usize {
    let middle = (count - 1) / 2;
    let distance = (rank + 1) / 2;
    if rank % 2 == 1 {
        (middle + distance).min(count - 1)
    } else {
        middle.saturating_sub(distance)
    }
}

/// How many arrows cross the busiest gutter.
///
/// An edge between columns `a` and `b` passes through every gutter between them, so a gutter's
/// load is not "the edges that end here" — that undercount is what let twelve arrows share a
/// gutter sized for one.
fn busiest_gutter(edges: &[Edge], layout: &crate::batbelt::miro::layout::GraphLayout) -> usize {
    let mut per_gutter: BTreeMap<usize, usize> = BTreeMap::new();
    for edge in edges {
        let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
            continue;
        };
        let (low, high) = (from.layer.min(to.layer), from.layer.max(to.layer));
        for gutter in low..high {
            *per_gutter.entry(gutter).or_default() += 1;
        }
    }
    per_gutter.into_values().max().unwrap_or(0)
}

/// Put the map on the board: every frame, then every box and marker, then every leg.
async fn draw(
    client: &MiroClient,
    prepared: PreparedMap,
    left: f64,
    top: f64,
) -> Result<Vec<crate::batbelt::evm::metadata::bat_metadata::MapFrameRef>, EvmMiroError> {
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    use crate::batbelt::miro::MiroError;

    // The frames first and together: everything else is a child of one of them, and a frame is
    // the one thing here nothing can be issued before.
    let mut frames_wave: tokio::task::JoinSet<(usize, String, std::result::Result<String, Report<MiroError>>)> =
        tokio::task::JoinSet::new();
    for (index, frame) in prepared.frames.iter().enumerate() {
        let client = client.clone();
        let title = frame.title.clone();
        let (x, y) = (
            left + frame.left + frame.width / 2.0,
            top + frame.top + frame.height / 2.0,
        );
        let (width, height) = (frame.width, frame.height);
        frames_wave.spawn(async move {
            let made = client.create_frame(&title, x, y, width, height, None).await;
            (index, title, made)
        });
    }
    let mut frame_ids: BTreeMap<usize, String> = BTreeMap::new();
    let mut failures: Vec<String> = Vec::new();
    while let Some(joined) = frames_wave.join_next().await {
        match joined {
            Ok((index, _, Ok(id))) => {
                frame_ids.insert(index, id);
            }
            Ok((_, title, Err(report))) => {
                failures.push(format!("frame {title}: {}", why(&report)))
            }
            Err(error) => failures.push(format!("a frame: {error}")),
        }
    }
    if frame_ids.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("not one frame of the map could be created")
            .attach_printable(failures.join("; ")));
    }

    // ONE wave for everything whose only reference is a frame: the boxes, the badges, the
    // legend's rows, the strip and every marker of every arrow. A marker's position came from
    // the plan, not from a box's id, so nothing about it waits on a box.
    //
    // And sent in BATCHES of twenty, which is the part that matters. One item per request, 226
    // requests at 48 in flight, took 75 seconds against a budget that allows 16.7 writes a
    // second — so the wall was never the budget, it was waiting for a round trip per item.
    // Miro's bulk endpoint takes twenty items a call; connectors it does not take, so the legs
    // below still go one by one.
    enum Made {
        Boxes(usize),
        Markers(Vec<(usize, usize, usize)>, Vec<String>),
    }
    type Outcome = (String, std::result::Result<Made, Report<MiroError>>);
    let mut wave: tokio::task::JoinSet<Outcome> = tokio::task::JoinSet::new();
    /// Miro's limit for one bulk call.
    const BATCH: usize = 20;
    // Every item of every frame, in one list, so a batch is full even when a frame holds three
    // boxes: batching per frame would have sent eight half-empty calls.
    let mut plain: Vec<(String, serde_json::Value)> = Vec::new();
    let mut marker_items: Vec<((usize, usize, usize), serde_json::Value)> = Vec::new();

    for (index, frame) in prepared.frames.iter().enumerate() {
        let Some(frame_id) = frame_ids.get(&index) else {
            continue;
        };
        let mut boxes: Vec<(String, String, f64, f64, f64, f64, usize, &str, &str, usize)> = Vec::new();
        if frame.is_legend() {
            for row in legend_rows() {
                let (fill, border) = match row.sample {
                    Sample::Leg(_) => (BOX_FILL, BOX_BORDER),
                    Sample::Box { fill, border } => (fill, border),
                };
                // The legend's own sample of a repeated contract has to look like one.
                let thickness = if border == BOX_BORDER { BORDER_WIDTH } else { REPEAT_BORDER_WIDTH };
                boxes.push((
                    format!("legend: {}", row.text),
                    row.text.to_string(),
                    row.x,
                    row.y,
                    row.width,
                    NODE_HEIGHT,
                    NODE_FONT,
                    fill,
                    border,
                    thickness,
                ));
            }
        }
        for node in &frame.layout.nodes {
            let (border, thickness) = frame.border_of(&node.id);
            boxes.push((
                format!("box {}", box_text(&node.id)),
                box_text(&node.id).to_string(),
                node.x,
                node.y,
                node.width,
                node.height,
                node_font(&node.id),
                frame.fill_of(&node.id),
                border,
                thickness,
            ));
        }
        for node in &frame.strip {
            boxes.push((
                format!("strip: {}", box_text(&node.id)),
                box_text(&node.id).to_string(),
                node.x,
                node.y,
                node.width,
                node.height,
                NODE_FONT,
                STRIP_FILL,
                BOX_BORDER,
                BORDER_WIDTH,
            ));
        }
        for (what, text, x, y, width, height, font, fill, border, thickness) in boxes {
            plain.push((
                what,
                MiroClient::label_item(
                    &text,
                    x,
                    y,
                    width,
                    height,
                    font,
                    fill,
                    border,
                    thickness,
                    // The name stays black, always. Colouring it as well as the border was one
                    // signal said twice, and it made a repeated contract read as a different
                    // KIND of box rather than as the same contract drawn again — the border
                    // alone says that, now that it is thick enough to see.
                    BOX_BORDER,
                    frame_id,
                ),
            ));
        }
        for (arrow_index, arrow) in frame.arrows.iter().enumerate() {
            for (point, (x, y)) in arrow.plan.points.iter().enumerate() {
                marker_items.push((
                    (index, arrow_index, point),
                    MiroClient::marker_item(*x, *y, MARKER_SIZE, frame_id),
                ));
            }
        }
    }

    for batch in plain.chunks(BATCH) {
        let client = client.clone();
        // Named by its first item: a batch that fails has to say what is missing, and listing
        // twenty names in one line says nothing a reader can use.
        let what = format!("a batch of {} item(s) from {}", batch.len(), batch[0].0);
        let items: Vec<serde_json::Value> = batch.iter().map(|(_, item)| item.clone()).collect();
        let count = items.len();
        wave.spawn(async move {
            let made = client.create_items_bulk(items).await.map(|_| Made::Boxes(count));
            (what, made)
        });
    }
    for batch in marker_items.chunks(BATCH) {
        let client = client.clone();
        let what = format!("a batch of {} marker(s)", batch.len());
        let keys: Vec<(usize, usize, usize)> = batch.iter().map(|(key, _)| *key).collect();
        let items: Vec<serde_json::Value> = batch.iter().map(|(_, item)| item.clone()).collect();
        wave.spawn(async move {
            let made = client
                .create_items_bulk(items)
                .await
                .map(|ids| Made::Markers(keys, ids));
            (what, made)
        });
    }

    // Every task is awaited, whatever happens to any of them. Returning on the first failure
    // aborts the requests still in flight: items get created that nothing reports, and the
    // frames' URLs are never printed, so the auditor is left with a half-drawn board and no
    // idea what is on it. A failure costs its own item and is named.
    let mut markers: BTreeMap<(usize, usize, usize), String> = BTreeMap::new();
    let mut boxes_made = 0usize;
    while let Some(joined) = wave.join_next().await {
        match joined {
            Ok((_, Ok(Made::Boxes(count)))) => boxes_made += count,
            Ok((what, Ok(Made::Markers(keys, ids)))) => {
                // The bulk endpoint answers in the order it was sent, which is what lets a
                // marker be found again by the leg that lands on it. If it ever does not, the
                // legs of those arrows are named as skipped rather than drawn somewhere wrong.
                if ids.len() != keys.len() {
                    failures.push(format!("{what}: {} item(s) back for {} sent", ids.len(), keys.len()));
                }
                for (key, id) in keys.into_iter().zip(ids) {
                    markers.insert(key, id);
                }
            }
            Ok((what, Err(report))) => failures.push(format!("{what}: {}", why(&report))),
            Err(error) => failures.push(format!("a task: {error}")),
        }
    }
    println!(
        "    {} {} frame(s), {boxes_made} box(es), {} marker(s)",
        "✓".green(),
        frame_ids.len(),
        markers.len()
    );

    // Then every leg of every arrow, together: each one's two ends already exist. The caption
    // rides on the leg that carries the head, and on that one only — a word on every leg of a
    // five-leg chain is five words.
    let mut legs_wave = tokio::task::JoinSet::new();
    let mut skipped: Vec<String> = Vec::new();
    for (index, frame) in prepared.frames.iter().enumerate() {
        if !frame_ids.contains_key(&index) {
            continue;
        }
        for (arrow_index, arrow) in frame.arrows.iter().enumerate() {
            for (from_side, from_anchor, to_side, to_anchor, head) in &arrow.plan.legs {
                let resolve = |side: &LaneSide| match side {
                    LaneSide::Marker(point) => markers.get(&(index, arrow_index, *point)).cloned(),
                    LaneSide::Item(id) => Some(id.clone()),
                };
                let (Some(from_id), Some(to_id)) = (resolve(from_side), resolve(to_side)) else {
                    // Its marker failed, so this leg has nowhere to land. Named rather than
                    // dropped: a missing arrow the reader is not told about is a map that lies.
                    skipped.push(format!("{}: a leg whose marker failed", arrow_name(frame, arrow)));
                    continue;
                };
                let mut leg = arrow.style.clone();
                leg.arrow = if *head { ArrowEnd::End } else { ArrowEnd::None };
                if !*head {
                    leg.caption = None;
                }
                let (from_anchor, to_anchor) = (*from_anchor, *to_anchor);
                let what = arrow_name(frame, arrow);
                let client = client.clone();
                legs_wave.spawn(async move {
                    let made = client
                        // STRAIGHT, not elbowed. Every leg of a map's arrow is already
                        // horizontal or vertical — the chain is planned that way — so `elbowed`
                        // handed a segment we had already computed to Miro's own router, which
                        // added its own elbows on top and drew a staircase where a line was
                        // asked for. The deploy keeps `elbowed`, where a leg can be diagonal
                        // and a straight one would cut across a screenshot.
                        .create_connector_shaped(
                            &from_id, from_anchor, &to_id, to_anchor, leg, "straight",
                        )
                        .await;
                    (what, made)
                });
            }
        }
    }
    let mut legs = 0usize;
    while let Some(joined) = legs_wave.join_next().await {
        match joined {
            Ok((_, Ok(_))) => legs += 1,
            Ok((what, Err(report))) => failures.push(format!("leg of {what}: {}", why(&report))),
            Err(error) => failures.push(format!("a leg: {error}")),
        }
    }
    for line in skipped.iter().chain(failures.iter()) {
        println!("    {} {line}", "skipped:".yellow());
    }
    println!(
        "    {} {} relation(s) drawn, {legs} leg(s)",
        "✓".green(),
        prepared
            .frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .filter(|arrow| arrow.edge.is_some())
            .count()
    );
    // One URL per frame, named: the whole point of several frames is that the auditor goes to
    // the one contract they are reading about.
    for (index, frame) in prepared.frames.iter().enumerate() {
        if let Some(id) = frame_ids.get(&index) {
            println!("  {:<46} {}", frame.title, client.frame_url(id).blue());
        }
    }
    // What was drawn, for the registry: which frame shows which contracts. A cluster cannot
    // point at the map without it, and the ids live nowhere else once this run ends.
    let drawn_frames: Vec<crate::batbelt::evm::metadata::bat_metadata::MapFrameRef> = prepared
        .frames
        .iter()
        .enumerate()
        .filter(|(_, frame)| !frame.is_legend())
        .filter_map(|(index, frame)| {
            Some(crate::batbelt::evm::metadata::bat_metadata::MapFrameRef {
                root: frame.root().to_string(),
                frame_id: frame_ids.get(&index)?.clone(),
                contracts: frame.contracts_shown(),
                cards: Vec::new(),
            })
        })
        .collect();
    if !failures.is_empty() {
        return Err(Report::new(EvmMiroError).attach_printable(format!(
            "{} item(s) of this map could not be drawn — the frames above have the rest",
            failures.len()
        )));
    }
    Ok(drawn_frames)
}

/// Why a call failed, in one line: the attachments the client hung on the report — which is
/// where the HTTP status and Miro's own message live.
///
/// Printing `current_context()` alone printed "Miro error" and nothing else, which told the
/// reader a thing failed and not one fact about why. The body is already carried; it was simply
/// never shown.
fn why(report: &Report<crate::batbelt::miro::MiroError>) -> String {
    let detail: Vec<String> = report
        .frames()
        .filter_map(|frame| frame.downcast_ref::<String>().map(|line| line.trim().to_string()))
        .collect();
    if detail.is_empty() {
        report.current_context().to_string()
    } else {
        detail.join(" — ")
    }
}

/// What an arrow is, for a message about it.
fn arrow_name(frame: &PreparedFrame, arrow: &RoutedArrow) -> String {
    match arrow.edge.and_then(|index| frame.edges.get(index)) {
        Some(edge) => format!("{} → {}", box_text(&edge.from), box_text(&edge.to)),
        None => "a legend sample".to_string(),
    }
}

/// Every relation between contracts, one per pair and kind — the outside included.
///
/// What LEAVES the repository is always worked out, because the panel beside the diagram is
/// made of it; whether it also gets a box is `drawn_edges`'s decision and the auditor's flag.
///
/// Three sources, which is the point: a call the scan pinned by type, a binding it refused to
/// pin, and the addresses a constructor fixes. The third is the one an auditor cannot get by
/// reading a call graph at all — a contract can be wired to another it never calls in the
/// paths that survived pruning, and that wiring is still a fact about the system.
pub fn relations(metadata: &EvmBatMetadata) -> Vec<Edge> {
    let in_scope: BTreeSet<&str> = metadata
        .contracts
        .iter()
        .filter(|contract| !contract.vendored)
        .map(|contract| contract.name.as_str())
        .collect();
    let ignored = |name: &str, path: &str| {
        metadata
            .ignored_contracts
            .iter()
            .any(|pattern| matches_ignore(pattern, name, path))
    };

    let hosted_by = hosts(metadata);
    // A library or an abstract base is not a node: its code runs as the contract that uses it,
    // which is what `hosts` works out. It is not a destination either — calling `MathLib.wad`
    // executes in the CALLER's address, so an arrow to it would be an arrow a contract draws
    // to itself.
    let folded: BTreeSet<&str> = metadata
        .contracts
        .iter()
        .filter(|contract| {
            !contract.vendored
                && matches!(
                    contract.contract_type,
                    crate::batbelt::evm::types::EvmContractType::Library
                        | crate::batbelt::evm::types::EvmContractType::Abstract
                )
        })
        .map(|contract| contract.name.as_str())
        .collect();

    let mut found: BTreeSet<Edge> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        if ignored(&contract.name, &contract.file_path) || folded.contains(contract.name.as_str())
        {
            continue;
        }
        let mut record = |to: &str, relation: Relation| {
            // A contract talking to itself is not a relation worth a line on a map: it is what
            // the contract's own deployment shows. Neither is a call into a library, which is
            // the same thing said differently — that code runs here.
            //
            // An ignored contract is not a destination either. The auditor declared it out of
            // the audit, and `ignored` used to be read only for the contract an edge leaves
            // FROM — so a contract nobody was going to look at still took a box and an arrow
            // the moment somebody called it.
            if to.is_empty() || to == contract.name || folded.contains(to) || ignored(to, "") {
                return;
            }
            found.insert(Edge {
                from: contract.name.clone(),
                to: to.to_string(),
                relation,
            });
        };

        // One rule for every kind of relation: what the type NAME means at runtime decides
        // where the arrow lands, and `with_boundaries` only decides whether an arrow that
        // leaves the code is drawn at all.
        let aim = |type_name: &str, relation: Relation| -> Option<(String, Relation)> {
            match classify_type(metadata, type_name) {
                TypeTarget::Contract(target) => Some((target, relation)),
                TypeTarget::Open(name) => Some((name, Relation::Unresolved)),
                // The outside is always KNOWN — it is what the panel is made of — and the
                // flag decides only whether it also gets a box in the diagram. Dropping it
                // here is how the panel came out empty without the flag.
                TypeTarget::Outside(name) => Some((name, Relation::Boundary)),
                TypeTarget::NotAContract => None,
            }
        };

        // What this contract's code IS: itself, plus every library and abstract base whose
        // functions run as it. A library has no address and no state — its call leaves the
        // host's address — so drawing it as a node invents an actor that does not exist. The
        // folding lives HERE and nowhere else: the entry-point graph still draws every
        // library function as its own screenshot, which is what the auditor reads there.
        let mut sources: Vec<&ContractMetadata> = vec![contract];
        sources.extend(
            hosted_by
                .get(contract.name.as_str())
                .into_iter()
                .flatten()
                .filter_map(|name| {
                    metadata
                        .contract_in_scope(name, &contract.file_path)
                        .or_else(|| metadata.contracts.iter().find(|c| &c.name == name))
                }),
        );

        for function in sources.iter().flat_map(|source| source.functions.iter()) {
            // `new X(...)`, which the scan records as a callee named `X.constructor`. Resolved
            // through the CALLER's file, never by name alone: `lib/` holds three `ProxyAdmin`s
            // and the import graph is what says which one this is.
            for created in created_by(metadata, contract, &function.metadata_id) {
                record(&created, Relation::Creates);
            }
            for call in &function.resolved_calls {
                if in_scope.contains(call.contract.as_str()) {
                    record(&call.contract, Relation::Calls);
                }
            }
            let typed = function
                .unresolved_calls
                .iter()
                .map(|call| call.inferred_type.as_str())
                .chain(
                    function
                        .unknown_external_calls
                        .iter()
                        .map(|call| call.inferred_type.as_str()),
                );
            for type_name in typed {
                if let Some((to, relation)) = aim(type_name, Relation::Calls) {
                    record(&to, relation);
                }
            }
        }

        for wired in sources.iter().flat_map(|source| wired_at_construction(source)) {
            if let Some((to, relation)) = aim(&wired, Relation::WiresAtConstruction) {
                record(&to, relation);
            }
        }
    }

    // One arrow per pair — two between the same boxes is the noise this map exists to avoid —
    // and the one kept is the one that SAYS THE MOST.
    //
    // `creates` outranks `calls`: that an address exists because of this line is the rare fact,
    // and it is the one nothing else on the board shows. That it also calls what it made is
    // taken for granted — `AscendYieldVault` both creates `YieldExitReserve` in `_checkpoint`
    // and calls it, and the map used to draw only the call, which read as two contracts that
    // happened to find each other.
    //
    // Below that, what a scan is SURER of wins: a call it pinned over wiring it inferred, and
    // either over a binding it could not pin at all.
    let rank = |relation: Relation| match relation {
        Relation::Creates => 0,
        Relation::Calls => 1,
        Relation::WiresAtConstruction => 2,
        Relation::Unresolved => 3,
        Relation::Boundary => 4,
    };
    let mut best: BTreeMap<(String, String), Relation> = BTreeMap::new();
    for edge in found {
        best.entry((edge.from.clone(), edge.to.clone()))
            .and_modify(|existing| {
                if rank(edge.relation) < rank(*existing) {
                    *existing = edge.relation;
                }
            })
            .or_insert(edge.relation);
    }
    best.into_iter()
        .map(|((from, to), relation)| Edge { from, to, relation })
        .collect()
}

/// Which deployable contracts a library's or an abstract base's code runs as.
///
/// A library has no address: its call leaves the host contract's address, so on a map of who
/// talks to whom the library is not a party. `hosts` answers "whose code is this", from the
/// `Lib.fn` callees the scan recorded and from inheritance, iterated to a FIXPOINT so a
/// library reached only through another library still reaches the contract at the end of the
/// chain.
///
/// Returns host name → the libraries and bases it hosts.
fn hosts(metadata: &EvmBatMetadata) -> BTreeMap<String, BTreeSet<String>> {
    use crate::batbelt::evm::types::EvmContractType;

    let folded: BTreeMap<&str, &ContractMetadata> = metadata
        .contracts
        .iter()
        .filter(|contract| {
            !contract.vendored
                && matches!(
                    contract.contract_type,
                    EvmContractType::Library | EvmContractType::Abstract
                )
        })
        .map(|contract| (contract.name.as_str(), contract))
        .collect();
    if folded.is_empty() {
        return BTreeMap::new();
    }

    // Who uses what, one hop: a contract uses a library when it calls `Lib.fn`, and a base
    // when it declares it.
    let mut uses: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        let mut used: BTreeSet<String> = contract
            .base_contracts
            .iter()
            .filter(|base| folded.contains_key(base.as_str()))
            .cloned()
            .collect();
        for function in &contract.functions {
            for callee in callees_of(metadata, &function.metadata_id) {
                if let Some((receiver, _)) = callee.split_once('.') {
                    if folded.contains_key(receiver) {
                        used.insert(receiver.to_string());
                    }
                }
            }
        }
        uses.insert(contract.name.clone(), used);
    }

    // To a fixpoint: a host inherits what its libraries use. Bounded by the number of
    // contracts, because each pass can only add, and a pass that adds nothing is the end.
    let mut hosted: BTreeMap<String, BTreeSet<String>> = uses
        .iter()
        .filter(|(name, _)| !folded.contains_key(name.as_str()))
        .map(|(name, used)| (name.clone(), used.clone()))
        .collect();
    for _ in 0..metadata.contracts.len().max(1) {
        let mut grew = false;
        for set in hosted.values_mut() {
            let reached: BTreeSet<String> = set
                .iter()
                .filter_map(|library| uses.get(library))
                .flatten()
                .cloned()
                .collect();
            for name in reached {
                grew |= set.insert(name);
            }
        }
        if !grew {
            break;
        }
    }
    hosted
}

/// The callee names the scan recorded for one function, as written (`Lib.fn`, `X.constructor`).
fn callees_of<'a>(metadata: &'a EvmBatMetadata, function_id: &str) -> &'a [String] {
    metadata
        .function_dependencies
        .iter()
        .find(|dependency| dependency.function_metadata_id == function_id)
        .map(|dependency| dependency.callees.as_slice())
        .unwrap_or(&[])
}

/// The deployable contracts one function creates with `new X(...)`.
///
/// The scan writes those as a callee named `X.constructor`. `X` is resolved through the
/// CALLER's file — `lib/` vendors three `ProxyAdmin`s, and the import graph is the only thing
/// that says which one a name means here. A `new` of vendored or unknown code is not a
/// relation on this map; it is listed with the untyped receivers instead.
fn created_by(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    function_id: &str,
) -> Vec<String> {
    callees_of(metadata, function_id)
        .iter()
        .filter_map(|callee| callee.strip_suffix(".constructor"))
        .filter_map(|name| metadata.contract_in_scope(name, &caller.file_path))
        .filter(|target| !target.vendored)
        .map(|target| target.name.clone())
        .collect()
}

/// The contracts whose address this one fixes when it is built.
///
/// An `immutable` of a contract type, or a state variable of one assigned in the constructor,
/// is the system's wiring written down: `YieldRouter` holds `vault`, `venue`, `oracle` and
/// `distributor` from the moment it exists. The type is the relation — what the variable is
/// called tells you nothing a map can draw.
fn wired_at_construction(contract: &ContractMetadata) -> Vec<String> {
    let constructor_writes: BTreeSet<&str> = contract
        .functions
        .iter()
        .filter(|function| function.is_constructor)
        .flat_map(|function| function.storage_writes.iter())
        .map(|write| write.split(['.', '[']).next().unwrap_or(write))
        .collect();

    contract
        .state_variables
        .iter()
        .filter(|variable| {
            // Fixed at construction: an immutable (which can be assigned nowhere else) or a
            // variable the constructor assigns.
            variable.is_immutable || constructor_writes.contains(variable.name.as_str())
        })
        // The raw type, which `classify_type` then reads: an interface collapses into its
        // implementer, a struct or an `address` is not a relation at all. Deciding that here
        // by the first letter being a capital is what let `Limits` and `CurveStep[]` onto
        // the map as contracts.
        .map(|variable| variable.type_name.trim().to_string())
        .collect()
}

/// What a type name stands for on the map.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TypeTarget {
    /// A deployable contract in scope — the box an arrow can land on.
    Contract(String),
    /// An interface with several deployable implementers and no resolution: a relation whose
    /// far end is a question for the auditor, never a guess.
    Open(String),
    /// Code that is not in this repository: an interface nothing in scope implements, or an
    /// instance of somebody else's contract (`ERC20 mirror`) held by address.
    Outside(String),
    /// A struct, an enum, a type alias, a mapping, or nothing at all — not a relation.
    NotAContract,
}

/// What a type NAME means at runtime. An interface is not a thing on the board: it is the
/// shape of a call, and the contract at the other end is what the reader is looking for.
/// `IAscendLaunchpad` and `AscendLaunchpad` were two boxes for one contract, which made the
/// system look bigger than it is and left the reader deciding which of the two to believe.
///
/// Collapsed when the answer is a FACT: a resolution the auditor recorded, or exactly one
/// DEPLOYABLE contract in scope declaring the interface as a base. Only deployable ones
/// count, because `IListingLaunchpad is IAscendLaunchpad` also "declares it as a base" and an
/// interface extending an interface was enough to make the count two and block the collapse.
/// Several deployable implementers and no resolution stays open — that is a question, and the
/// map says so.
///
/// An interface is IN SCOPE — the scan stores it like any other contract — and that is why
/// "is it in scope" cannot be the question here: answering yes for `IAscendLaunchpad` is how
/// the map drew the interface beside the contract that implements it. And a VENDORED contract
/// used as a type is not collapsible either: `ERC20 mirror` is an instance of somebody else's
/// token at another address, and the fact that `AscendCoreToken is ERC20` says nothing about
/// which token `mirror` is. Folding it into its in-scope child made a real boundary vanish as
/// a self-call.
fn classify_type(metadata: &EvmBatMetadata, type_name: &str) -> TypeTarget {
    use crate::batbelt::evm::types::EvmContractType;

    let Some(name) = contract_type_name(type_name) else {
        return TypeTarget::NotAContract;
    };
    let copies: Vec<&ContractMetadata> =
        metadata.contracts.iter().filter(|c| c.name == name).collect();
    if copies.is_empty() {
        return TypeTarget::NotAContract;
    }
    // Reading the kind off ANY copy is enough: three vendored `IERC20`s are all interfaces.
    // What matters is whether some copy is in scope and what kind of thing the name is.
    let is_interface = copies
        .iter()
        .any(|c| c.contract_type == EvmContractType::Interface);
    let in_scope = copies.iter().find(|c| !c.vendored);
    let deployable_in_scope = in_scope
        .is_some_and(|c| c.contract_type == EvmContractType::Contract);

    if deployable_in_scope {
        return TypeTarget::Contract(name.to_string());
    }
    if let Some(recorded) = metadata.resolutions.get(name) {
        if metadata.contracts.iter().any(|c| !c.vendored && c.name == *recorded) {
            return TypeTarget::Contract(recorded.clone());
        }
    }
    // Collapsible: an interface (wherever it lives) or an abstract contract of this project.
    // A vendored abstract or concrete contract is neither — it is an address of their code.
    let collapsible = is_interface
        || in_scope.is_some_and(|c| c.contract_type == EvmContractType::Abstract);
    if !collapsible {
        return TypeTarget::Outside(name.to_string());
    }
    let mut implementers = metadata
        .contracts
        .iter()
        .filter(|c| !c.vendored && c.contract_type == EvmContractType::Contract)
        .filter(|c| c.base_contracts.iter().any(|base| base == name));
    match (implementers.next(), implementers.next()) {
        (Some(only), None) => TypeTarget::Contract(only.name.clone()),
        (Some(_), Some(_)) => TypeTarget::Open(name.to_string()),
        (None, _) if is_interface => TypeTarget::Outside(name.to_string()),
        // An abstract contract of this project that nothing deployable derives from: there is
        // no box for it and no outside either, so it is a question.
        (None, _) => TypeTarget::Open(name.to_string()),
    }
}

/// The contract name a declared type can stand for, or `None` when the type cannot name a
/// contract at all: a mapping, an elementary type, or nothing.
///
/// `CurveStep[]` is an array of whatever `CurveStep` is, so the brackets are stripped; a
/// `mapping(Id => PendingUint192)` is storage, not an address, and is never a relation.
fn contract_type_name(type_name: &str) -> Option<&str> {
    let mut name = type_name.trim();
    if name.is_empty() || name.starts_with("mapping(") {
        return None;
    }
    while let Some(open) = name.rfind('[') {
        if !name.ends_with(']') {
            break;
        }
        name = name[..open].trim_end();
    }
    // `uint256`, `address`, `bytes32`: a contract name starts with a capital.
    name.chars()
        .next()
        .filter(|first| first.is_ascii_uppercase())
        .map(|_| name)
}

/// Calls whose receiver the scan could not type as a contract — an empty type, a struct
/// field it could not follow — one line each, so the report can say what the map leaves out.
pub fn untyped_receivers(metadata: &EvmBatMetadata) -> Vec<String> {
    let mut lines: BTreeSet<String> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        for function in &contract.functions {
            let calls = function
                .unresolved_calls
                .iter()
                .map(|call| (&call.receiver, &call.method, &call.inferred_type))
                .chain(
                    function
                        .unknown_external_calls
                        .iter()
                        .map(|call| (&call.receiver, &call.method, &call.inferred_type)),
                );
            for (receiver, method, inferred_type) in calls {
                if classify_type(metadata, inferred_type) == TypeTarget::NotAContract {
                    let shown = if inferred_type.is_empty() {
                        "untyped".to_string()
                    } else {
                        inferred_type.clone()
                    };
                    lines.insert(format!(
                        "{}.{}: {receiver}.{method} ({shown})",
                        contract.name, function.name
                    ));
                }
            }
        }
    }
    lines.into_iter().collect()
}

/// Interfaces of this repository that some in-scope contract calls or holds, and that no
/// deployable contract declares as a base and no resolution binds.
///
/// Each one is classified as the outside, and for most of them that is the truth — an
/// interface file in `src/interfaces/` describing a protocol deployed elsewhere. But a contract
/// may implement an interface without `is IFace`, and then the map has just drawn a call into
/// this project's own code as a call out of it. Listing them is the difference between a
/// wrong map and a map with a question on it.
pub fn undeclared_interfaces(metadata: &EvmBatMetadata) -> Vec<String> {
    use crate::batbelt::evm::types::EvmContractType;
    let own_interfaces: BTreeSet<&str> = metadata
        .contracts
        .iter()
        .filter(|c| !c.vendored && c.contract_type == EvmContractType::Interface)
        .map(|c| c.name.as_str())
        .collect();
    let mut found: BTreeSet<String> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        let referenced = contract
            .functions
            .iter()
            .flat_map(|function| {
                function
                    .unresolved_calls
                    .iter()
                    .map(|call| call.inferred_type.clone())
                    .chain(
                        function
                            .unknown_external_calls
                            .iter()
                            .map(|call| call.inferred_type.clone()),
                    )
            })
            .chain(wired_at_construction(contract));
        for type_name in referenced {
            if let TypeTarget::Outside(name) = classify_type(metadata, &type_name) {
                if own_interfaces.contains(name.as_str()) {
                    found.insert(name);
                }
            }
        }
    }
    found.into_iter().collect()
}

/// How many contracts a scan without the `vendored` flag left in scope under `lib/`, or
/// `None` when the scan knows what is vendored.
///
/// The flag was added after the first scans shipped, and `serde(default)` reads its absence
/// as "nothing is vendored" — which is also, exactly, what a project with no dependencies
/// looks like. The two are told apart by the paths: a contract under a `lib/` segment with
/// `vendored == false` can only come from a scan that never set the flag.
pub fn predates_vendored(metadata: &EvmBatMetadata) -> Option<usize> {
    if metadata.contracts.iter().any(|contract| contract.vendored) {
        return None;
    }
    let under_lib = metadata
        .contracts
        .iter()
        .filter(|contract| {
            contract
                .file_path
                .split('/')
                .any(|segment| segment == "lib")
        })
        .count();
    (under_lib > 0).then_some(under_lib)
}

/// The relations as lines, grouped by the contract they leave from.
pub fn report(edges: &[Edge]) -> Vec<String> {
    let mut lines = vec![
        format!(
            "{} relation(s) between contracts — one per pair, whatever the number of calls",
            edges.len()
        ),
        String::new(),
    ];
    let mut current = String::new();
    for edge in edges {
        if edge.from != current {
            current = edge.from.clone();
            lines.push(current.clone());
        }
        lines.push(format!("  → {:<28} {}", edge.to, edge.relation.label()));
    }

    // Who the system turns around: the contracts most things point at.
    let mut incoming: BTreeMap<&str, usize> = BTreeMap::new();
    for edge in edges {
        *incoming.entry(edge.to.as_str()).or_default() += 1;
    }
    let mut ranked: Vec<(&str, usize)> = incoming.into_iter().collect();
    ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
    lines.push(String::new());
    lines.push("reached by the most contracts:".to_string());
    for (name, count) in ranked.iter().take(5) {
        lines.push(format!("  {name:<28} {count} contract(s) talk to it"));
    }
    lines
}

#[cfg(test)]
mod map_test {
    use super::{drawn_edges, Edge, Relation};

    /// A pair that both calls and is wired is ONE edge: the call, which is the stronger fact.
    #[test]
    fn the_stronger_relation_wins_a_pair() {
        assert!(Relation::Calls < Relation::WiresAtConstruction);
        assert!(Relation::WiresAtConstruction < Relation::Unresolved);
    }

    /// Edges sort by their source, which is what makes the report read as one block per
    /// contract.
    #[test]
    fn edges_group_by_their_source() {
        let mut edges = vec![
            Edge { from: "B".into(), to: "C".into(), relation: Relation::Calls },
            Edge { from: "A".into(), to: "C".into(), relation: Relation::Calls },
            Edge { from: "A".into(), to: "B".into(), relation: Relation::Calls },
        ];
        edges.sort();
        assert_eq!(edges[0].from, "A");
        assert_eq!(edges[0].to, "B");
        assert_eq!(edges[2].from, "B");
    }

    use super::{classify_type, predates_vendored, relations, undeclared_interfaces, TypeTarget};
    use crate::batbelt::evm::metadata::bat_metadata::{
        ContractMetadata, EvmBatMetadata, FunctionDependency, FunctionMetadata, UnresolvedCall,
    };
    use crate::batbelt::evm::types::{
        EvmContractType, EvmFileItem, EvmFileItemKind, EvmMutability, EvmVisibility,
        StorageVariable,
    };

    fn contract(
        name: &str,
        kind: EvmContractType,
        bases: &[&str],
        vendored: bool,
    ) -> ContractMetadata {
        ContractMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            using_libraries: Vec::new(),
            file_path: format!("./{}/{name}.sol", if vendored { "lib/dep/src" } else { "src" }),
            contract_type: kind,
            base_contracts: bases.iter().map(|b| b.to_string()).collect(),
            functions: Vec::new(),
            state_variables: Vec::new(),
            events: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            vendored,
        }
    }

    /// A function making one call on a receiver of the given interface type.
    fn calling(inferred_type: &str) -> FunctionMetadata {
        FunctionMetadata {
            metadata_id: format!("f_{inferred_type}"),
            name: "poke".to_string(),
            contract_name: String::new(),
            visibility: EvmVisibility::External,
            mutability: EvmMutability::NonPayable,
            modifiers: Vec::new(),
            params: Vec::new(),
            returns: Vec::new(),
            line: 1,
            end_line: 2,
            is_constructor: false,
            is_stub: false,
            storage_writes: Vec::new(),
            storage_write_sites: Vec::new(),
            unresolved_calls: vec![UnresolvedCall {
                receiver: "target".to_string(),
                method: "poke".to_string(),
                inferred_type: inferred_type.to_string(),
                candidates: Vec::new(),
                assigned_in: Vec::new(),
            }],
            unknown_external_calls: Vec::new(),
            resolved_calls: Vec::new(),
        }
    }

    fn immutable(type_name: &str) -> StorageVariable {
        StorageVariable {
            name: type_name.to_lowercase(),
            type_name: type_name.to_string(),
            visibility: EvmVisibility::Internal,
            is_constant: false,
            is_immutable: true,
            line: 3,
        }
    }

    fn pairs(edges: &[Edge]) -> Vec<(String, String, Relation)> {
        edges
            .iter()
            .map(|edge| (edge.from.clone(), edge.to.clone(), edge.relation))
            .collect()
    }

    /// A pair that is both CREATED and called keeps the creation. One arrow per pair, and the
    /// one kept is the one that says the most: that an address exists because of this line is
    /// the rare fact and the one nothing else on the board shows. `AscendYieldVault` creates
    /// `YieldExitReserve` in `_checkpoint` and calls it, and the map used to draw only the
    /// call, which read as two contracts that happened to find each other.
    #[test]
    fn a_created_and_called_pair_keeps_the_creation() {
        let mut vault = contract("AscendYieldVault", EvmContractType::Contract, &[], false);
        vault.functions.push(calling("YieldExitReserve"));
        let maker = vault.functions[0].metadata_id.clone();
        let metadata = EvmBatMetadata {
            contracts: vec![
                vault,
                contract("YieldExitReserve", EvmContractType::Contract, &[], false),
            ],
            function_dependencies: vec![FunctionDependency {
                function_metadata_id: maker,
                callees: vec!["YieldExitReserve.constructor".to_string()],
            }],
            ..Default::default()
        };
        assert_eq!(
            pairs(&relations(&metadata)),
            vec![(
                "AscendYieldVault".to_string(),
                "YieldExitReserve".to_string(),
                Relation::Creates
            )]
        );
    }

    /// `IListingLaunchpad is IAscendLaunchpad` declares the interface as a base too, and
    /// counting it made two implementers out of one: the collapse was blocked and the
    /// interface was drawn beside the contract that implements it. Only a deployable
    /// contract implements anything.
    #[test]
    fn an_interface_extending_an_interface_does_not_block_the_collapse() {
        let mut caller = contract("AscendCtoReceiver", EvmContractType::Contract, &[], false);
        caller.functions.push(calling("IAscendLaunchpad"));
        let metadata = EvmBatMetadata {
            contracts: vec![
                caller,
                contract("AscendLaunchpad", EvmContractType::Contract, &["IAscendLaunchpad"], false),
                contract("IAscendLaunchpad", EvmContractType::Interface, &[], false),
                contract("IListingLaunchpad", EvmContractType::Interface, &["IAscendLaunchpad"], false),
            ],
            ..Default::default()
        };
        assert_eq!(
            classify_type(&metadata, "IAscendLaunchpad"),
            TypeTarget::Contract("AscendLaunchpad".to_string())
        );
        assert_eq!(
            pairs(&relations(&metadata)),
            vec![("AscendCtoReceiver".to_string(), "AscendLaunchpad".to_string(), Relation::Calls)]
        );
    }

    /// Two deployable implementers and no resolution is a question, drawn as one.
    #[test]
    fn two_deployable_implementers_stay_an_open_question() {
        let mut caller = contract("Router", EvmContractType::Contract, &[], false);
        caller.functions.push(calling("IVault"));
        let metadata = EvmBatMetadata {
            contracts: vec![
                caller,
                contract("IVault", EvmContractType::Interface, &[], false),
                contract("VaultA", EvmContractType::Contract, &["IVault"], false),
                contract("VaultB", EvmContractType::Contract, &["IVault"], false),
            ],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "IVault"), TypeTarget::Open("IVault".to_string()));
        assert_eq!(
            pairs(&drawn_edges(&relations(&metadata), false)),
            vec![("Router".to_string(), "IVault".to_string(), Relation::Unresolved)]
        );
    }

    /// `Limits limits`, `CurveStep[] steps` and a mapping are state, not relations. They got
    /// onto the map because "starts with a capital letter" was the whole test for a contract.
    #[test]
    fn a_struct_typed_immutable_is_not_a_relation() {
        let mut vault = contract("AscendYieldVault", EvmContractType::Contract, &[], false);
        vault.state_variables.extend([
            immutable("Limits"),
            immutable("CurveStep[]"),
            immutable("mapping(Id => PendingUint192)"),
            immutable("PriceFeed"),
        ]);
        let metadata = EvmBatMetadata {
            contracts: vec![vault, contract("PriceFeed", EvmContractType::Contract, &[], false)],
            file_items: vec![EvmFileItem {
                name: "Limits".to_string(),
                kind: EvmFileItemKind::Struct,
                file_path: "./src/AscendYieldVault.sol".to_string(),
                line: 5,
                end_line: 9,
                vendored: false,
                owner: "AscendYieldVault".to_string(),
            }],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "Limits"), TypeTarget::NotAContract);
        assert_eq!(classify_type(&metadata, "CurveStep[]"), TypeTarget::NotAContract);
        assert_eq!(classify_type(&metadata, "mapping(Id => PendingUint192)"), TypeTarget::NotAContract);
        // With boundaries on, which is where the structs used to leak through as "outside".
        assert_eq!(
            pairs(&relations(&metadata)),
            vec![(
                "AscendYieldVault".to_string(),
                "PriceFeed".to_string(),
                Relation::WiresAtConstruction
            )]
        );
    }

    /// `ERC20 mirror` is an instance of somebody else's token at another address, and
    /// `AscendCoreToken is ERC20` says nothing about which token. The derives-from rule used
    /// to fold it into `AscendCoreToken` itself, where the self-call filter dropped it: a real
    /// boundary, gone without a word. A vendored contract type is the outside, never a box.
    #[test]
    fn a_vendored_contract_type_is_the_outside_not_its_in_scope_child() {
        let mut token = contract("AscendCoreToken", EvmContractType::Contract, &["ERC20"], false);
        token.state_variables.push(immutable("ERC20"));
        let metadata = EvmBatMetadata {
            contracts: vec![token, contract("ERC20", EvmContractType::Abstract, &["IERC20"], true)],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "ERC20"), TypeTarget::Outside("ERC20".to_string()));
        assert_eq!(
            pairs(&relations(&metadata)),
            vec![("AscendCoreToken".to_string(), "ERC20".to_string(), Relation::Boundary)]
        );
        // Drawn, as a leaf of its own caller: `ERC20@AscendCoreToken` is that contract's own
        // copy, so no two callers share a box for it.
        let drawn = drawn_edges(&relations(&metadata), false);
        assert_eq!(drawn.len(), 1);
        assert_eq!(drawn[0].to, "ERC20@AscendCoreToken");
        assert_eq!(super::box_text(&drawn[0].to), "ERC20");
        assert!(drawn_edges(&relations(&metadata), true).is_empty(), "--no-boundaries draws none");
    }

    /// An in-scope ABSTRACT contract used as a type still collapses into the one deployable
    /// contract that derives from it — that is this project's code, with an address.
    #[test]
    fn an_in_scope_abstract_type_collapses_into_its_deployable_child() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract("BaseVault", EvmContractType::Abstract, &[], false),
                contract("Vault", EvmContractType::Contract, &["BaseVault"], false),
            ],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "BaseVault"), TypeTarget::Contract("Vault".to_string()));
    }

    /// An interface of this repository that nothing declares to implement is the outside by
    /// the rule — and may be a contract implementing it without `is`. The map cannot know,
    /// so it names the interface and the command that settles it; a recorded resolution
    /// settles it.
    #[test]
    fn an_own_interface_nothing_declares_is_named_as_a_question() {
        let mut caller = contract("AscendCtoReceiver", EvmContractType::Contract, &[], false);
        caller.functions.push(calling("IListingLaunchpad"));
        let mut metadata = EvmBatMetadata {
            contracts: vec![
                caller,
                contract("ListingDesk", EvmContractType::Contract, &["ReentrancyGuard"], false),
                contract("IListingLaunchpad", EvmContractType::Interface, &[], false),
                // A vendored interface nothing implements is the outside with no question.
                contract("IMirrorFactory", EvmContractType::Interface, &[], true),
            ],
            ..Default::default()
        };
        metadata.contracts[0].functions.push(calling("IMirrorFactory"));
        assert_eq!(undeclared_interfaces(&metadata), vec!["IListingLaunchpad".to_string()]);

        metadata
            .resolutions
            .insert("IListingLaunchpad".to_string(), "ListingDesk".to_string());
        assert!(undeclared_interfaces(&metadata).is_empty());
        assert!(pairs(&drawn_edges(&relations(&metadata), false)).contains(&(
            "AscendCtoReceiver".to_string(),
            "ListingDesk".to_string(),
            Relation::Calls
        )));
    }

    /// A scan from before the flag marks nothing vendored and still has `lib/` in it. That is
    /// a map of forge-std, and the tool refuses rather than draws it.
    #[test]
    fn a_scan_before_the_vendored_flag_is_refused() {
        let mut stale = EvmBatMetadata {
            contracts: vec![
                contract("Vault", EvmContractType::Contract, &[], false),
                contract("Test", EvmContractType::Abstract, &[], false),
            ],
            ..Default::default()
        };
        stale.contracts[1].file_path = "./lib/forge-std/src/Test.sol".to_string();
        assert_eq!(predates_vendored(&stale), Some(1));

        // The same paths with the flag set is a scan that knows.
        let mut current = stale.clone();
        current.contracts[1].vendored = true;
        assert_eq!(predates_vendored(&current), None);

        // And a project with no `lib/` at all legitimately has nothing vendored.
        let bare = EvmBatMetadata {
            contracts: vec![contract("Vault", EvmContractType::Contract, &[], false)],
            ..Default::default()
        };
        assert_eq!(predates_vendored(&bare), None);
    }
}

#[cfg(test)]
mod folding_test {
    use super::{hosts, Relation};
    use crate::batbelt::evm::metadata::bat_metadata::{
        ContractMetadata, EvmBatMetadata, FunctionDependency,
    };
    use crate::batbelt::evm::types::EvmContractType;

    /// The map only ever reads a handful of fields; the rest of a scanned contract is noise
    /// here, and writing it out would hide what each test is actually about.
    fn contract(name: &str, kind: EvmContractType, bases: &[&str]) -> ContractMetadata {
        let mut built: ContractMetadata =
            serde_json::from_str(&format!(
                r#"{{"metadata_id":"{name}","name":"{name}","file_path":"./src/{name}.sol",
                    "contract_type":"{kind:?}","base_contracts":[],"functions":[],
                    "state_variables":[],"events":[],"modifiers":[],"line":1}}"#
            ))
            .expect("fixture parses");
        built.base_contracts = bases.iter().map(|base| base.to_string()).collect();
        built
    }

    fn with_function(mut contract: ContractMetadata, id: &str) -> ContractMetadata {
        let function = serde_json::from_str(&format!(
            r#"{{"metadata_id":"{id}","name":"f","contract_name":"{}","visibility":"Internal",
                "mutability":"NonPayable","modifiers":[],"params":[],"returns":[],"line":1,
                "end_line":2,"is_constructor":false}}"#,
            contract.name
        ))
        .expect("fixture parses");
        contract.functions.push(function);
        contract
    }

    fn metadata(contracts: Vec<ContractMetadata>, deps: Vec<(&str, &str)>) -> EvmBatMetadata {
        let mut built: EvmBatMetadata = serde_json::from_str(
            r#"{"contracts":[],"entry_points":[],"function_dependencies":[],"interfaces":[],
                "file_items":[]}"#,
        )
        .expect("an empty scan");
        built.contracts = contracts;
        built.function_dependencies = deps
            .into_iter()
            .map(|(id, callee)| FunctionDependency {
                function_metadata_id: id.to_string(),
                callees: vec![callee.to_string()],
            })
            .collect();
        built
    }

    /// A library used by one contract is that contract's code, and `hosts` says so.
    #[test]
    fn a_library_is_hosted_by_the_contract_that_uses_it() {
        let built = metadata(
            vec![
                with_function(contract("Vault", EvmContractType::Contract, &[]), "vault_f"),
                contract("MathLib", EvmContractType::Library, &[]),
            ],
            vec![("vault_f", "MathLib.wadMul")],
        );
        let hosted = hosts(&built);
        assert!(hosted["Vault"].contains("MathLib"));
        assert!(!hosted.contains_key("MathLib"), "a library hosts nobody");
    }

    /// A library reached only through another library still reaches the contract at the end:
    /// the fixpoint is what makes `FLAMMStore` → `FLAMMFlowLib` → `FLAMM` work.
    #[test]
    fn hosting_is_transitive() {
        let built = metadata(
            vec![
                with_function(contract("FLAMM", EvmContractType::Contract, &[]), "flamm_f"),
                with_function(contract("FlowLib", EvmContractType::Library, &[]), "flow_f"),
                contract("StoreLib", EvmContractType::Library, &[]),
            ],
            vec![("flamm_f", "FlowLib.run"), ("flow_f", "StoreLib.read")],
        );
        let hosted = hosts(&built);
        assert!(hosted["FLAMM"].contains("FlowLib"));
        assert!(hosted["FLAMM"].contains("StoreLib"), "reached through FlowLib");
    }

    /// An abstract base folds the same way, through inheritance.
    #[test]
    fn an_abstract_base_is_hosted_by_what_inherits_it() {
        let built = metadata(
            vec![
                contract("Router", EvmContractType::Contract, &["Pausable"]),
                contract("Pausable", EvmContractType::Abstract, &[]),
            ],
            vec![],
        );
        assert!(hosts(&built)["Router"].contains("Pausable"));
    }

}

#[cfg(test)]
mod report_test {
    use super::{hierarchy, Edge, Relation};

    fn edge(from: &str, to: &str, relation: Relation) -> Edge {
        Edge { from: from.to_string(), to: to.to_string(), relation }
    }

    /// The hierarchy names both ends and nothing in between: a top caller is what the map
    /// frames, a foundation is what everything else needs in order to exist.
    #[test]
    fn the_hierarchy_names_the_tops_and_the_foundations() {
        let edges = vec![
            edge("Launchpad", "Desk", Relation::Calls),
            edge("Desk", "Treasury", Relation::Calls),
            edge("Router", "Treasury", Relation::Calls),
        ];
        let lines = hierarchy(&edges, false);
        let tops: Vec<&String> = lines
            .iter()
            .take_while(|line| !line.is_empty())
            .filter(|line| line.starts_with("  "))
            .collect();
        assert_eq!(tops.len(), 2, "Launchpad and Router: {tops:?}");
        assert!(tops.iter().all(|line| line.contains("Launchpad") || line.contains("Router")));
        let foundations: Vec<&String> = lines
            .iter()
            .skip_while(|line| !line.is_empty())
            .filter(|line| line.starts_with("  "))
            .collect();
        assert_eq!(foundations.len(), 1, "only Treasury depends on nothing: {foundations:?}");
        assert!(foundations[0].contains("Treasury") && foundations[0].contains('2'));
    }

    /// The hierarchy is about this repository's contracts: what leaves the code is a badge,
    /// never a rung of the hierarchy, whichever way the flag is set.
    #[test]
    fn the_outside_is_never_part_of_the_hierarchy() {
        let edges = vec![
            edge("Vault", "IERC20", Relation::Boundary),
            edge("Vault", "Oracle", Relation::Calls),
        ];
        for no_boundaries in [true, false] {
            assert!(hierarchy(&edges, no_boundaries).iter().all(|line| !line.contains("IERC20")));
        }
        assert!(hierarchy(&edges, false).iter().any(|line| line.contains("Oracle")));
    }
}

#[cfg(test)]
mod visual_test {
    use super::{
        centre_out, legend_rows, order_hub_column, route_arrows, strip_of, style_of, Edge,
        Relation, Sample, CYCLE_COLOUR, EDGE_COLOUR, LEGEND_ROWS, NODE_HEIGHT, STRIP_HEADING,
    };
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    use crate::batbelt::miro::client::ConnectorStroke;
    use crate::batbelt::miro::layout::{GraphLayout, PlacedNode};

    fn edge(from: &str, to: &str, relation: Relation) -> Edge {
        Edge { from: from.to_string(), to: to.to_string(), relation }
    }

    fn node(id: &str, layer: usize, x: f64, y: f64) -> PlacedNode {
        PlacedNode { id: id.to_string(), layer, x, y, width: 1_000.0, height: NODE_HEIGHT }
    }

    /// A layout as `layout_graph` would hand it back: columns 1 000 wide at a 2 000 pitch,
    /// every route listed from the CALLEE's column outwards.
    fn layout(nodes: Vec<PlacedNode>, routes: Vec<Vec<(f64, f64)>>) -> GraphLayout {
        GraphLayout {
            nodes,
            routes,
            back_edges: Vec::new(),
            bbox_width: 8_000.0,
            bbox_height: 4_000.0,
            frame_width: 9_200.0,
            frame_height: 5_200.0,
            crossings: 0,
        }
    }

    /// The legs of one arrow as point-to-point segments.
    fn segments(arrow: &super::RoutedArrow) -> Vec<((f64, f64), (f64, f64))> {
        arrow
            .plan
            .legs
            .iter()
            .filter_map(|(from, _, to, _, _)| {
                let at = |side: &LaneSide| match side {
                    LaneSide::Marker(index) => arrow.plan.points.get(*index).copied(),
                    LaneSide::Item(_) => None,
                };
                Some((at(from)?, at(to)?))
            })
            .collect()
    }

    /// The layout bends an edge from the callee's column outwards, and the chain is drawn from
    /// the caller: consumed as listed, an arrow skipping two columns ran its corridor legs at
    /// the wrong columns' heights — through the boxes. The corridor beside the caller comes
    /// first.
    #[test]
    fn corridors_are_walked_from_the_callers_side() {
        let laid = layout(
            // The caller is column 0 — its frame's own contract — and the chain grows right.
            vec![node("Caller", 0, 500.0, 3_000.0), node("Callee", 3, 6_500.0, 1_000.0)],
            // Column 1's corridor at y = 2 400, column 2's at y = 1 700: caller-first order.
            vec![vec![(2_000.0, 2_400.0), (4_000.0, 1_700.0)]],
        );
        let routed = route_arrows(&[edge("Caller", "Callee", Relation::Calls)], &laid, false);
        let arrow = routed.iter().find(|arrow| arrow.edge == Some(0)).expect("the arrow");
        let legs = segments(arrow);
        // Leg 1 leaves the caller; leg 2 runs up the first lane to the FIRST corridor the
        // arrow meets, which is the column beside the caller.
        let first_drop = legs[1];
        assert_eq!(first_drop.0 .1, 3_000.0, "from the caller's row: {legs:?}");
        assert_eq!(first_drop.1 .1, 2_400.0, "to the corridor of the column beside the caller: {legs:?}");
        // Two skipped columns: at most 2s + 2 markers and 2s + 3 legs — fewer when two of them
        // land on the same point, which `tighten` collapses rather than asking Miro to draw a
        // connector from an item to itself.
        assert!(arrow.plan.points.len() <= 6 + 2, "{:?}", arrow.plan.points);
        assert!(arrow.plan.legs.len() <= 7);
        assert!(arrow.plan.legs.last().expect("a leg").4, "the last leg still carries the head");
    }

    /// Five arrows into one contract used to meet its border at one point. They land spread
    /// along the side, in the order they arrive from, so none crosses another at the box.
    #[test]
    fn arrows_meeting_one_box_are_spread_along_its_side() {
        let laid = layout(
            vec![
                node("Top", 0, 500.0, 500.0),
                node("Mid", 0, 500.0, 2_000.0),
                node("Low", 0, 500.0, 3_500.0),
                node("Hub", 1, 2_500.0, 2_000.0),
            ],
            vec![Vec::new(), Vec::new(), Vec::new()],
        );
        let edges = [
            edge("Low", "Hub", Relation::Calls),
            edge("Top", "Hub", Relation::Calls),
            edge("Mid", "Hub", Relation::Calls),
        ];
        let routed = route_arrows(&edges, &laid, false);
        let landing = |index: usize| {
            let arrow = routed.iter().find(|arrow| arrow.edge == Some(index)).expect("drawn");
            segments(arrow).last().expect("the head leg").1 .1
        };
        let (low, top, mid) = (landing(0), landing(1), landing(2));
        assert!(top < mid && mid < low, "landings follow where the arrows come from: {top} {mid} {low}");
        assert!((low - top) <= NODE_HEIGHT - 2.0 * super::ANCHOR_INSET, "and stay on the box's side");
        assert_eq!(mid, 2_000.0, "the middle one lands on the middle");
    }

    /// The first column is ordered by how many contracts point at each box, from the middle
    /// outwards: the hub in the middle, where its arrows split above and below it.
    #[test]
    fn the_hub_column_puts_the_most_called_in_the_middle() {
        let mut laid = layout(
            vec![
                node("A", 0, 500.0, 500.0),
                node("B", 0, 500.0, 1_000.0),
                node("Hub", 0, 500.0, 1_500.0),
                node("D", 0, 500.0, 2_000.0),
                node("E", 0, 500.0, 2_500.0),
                node("Caller", 1, 2_500.0, 500.0),
            ],
            Vec::new(),
        );
        let edges = [
            edge("Caller", "A", Relation::Calls),
            edge("Caller", "E", Relation::Calls),
            edge("Caller", "E", Relation::Creates),
            edge("Caller", "Hub", Relation::Calls),
        ];
        // E is reached by two relations, Hub by one, A by one, B and D by none.
        order_hub_column(&mut laid, &edges);
        let y = |id: &str| laid.nodes.iter().find(|node| node.id == id).expect(id).y;
        assert_eq!(y("E"), 1_500.0, "the most called takes the middle slot");
        assert_eq!(y("Caller"), 500.0, "other columns are untouched");
        let mut ys: Vec<f64> = ["A", "B", "Hub", "D", "E"].iter().map(|id| y(id)).collect();
        ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
        assert_eq!(ys, vec![500.0, 1_000.0, 1_500.0, 2_000.0, 2_500.0], "the same slots, reassigned");
    }

    #[test]
    fn centre_out_fills_the_middle_then_alternates() {
        let order: Vec<usize> = (0..5).map(|rank| centre_out(rank, 5)).collect();
        assert_eq!(order, vec![2, 3, 1, 4, 0]);
        let order: Vec<usize> = (0..4).map(|rank| centre_out(rank, 4)).collect();
        assert_eq!(order, vec![1, 2, 0, 3]);
    }

    /// One colour for the relations a reader walks, three strokes to tell them apart, and the
    /// two colours that mean something: red for an arrow that runs backwards, green for one
    /// that DEPLOYED the contract at its head. Neither carries a word any more.
    #[test]
    fn one_colour_three_strokes_and_a_colour_where_it_means_something() {
        for relation in [Relation::Calls, Relation::WiresAtConstruction, Relation::Unresolved] {
            assert_eq!(style_of(relation, false).stroke_color, EDGE_COLOUR);
        }
        assert_eq!(style_of(Relation::Creates, false).stroke_color, super::CREATES_COLOUR);
        assert_eq!(style_of(Relation::Creates, false).caption, None, "the colour replaced the word");
        assert_eq!(style_of(Relation::Calls, false).stroke, ConnectorStroke::Solid);
        assert_eq!(style_of(Relation::Unresolved, false).stroke, ConnectorStroke::Dashed);
        assert_eq!(style_of(Relation::Unresolved, false).caption.as_deref(), Some("?"));
        assert_eq!(style_of(Relation::WiresAtConstruction, false).stroke, ConnectorStroke::Dotted);
        assert_eq!(style_of(Relation::Calls, true).stroke_color, CYCLE_COLOUR);
    }

    /// A cycle — the layout had to reverse it — is drawn red, by us and not by Miro, and the
    /// short way round: out of the caller's left, one row down, across, up and in. It used to
    /// be dropped without a word, then drawn through the boxes, then sent on a lap of the whole
    /// frame to reach a contract two rows above.
    #[test]
    fn a_backwards_arrow_is_drawn_red_box_to_box() {
        let laid = layout(
            vec![node("Left", 0, 500.0, 1_000.0), node("Right", 1, 2_500.0, 1_000.0)],
            vec![Vec::new(), Vec::new()],
        );
        let edges = [
            // Left → Right is the flow; Right → Left runs back against it and is the cycle.
            edge("Left", "Right", Relation::Calls),
            edge("Right", "Left", Relation::Calls),
        ];
        let routed = route_arrows(&edges, &laid, false);
        let back = routed.iter().find(|arrow| arrow.edge == Some(1)).expect("the cycle is drawn");
        assert_eq!(back.style.stroke_color, CYCLE_COLOUR);
        let legs = segments(back);
        // Down out of the caller, left under every box, up into the callee: three legs, the
        // head on the last. Routed by us and not by Miro, which drew it through the middle of
        // the frame and across every other arrow.
        assert_eq!(legs.len(), 5);
        let row_bottom = 1_000.0 + NODE_HEIGHT / 2.0;
        assert_eq!(legs[0].0, (2_000.0, 1_000.0), "out of Right's LEFT side, towards the callee");
        assert!(legs[0].1 .0 < 2_000.0, "into the lane beside it: {legs:?}");
        assert!(legs[1].1 .1 > row_bottom, "down just past its own row, not past the frame");
        assert_eq!(legs[2].0 .1, legs[2].1 .1, "along the corridor");
        assert!(legs[3].1 .0 < 0.0, "up outside the callee's column");
        assert_eq!(legs[4].1, (0.0, 1_000.0), "and into Left's left side");
        assert!(back.plan.legs[..4].iter().all(|leg| !leg.4), "no head before the end");
        assert!(back.plan.legs[4].4, "the last leg carries the head");
    }

    /// The legend is drawn by the same code as the map: its samples are arrows, so they are
    /// counted and previewed with the rest, and the layout reserves exactly its rows.
    #[test]
    fn the_legend_is_rows_of_real_samples() {
        let rows = legend_rows();
        assert_eq!(rows.len(), LEGEND_ROWS);
        let legs = rows.iter().filter(|row| matches!(row.sample, Sample::Leg(_))).count();
        let laid = layout(vec![node("A", 0, 500.0, 1_000.0), node("B", 1, 2_500.0, 1_000.0)], vec![Vec::new()]);
        let routed = route_arrows(&[edge("B", "A", Relation::Calls)], &laid, true);
        assert_eq!(routed.iter().filter(|arrow| arrow.edge.is_none()).count(), legs);
        assert!(rows.iter().any(|row| matches!(row.sample, Sample::Leg(ref style) if style.stroke_color == CYCLE_COLOUR)));
    }

    /// The strip stacks under the legend's rows, heading first — present on the picture, and
    /// apart from the diagrams.
    #[test]
    fn the_strip_stacks_under_the_legend() {
        let strip = strip_of(&["Alone".to_string(), "Proxy".to_string()], 4_000.0);
        assert_eq!(strip.len(), 3);
        assert_eq!(strip[0].id, STRIP_HEADING);
        assert_eq!(strip[0].y, 4_000.0);
        assert!(strip[1].y > strip[0].y && strip[2].y > strip[1].y);
        assert!(strip_of(&[], 4_000.0).is_empty());
    }
}

#[cfg(test)]
mod framing_test {
    use super::{original_of, partition_frames, unfold, BTreeMap, Edge, Relation};

    fn edge(from: &str, to: &str) -> Edge {
        Edge { from: from.to_string(), to: to.to_string(), relation: Relation::Calls }
    }

    /// One frame per top caller, each holding everything that caller reaches. A contract two
    /// of them use is in both — repeated on purpose, the way a screenshot is repeated in two
    /// deployment frames, because a copy is cheap and a crossing arrow is not.
    #[test]
    fn a_frame_per_top_caller_repeats_what_they_share() {
        let edges = vec![edge("Launchpad", "Treasury"), edge("Router", "Treasury")];
        let frames = partition_frames(&edges);
        assert_eq!(frames.len(), 2);
        assert!(frames.iter().any(|plan| plan.root == "Launchpad"));
        assert!(frames.iter().any(|plan| plan.root == "Router"));
        assert!(
            frames.iter().all(|plan| plan.edges.len() == 1 && plan.edges[0].to == "Treasury"),
            "Treasury is drawn in both frames"
        );
    }

    /// A frame holds the whole chain under its top, not only what it calls directly.
    #[test]
    fn a_frame_holds_everything_its_top_reaches() {
        let edges = vec![edge("Launchpad", "Desk"), edge("Desk", "Treasury")];
        let frames = partition_frames(&edges);
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].root, "Launchpad");
        assert_eq!(frames[0].edges.len(), 2);
    }

    /// A cycle nothing points into has no top caller, and is still every bit as much a part of
    /// the system — it gets a frame rather than being dropped.
    #[test]
    fn a_cycle_with_nothing_above_it_still_gets_a_frame() {
        let edges = vec![edge("A", "B"), edge("B", "A")];
        let frames = partition_frames(&edges);
        assert_eq!(frames.len(), 1, "one frame, not none: {frames:?}");
        assert_eq!(frames[0].edges.len(), 2, "both relations drawn");
    }

    /// The tree the frame draws has no crossings — which is the certificate, printed per frame,
    /// and not something anyone has to judge from a picture.
    #[test]
    fn the_tree_a_frame_draws_has_no_crossings() {
        let edges = vec![
            edge("Top", "Middle"),
            edge("Top", "Shared"),
            edge("Middle", "Shared"),
            edge("Top", "Other"),
            edge("Other", "Shared"),
        ];
        assert_eq!(super::layout_map(&unfold("Top", &edges)).crossings, 0);
    }

    /// A frame is self-contained: everything its contract reaches is IN it, and a contract two
    /// branches both reach is drawn twice rather than lifted into a frame of its own. Fewer
    /// frames, each answering one question, beats fewer boxes.
    #[test]
    fn a_frame_holds_its_whole_tree_and_repeats_what_is_shared() {
        let edges = vec![
            edge("Registry", "Receiver"),
            edge("Receiver", "Desk"),
            edge("Registry", "Desk"),
            edge("Desk", "Treasury"),
        ];
        let frames = partition_frames(&edges);
        assert_eq!(frames.len(), 1, "one top caller, one frame: {frames:?}");
        let mine = &frames[0].edges;
        // Desk is reached two ways, so it is drawn twice — and `Treasury` under each of them.
        let desks: Vec<&str> = mine
            .iter()
            .map(|edge| edge.to.as_str())
            .filter(|to| original_of(to) == "Desk")
            .collect();
        assert_eq!(desks.len(), 2, "Desk is drawn once per branch that reaches it: {mine:?}");
        assert_ne!(desks[0], desks[1], "and the two are different boxes");
        assert_eq!(
            mine.iter().filter(|edge| original_of(&edge.to) == "Treasury").count(),
            2,
            "its own chain comes with each copy"
        );
    }

    /// Nothing is shared inside a frame, which is what makes it a tree: every box has exactly
    /// one arrow into it.
    #[test]
    fn a_frame_is_a_tree() {
        let edges = vec![
            edge("Top", "Middle"),
            edge("Top", "Shared"),
            edge("Middle", "Shared"),
            edge("Shared", "Leaf"),
        ];
        let mine = unfold("Top", &edges);
        let mut into: BTreeMap<&str, usize> = BTreeMap::new();
        for edge in &mine {
            *into.entry(edge.to.as_str()).or_default() += 1;
        }
        assert!(into.values().all(|count| *count == 1), "one arrow into each box: {into:?}");
    }

    /// A cycle has no top caller, so one of its members has to be the frame's root — and it is
    /// the one that CALLS THE MOST, not whichever the relations happen to list first.
    #[test]
    fn the_root_of_a_cycle_is_the_member_that_calls_the_most() {
        let edges = vec![
            // `Quiet` comes first alphabetically and calls one; `Busy` calls three. The frame
            // belongs to `Busy`, whose story is the longer one.
            edge("Quiet", "Busy"),
            edge("Busy", "Quiet"),
            edge("Busy", "LeafOne"),
            edge("Busy", "LeafTwo"),
        ];
        let frames = partition_frames(&edges);
        assert_eq!(frames.len(), 1, "one cycle, one frame: {frames:?}");
        assert_eq!(frames[0].root, "Busy");
        assert_eq!(frames[0].edges.len(), 4, "and it draws every relation of the cycle");
    }

    /// A cycle is NOT unfolded for ever: the arrow goes back to the copy this path came
    /// through, which is the one red arrow on the frame.
    #[test]
    fn a_cycle_points_back_instead_of_unfolding() {
        let edges = vec![edge("A", "B"), edge("B", "C"), edge("C", "A")];
        let mine = unfold("A", &edges);
        assert_eq!(mine.len(), 3, "three relations, drawn once each: {mine:?}");
        let back = mine.iter().find(|edge| edge.to == "A").expect("the arrow home");
        assert_eq!(back.from, "C");
    }

    /// What leaves the repository is drawn — and every caller gets its OWN copy of it. One
    /// shared `IERC20` pulled an arrow from each of its seven callers across the whole frame;
    /// an outside box has no chain under it, so a copy costs one box and saves a crossing.
    #[test]
    fn every_caller_gets_its_own_copy_of_what_is_outside() {
        let all = vec![
            Edge { from: "Vault".into(), to: "IERC20".into(), relation: Relation::Boundary },
            Edge { from: "Router".into(), to: "IERC20".into(), relation: Relation::Boundary },
            edge("Vault", "Oracle"),
        ];
        let drawn = super::drawn_edges(&all, false);
        let outside: Vec<&str> = drawn
            .iter()
            .filter(|edge| edge.relation == Relation::Boundary)
            .map(|edge| edge.to.as_str())
            .collect();
        assert_eq!(outside, vec!["IERC20@Vault", "IERC20@Router"], "never one shared box");
        for id in outside {
            assert_eq!(original_of(id), "IERC20", "and both read as IERC20");
            assert!(super::is_outside(id));
        }
        assert!(
            super::drawn_edges(&all, true).iter().all(|edge| edge.to == "Oracle"),
            "--no-boundaries leaves them out altogether"
        );
    }

    /// Within a frame, every copy of one interface carries ONE colour and no two interfaces
    /// carry the same: the copies are what keep the arrows short, the colour is what says the
    /// four boxes reading `IERC20` are one thing.
    #[test]
    fn one_colour_per_interface_and_never_two_the_same() {
        let all = vec![
            Edge { from: "Vault".into(), to: "IERC20".into(), relation: Relation::Boundary },
            Edge { from: "Router".into(), to: "IERC20".into(), relation: Relation::Boundary },
            Edge { from: "Vault".into(), to: "IVault".into(), relation: Relation::Boundary },
            edge("Vault", "Oracle"),
        ];
        let drawn = super::drawn_edges(&all, false);
        let fills = super::PreparedFrame::outside_fills(&drawn);
        assert_eq!(fills.len(), 2, "one entry per interface, not per copy: {fills:?}");
        assert_ne!(fills["IERC20"], fills["IVault"], "two interfaces never share a colour");
        // Both copies of IERC20 resolve to the same fill, whichever caller they belong to.
        assert_eq!(fills[original_of("IERC20@Vault")], fills[original_of("IERC20@Router")]);
    }

    /// A frame is laid out as a TREE: a parent sits at the middle of its children and one column
    /// to their left, so a box is always beside the boxes it points at. Packed from the top
    /// instead, a contract's callees sat level with somebody else's and following one arrow
    /// meant scrolling a frame whose answer was two boxes apart.
    #[test]
    fn a_parent_sits_beside_its_own_children() {
        let edges = vec![
            edge("Root", "First"),
            edge("Root", "Second"),
            edge("Second", "Deep"),
            edge("Second", "Deeper"),
        ];
        let layout = super::layout_tree("Root", &edges);
        let at = |id: &str| layout.node(id).cloned().expect(id);
        assert_eq!(at("Root").layer, 0);
        assert_eq!(at("Second").layer, 1);
        assert_eq!(at("Deep").layer, 2, "a column per depth");
        assert!(at("Root").x < at("Second").x && at("Second").x < at("Deep").x, "left to right");
        // Each parent at the middle of its own children, which is what puts it beside them.
        let middle = |a: f64, b: f64| (a + b) / 2.0;
        assert!((at("Second").y - middle(at("Deep").y, at("Deeper").y)).abs() < 1.0);
        assert!((at("Root").y - middle(at("First").y, at("Second").y)).abs() < 1.0);
        assert_eq!(layout.crossings, 0, "a tidy tree cannot cross");
    }

    /// The frame of a CYCLE still draws its boxes: its root is the one the caller names, not
    /// "whatever has no parent" — in a cycle the root is itself somebody's callee, so that rule
    /// found no root and the frame reached the board titled and empty.
    #[test]
    fn the_frame_of_a_cycle_is_not_empty() {
        let edges = vec![
            edge("Converter", "Treasury"),
            edge("Treasury", "Converter"),
            edge("Converter", "Oracle"),
        ];
        let mine = unfold("Converter", &edges);
        let layout = super::layout_tree("Converter", &mine);
        assert_eq!(layout.nodes.len(), 3, "every box is placed: {:?}", layout.nodes);
        assert_eq!(layout.node("Converter").expect("the root").layer, 0);
        assert!(layout.frame_width > 0.0 && layout.frame_height > 0.0);
    }

    /// A contract drawn twice in one frame carries its own border colour on both copies, so the
    /// two boxes read as one address; a contract drawn once keeps the plain border, because a
    /// colour that means nothing is a colour to decode.
    #[test]
    fn a_contract_drawn_twice_gets_a_border_of_its_own() {
        let edges = vec![
            edge("Registry", "Receiver"),
            edge("Registry", "Desk"),
            edge("Receiver", "Desk"),
        ];
        let mine = unfold("Registry", &edges);
        let borders = super::PreparedFrame::repeat_borders(&mine);
        assert_eq!(borders.len(), 1, "only Desk is drawn twice: {borders:?}");
        let desk = borders["Desk"];
        assert_ne!(desk, super::BOX_BORDER);
        // Both copies carry it, and `Receiver`, drawn once, does not.
        let frame = super::PreparedFrame {
            title: String::new(),
            edges: mine.clone(),
            layout: super::layout_map(&mine),
            arrows: Vec::new(),
            fills: BTreeMap::new(),
            borders,
            strip: Vec::new(),
            width: 0.0,
            height: 0.0,
            crossings: 0,
            left: 0.0,
            top: 0.0,
        };
        assert_eq!(frame.border_of("Desk"), (desk, super::REPEAT_BORDER_WIDTH));
        assert_eq!(frame.border_of("Desk#2"), (desk, super::REPEAT_BORDER_WIDTH));
        assert_eq!(frame.border_of("Receiver"), (super::BOX_BORDER, super::BORDER_WIDTH));
        assert!(
            super::REPEAT_BORDER_WIDTH > super::BORDER_WIDTH,
            "a colour nobody can see at the frame's zoom is not a signal"
        );
    }

    /// A copy is a second box for the same contract, and reads as that contract.
    #[test]
    fn a_copy_carries_its_originals_name() {
        assert_eq!(original_of("Treasury#2"), "Treasury");
        assert_eq!(original_of("Treasury"), "Treasury");
        assert_eq!(super::box_text("Treasury#3"), "Treasury");
    }
}

#[cfg(test)]
mod failure_message_test {
    use crate::batbelt::miro::MiroError;
    use error_stack::Report;

    /// A failed item says WHY: the HTTP status and Miro's own words, which the client already
    /// attaches. Printing the context alone printed "Miro error" and nothing a reader can act on.
    #[test]
    fn a_failure_carries_the_api_s_own_words() {
        let report = Report::new(MiroError)
            .attach_printable("create_connector: HTTP 400 Bad Request: {\"message\":\"too close\"}".to_string());
        let line = super::why(&report);
        assert!(line.contains("400"), "{line}");
        assert!(line.contains("too close"), "{line}");
    }

    /// Nothing attached, nothing invented: the context is still better than an empty line.
    #[test]
    fn a_bare_failure_still_says_something() {
        assert_eq!(super::why(&Report::new(MiroError)), MiroError.to_string());
    }
}

#[cfg(test)]
mod marker_test {
    use super::{layout_tree, route_arrows, Edge, Relation};

    /// No two markers of one arrow land on the same point.
    ///
    /// Miro refuses a connector whose two ends are the same item — `"The startitem id and
    /// enditem id cannot be the same"` — and two markers at identical coordinates come back
    /// from the bulk endpoint as one item, so an arrow that plans a zero-length leg is an arrow
    /// that cannot be drawn. It cost four relations on a real board.
    #[test]
    fn no_leg_of_an_arrow_is_zero_length() {
        let edges = vec![Edge {
            from: "AscendFeeController".into(),
            to: "ICLPoolManager@AscendFeeController".into(),
            relation: Relation::Boundary,
        }];
        let layout = layout_tree("AscendFeeController", &edges);
        for arrow in route_arrows(&edges, &layout, false) {
            for (index, point) in arrow.plan.points.iter().enumerate() {
                for other in arrow.plan.points.iter().skip(index + 1) {
                    assert!(
                        (point.0 - other.0).abs() > 0.5 || (point.1 - other.1).abs() > 0.5,
                        "two markers on {point:?}: {:?}",
                        arrow.plan.points
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod card_test {
    use super::{CARD_GAP, CARD_WIDTH, MAX_CARDS};
    use crate::batbelt::miro::client::MiroClient;

    /// The cards of one cluster are centred on its shape and evenly spread, so three of them
    /// read as one row belonging to one column rather than as three loose chips.
    fn placed(count: usize, centre: f64) -> Vec<f64> {
        let drawn = count.min(MAX_CARDS);
        let span = drawn as f64 * CARD_WIDTH + (drawn as f64 - 1.0) * CARD_GAP;
        (0..drawn)
            .map(|index| centre - span / 2.0 + CARD_WIDTH / 2.0 + index as f64 * (CARD_WIDTH + CARD_GAP))
            .collect()
    }

    #[test]
    fn cards_are_centred_on_the_cluster_and_evenly_spread() {
        let centre = 10_000.0;
        let one = placed(1, centre);
        assert_eq!(one, vec![centre], "a single card sits on the centre");
        let three = placed(3, centre);
        assert_eq!(three.len(), 3);
        let middle = (three[0] + three[2]) / 2.0;
        assert!((middle - centre).abs() < 1.0, "the row is centred: {three:?}");
        assert!(
            ((three[1] - three[0]) - (three[2] - three[1])).abs() < 1.0,
            "evenly spread: {three:?}"
        );
        assert!((three[1] - three[0]) >= CARD_WIDTH, "and never overlapping");
    }

    /// Past the cap the row stops growing: a cluster is not a place to list twelve frames.
    #[test]
    fn a_cluster_never_carries_more_than_the_cap() {
        assert_eq!(placed(12, 0.0).len(), MAX_CARDS);
    }

    /// The card carries the frame's URL as an anchor INSIDE its text, because Miro's REST API
    /// rejects `linkedTo` — and the words name the frame, so a deleted map leaves a card that
    /// still says something true.
    #[test]
    fn a_card_carries_the_link_in_its_words() {
        let item = MiroClient::link_card_item(
            "map · YieldRouter",
            "https://miro.com/app/board/x=/?moveToWidget=123",
            0.0,
            0.0,
            100.0,
            50.0,
            90,
            "#ffffff",
            "#1a73e8",
        );
        let content = item["data"]["content"].as_str().expect("the words");
        assert!(content.contains("moveToWidget=123"), "{content}");
        assert!(content.contains("YieldRouter"), "{content}");
        assert!(item["parent"].is_null(), "a card sits on the board, not inside a frame");
    }
}

#[cfg(test)]
mod cards_for_test {
    use super::frames_showing;
    use crate::batbelt::evm::metadata::bat_metadata::MapFrameRef;

    fn frame(root: &str, contracts: &[&str]) -> MapFrameRef {
        MapFrameRef {
            root: root.to_string(),
            frame_id: format!("id-{root}"),
            contracts: contracts.iter().map(|name| name.to_string()).collect(),
            cards: Vec::new(),
        }
    }

    /// A cluster is carded for every frame that DRAWS its contract, not only for the frame
    /// named after it: `Treasury` is a leaf of three other systems and has no frame of its own.
    #[test]
    fn a_cluster_is_carded_for_every_frame_that_draws_it() {
        let frames = [
            frame("YieldRouter", &["YieldRouter", "AscendLaunchpad", "Treasury"]),
            frame("AscendCtoRegistry", &["AscendCtoRegistry", "Treasury"]),
            frame("ReferralPot", &["ReferralPot"]),
        ];
        let roots: Vec<&str> = frames_showing(&frames, "Treasury")
            .iter()
            .map(|frame| frame.root.as_str())
            .collect();
        assert_eq!(roots, vec!["YieldRouter", "AscendCtoRegistry"]);
        assert!(frames_showing(&frames, "BurnSink").is_empty(), "nothing drawn, nothing to point at");
    }
}

#[cfg(test)]
mod stale_card_test {
    use super::is_map_card;
    use crate::batbelt::miro::client::MiroClient;

    /// A card is recognised on the board by its OWN signature, so a lost registry cannot leave
    /// one behind: the prefix it is written with and the link it carries, both.
    #[test]
    fn a_card_is_recognised_by_what_it_says() {
        let card = MiroClient::link_card_item(
            "map · YieldRouter",
            "https://miro.com/app/board/x=/?moveToWidget=123",
            0.0,
            0.0,
            10.0,
            10.0,
            90,
            "#ffffff",
            "#1a73e8",
        );
        assert!(is_map_card(card["data"]["content"].as_str().expect("the words")));
    }

    /// Nothing else is touched. This is the only place the tool deletes an item it holds no id
    /// for, so the test is the guard: a note of the auditor's that merely mentions the map, or
    /// a link of theirs to a frame, is NOT a card.
    #[test]
    fn nothing_the_auditor_wrote_is_mistaken_for_one() {
        assert!(!is_map_card("<p>map · YieldRouter</p>"), "a label with no link");
        assert!(
            !is_map_card("<p><a href=\"https://miro.com/app/board/x=/?moveToWidget=9\">ir al mapa</a></p>"),
            "a link of their own, without the prefix"
        );
        assert!(!is_map_card("<p>revisar el map de nuevo</p>"));
    }
}