paperboy 0.6.0

A Rust TUI API tester
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
//! Front-end-agnostic **structural editing** of a PaperTrail [`ReportFlow`] —
//! the operations behind the "Scratch-like" node/block editors in both the
//! terminal UI and the GUI.
//!
//! A report flow is a linear/nested outline of statements, so authoring it is a
//! matter of inserting / removing / moving / replacing whole *nodes* rather than
//! typing text. These helpers flatten the AST into a navigable list of rows and
//! mutate it by *path* (a sequence of indices, each stepping into a loop body),
//! keeping the tree the single source of truth: every structural edit
//! re-serializes back to `report.text` via [`ReportFlow::to_text`], so the text
//! and node views round-trip and both front-ends share this one implementation.

// The modifier half of this API (attach / detach / carry / transfer) exists for
// the GUI's block editor — the terminal UI reaches its node editor through its
// own wizards and uses only the insert/move/replace half. It stays compiled in a
// terminal-only build so this module remains one shared core with one test
// suite, rather than splintering along a front-end boundary.
#![cfg_attr(not(feature = "gui"), allow(dead_code))]

use crate::i18n::Strings;
use crate::report::flow::{
    Binder, EnvClause, FlowNode, HeaderLine, ImageSpec, OverrideTarget, ParallelSpec, Pattern,
    Producer, ReportFlow, ReportStmt, ResponseFmt, RoleRef, ShowField, UsingItem, WithItem,
};
use crate::report::model::StatKind;
use crate::report::parse_flow;

// ---------------------------------------------------------------------------
// The `USING(…)` requirement checklist
// ---------------------------------------------------------------------------

/// One row of a request node's `USING(…)` parameter checklist.
pub struct ParamRow {
    pub name: String,
    /// Ticked ⇒ named in `USING(…)`: this call declares that it relies on the
    /// request being steerable by that name.
    pub required: bool,
    /// The value the request declares as its default (`[Options] variable:
    /// NAME=…`), shown beside the row so it is obvious what the request does
    /// when nothing steers it. `None` means the clause requires a name the
    /// request doesn't declare — a validation error, kept as a row so it can be
    /// un-ticked where the error is seen rather than only in the source view.
    pub default: Option<String>,
}

/// Build the checklist: one row per parameter the request declares, ticked when
/// the clause requires it, followed by any requirement the request *doesn't*
/// declare.
///
/// Both front-ends' request node forms show this, so it lives here rather than
/// twice — the terminal UI draws it as a column of checkboxes and the GUI as an
/// egui checklist, but which rows exist, and what they mean, is one decision.
pub fn param_rows(declared: &[(String, String)], using: &[UsingItem]) -> Vec<ParamRow> {
    let required = |name: &str| {
        using
            .iter()
            .any(|i| matches!(i, UsingItem::Require(n) if n == name))
    };
    let mut rows: Vec<ParamRow> = declared
        .iter()
        .map(|(name, value)| ParamRow {
            name: name.clone(),
            required: required(name),
            default: Some(value.clone()),
        })
        .collect();
    for item in using {
        if let UsingItem::Require(name) = item
            && !rows.iter().any(|r| &r.name == name)
        {
            rows.push(ParamRow {
                name: name.clone(),
                required: true,
                default: None,
            });
        }
    }
    rows
}

/// One per-call override of a `USING(…)` clause, as a node form edits it: two
/// boxes of text rather than a parsed [`OverrideTarget`].
///
/// The target is kept as the user's text so a half-typed `multipart.` is a
/// state the form can be *in*. Parsing happens on the way out
/// ([`override_items`]), and [`override_target_valid`] is what the form paints
/// red in the meantime.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OverrideRow {
    /// `url`, `body`, `multipart.document`, `header.X-Trace`, …
    pub target: String,
    pub value: String,
}

/// The editable rows for the overrides in `using`, in clause order.
///
/// Both front-ends' node forms build these, so which items count as overrides
/// — everything that isn't a `Require` — is decided once.
pub fn override_rows(using: &[UsingItem]) -> Vec<OverrideRow> {
    using
        .iter()
        .filter_map(|i| match i {
            UsingItem::Override { target, value } => Some(OverrideRow {
                target: target.text(),
                value: value.clone(),
            }),
            UsingItem::Require(_) => None,
        })
        .collect()
}

/// Whether a target box holds something [`OverrideTarget::parse`] accepts. An
/// empty box is "not filled in yet" rather than wrong, so it reads as valid —
/// the form shows an error for text that can never work, not for text that
/// isn't finished.
pub fn override_target_valid(target: &str) -> bool {
    target.trim().is_empty() || OverrideTarget::parse(target.trim()).is_some()
}

/// The clause items for a form's override rows.
///
/// Rows with an unparseable or empty target are dropped: an override that names
/// no part of the request has nothing to patch, and writing it out would
/// produce a flow that doesn't parse. Front-ends must not let a row reach here
/// in that state without having said so — see [`override_target_valid`].
pub fn override_items(rows: &[OverrideRow]) -> Vec<UsingItem> {
    rows.iter()
        .filter_map(|r| {
            OverrideTarget::parse(r.target.trim()).map(|target| UsingItem::Override {
                target,
                value: r.value.clone(),
            })
        })
        .collect()
}

/// The `USING(…)` clause for a checklist: the ticked parameters as
/// requirements, then every item the checklist has no row for — the per-call
/// overrides — verbatim.
///
/// This canonicalises the order, requirements first, which is the only thing
/// about the clause a node form rewrites. A clause written the other way round
/// in the source view means exactly the same thing, and grouping the
/// requirements is what makes the checklist and the text agree on sight.
pub fn using_items(params: &[ParamRow], carried: &[UsingItem]) -> Vec<UsingItem> {
    let mut out: Vec<UsingItem> = params
        .iter()
        .filter(|p| p.required)
        .map(|p| UsingItem::Require(p.name.clone()))
        .collect();
    out.extend(
        carried
            .iter()
            .filter(|i| !matches!(i, UsingItem::Require(_)))
            .cloned(),
    );
    out
}

// ---------------------------------------------------------------------------
// The flattened, navigable outline
// ---------------------------------------------------------------------------

/// One displayed row of the node outline. A leaf statement is one row; a `FOR`
/// loop is a header row (`kind = LoopHead`) whose body nests one level deeper
/// and closes with a synthetic `END` row (`kind = LoopEnd`). Row 0 is always
/// the synthetic `Begin` root.
pub(crate) struct NodeRow {
    /// Indentation depth (0 = top level; the `Begin` root is also 0).
    pub(crate) depth: usize,
    /// The rendered label (the node's [`FlowNode::label`]; `""` for the
    /// synthetic rows, which get their text from `kind`).
    pub(crate) label: String,
    pub(crate) kind: RowKind,
    /// Path to the addressed AST node: a sequence of indices, each stepping
    /// into a loop body. Empty for `Begin`; for `LoopEnd` it is the `FOR`
    /// node's own path (same as its `LoopHead`).
    pub(crate) path: Vec<usize>,
    /// For a `REQUEST` / `REPORT REQUEST` row, whether the referenced request
    /// name resolves in the bound collection (green) or not (amber). `None`
    /// for every other row.
    pub(crate) req_ok: Option<bool>,
}

/// The role of a [`NodeRow`] — drives rendering and where an insert lands.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum RowKind {
    /// The synthetic root; inserting here adds the first top-level node.
    Begin,
    /// A leaf statement (assignment, request, report, list).
    Leaf,
    /// The `FOR … IN …` opener of a loop.
    LoopHead,
    /// The synthetic `END` closing a loop.
    LoopEnd,
    /// A `# …` comment line. A node like any other — it can be selected, moved
    /// and deleted — but it is drawn dimmed, because it isn't a statement.
    Comment,
    /// One field of an expanded `REPORT REQUEST … WITH … END` block, at this
    /// index into the request's `with` list. `path` addresses the *request*, not
    /// the field, so anything acting on a `WITH` row must branch on this kind
    /// rather than treating the path as a node to delete or move.
    WithField(usize),
    /// A `# …` comment line *inside* an expanded `WITH` block, at this index
    /// into the request's `with` list. Separate from [`RowKind::WithField`] so
    /// it can be drawn dimmed and kept out of the field editor, but it indexes
    /// the same list, so deleting and reordering treat the two alike.
    WithComment(usize),
    /// The "add a field" affordance at the end of an expanded `WITH` block.
    WithAdd,
    /// The synthetic `END` closing an expanded `WITH` block.
    WithEnd,
}

impl RowKind {
    /// Whether this row belongs to an expanded `WITH` block rather than being a
    /// flow node in its own right.
    pub(crate) fn is_with(self) -> bool {
        matches!(
            self,
            RowKind::WithField(_) | RowKind::WithComment(_) | RowKind::WithAdd | RowKind::WithEnd
        )
    }

    /// The index into the request's `with` list this row stands for, for the
    /// rows that address one item (a field or a comment).
    pub(crate) fn with_item(self) -> Option<usize> {
        match self {
            RowKind::WithField(i) | RowKind::WithComment(i) => Some(i),
            _ => None,
        }
    }
}

/// Flatten a flow into the display rows, tagging request rows with whether they
/// resolve (via `resolves`). Row 0 is the `Begin` root.
///
/// `WITH` blocks stay collapsed to a single `… WITH …` row — see
/// [`flatten_expanded`] for the form that opens them up.
pub(crate) fn flatten(flow: &ReportFlow, resolves: &impl Fn(&str) -> bool) -> Vec<NodeRow> {
    flatten_expanded(flow, resolves, false)
}

/// As [`flatten`], but with `expand_with` a `REPORT REQUEST … WITH` block is
/// opened out: the request row, one [`RowKind::WithField`] row per field, an
/// [`RowKind::WithAdd`] row, and a closing [`RowKind::WithEnd`].
///
/// It is opt-in because the two front-ends show `WITH` differently — the GUI
/// draws each field as a chip on the request's own row, so expanding would
/// double it up, while the TUI outline has no room for chips and needs the rows.
pub(crate) fn flatten_expanded(
    flow: &ReportFlow,
    resolves: &impl Fn(&str) -> bool,
    expand_with: bool,
) -> Vec<NodeRow> {
    let mut rows = vec![NodeRow {
        depth: 0,
        label: String::new(),
        kind: RowKind::Begin,
        path: Vec::new(),
        req_ok: None,
    }];
    let mut prefix = Vec::new();
    push_nodes(
        &flow.nodes,
        &mut prefix,
        1,
        resolves,
        expand_with,
        &mut rows,
    );
    rows
}

/// The `WITH` fields of a report-request node, or `None` for anything else.
pub(crate) fn node_with_items(node: &FlowNode) -> Option<&[WithItem]> {
    match node {
        FlowNode::Report(ReportStmt::Request { with, .. }) => Some(with),
        _ => None,
    }
}

/// The row label for one `WITH` item — the same text it is written with in
/// source, so the outline and the source view read alike.
pub(crate) fn with_item_label(item: &WithItem) -> String {
    crate::report::flow::with_item_text(item)
}

fn push_nodes(
    nodes: &[FlowNode],
    prefix: &mut Vec<usize>,
    depth: usize,
    resolves: &impl Fn(&str) -> bool,
    expand_with: bool,
    rows: &mut Vec<NodeRow>,
) {
    for (i, node) in nodes.iter().enumerate() {
        prefix.push(i);
        let req_ok = node.request_name().map(resolves);
        if let Some(body) = loop_body(node) {
            rows.push(NodeRow {
                depth,
                label: node.label(),
                kind: RowKind::LoopHead,
                path: prefix.clone(),
                req_ok,
            });
            push_nodes(body, prefix, depth + 1, resolves, expand_with, rows);
            rows.push(NodeRow {
                depth,
                label: String::new(),
                kind: RowKind::LoopEnd,
                path: prefix.clone(),
                req_ok: None,
            });
        } else {
            let with = expand_with
                .then(|| node_with_items(node))
                .flatten()
                .filter(|w| !w.is_empty());
            rows.push(NodeRow {
                depth,
                // Expanded, the head loses its "…" placeholder: the fields it
                // stood for are the rows immediately below.
                label: match with {
                    Some(_) => format!("{} WITH", node.header_line()),
                    None => node.label(),
                },
                kind: match node {
                    FlowNode::Comment(_) => RowKind::Comment,
                    _ => RowKind::Leaf,
                },
                path: prefix.clone(),
                req_ok,
            });
            if let Some(with) = with {
                for (wi, item) in with.iter().enumerate() {
                    rows.push(NodeRow {
                        depth: depth + 1,
                        label: with_item_label(item),
                        kind: match item {
                            WithItem::Comment(_) => RowKind::WithComment(wi),
                            _ => RowKind::WithField(wi),
                        },
                        path: prefix.clone(),
                        req_ok: None,
                    });
                }
                rows.push(NodeRow {
                    depth: depth + 1,
                    label: String::new(),
                    kind: RowKind::WithAdd,
                    path: prefix.clone(),
                    req_ok: None,
                });
                rows.push(NodeRow {
                    depth,
                    label: String::new(),
                    kind: RowKind::WithEnd,
                    path: prefix.clone(),
                    req_ok: None,
                });
            }
        }
        prefix.pop();
    }
}

// ---------------------------------------------------------------------------
// AST navigation & mutation
// ---------------------------------------------------------------------------

/// Where a newly inserted node lands: the containing loop body (`parent`, empty
/// = top level) and the index within it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct InsertPos {
    pub(crate) parent: Vec<usize>,
    pub(crate) index: usize,
}

/// The insertion point implied by the selected row: after a leaf, as the first
/// child of a `FOR` header, after the loop when on its `END`, or at the very
/// front when on `Begin`. So put the cursor on a `FOR` header and insert to go
/// *inside* it; on its `END` to go *after* it.
pub(crate) fn insert_pos_after(rows: &[NodeRow], sel: usize) -> InsertPos {
    let Some(row) = rows.get(sel) else {
        return InsertPos {
            parent: Vec::new(),
            index: 0,
        };
    };
    match row.kind {
        RowKind::Begin => InsertPos {
            parent: Vec::new(),
            index: 0,
        },
        RowKind::LoopHead => InsertPos {
            parent: row.path.clone(),
            index: 0,
        },
        // A `WITH` row isn't a flow node, but a flow insert asked for from one
        // still has to land *somewhere* sensible: after the request that owns
        // the block, which is where the whole `WITH … END` ends on screen.
        RowKind::Leaf
        | RowKind::Comment
        | RowKind::LoopEnd
        | RowKind::WithField(_)
        | RowKind::WithComment(_)
        | RowKind::WithAdd
        | RowKind::WithEnd => {
            let (last, rest) = row.path.split_last().unwrap_or((&0, &[]));
            InsertPos {
                parent: rest.to_vec(),
                index: last + 1,
            }
        }
    }
}

fn loop_body(node: &FlowNode) -> Option<&Vec<FlowNode>> {
    match node {
        FlowNode::ForEach { body, .. }
        | FlowNode::ForEnvs { body, .. }
        | FlowNode::Graph { body, .. } => Some(body),
        _ => None,
    }
}

/// The source directory of a `FOR … IN FILES/FOLDERS` node, or `None` for any
/// other node (only these two producers carry a browsable folder).
pub(crate) fn loop_producer_dir(node: &FlowNode) -> Option<&str> {
    match node {
        FlowNode::ForEach {
            producer: Producer::Files { dir, .. } | Producer::Folders { dir, .. },
            ..
        } => Some(dir),
        _ => None,
    }
}

/// Mutable counterpart to [`loop_producer_dir`].
pub(crate) fn loop_producer_dir_mut(node: &mut FlowNode) -> Option<&mut String> {
    match node {
        FlowNode::ForEach {
            producer: Producer::Files { dir, .. } | Producer::Folders { dir, .. },
            ..
        } => Some(dir),
        _ => None,
    }
}

/// Mutable reference to the body Vec addressed by `parent` (empty = top level).
fn body_at_mut<'a>(flow: &'a mut ReportFlow, parent: &[usize]) -> Option<&'a mut Vec<FlowNode>> {
    let mut body = &mut flow.nodes;
    for &i in parent {
        body = body.get_mut(i)?.body_mut()?;
    }
    Some(body)
}

pub(crate) fn node_at<'a>(flow: &'a ReportFlow, path: &[usize]) -> Option<&'a FlowNode> {
    let (last, rest) = path.split_last()?;
    let mut body = &flow.nodes;
    for &i in rest {
        body = loop_body(body.get(i)?)?;
    }
    body.get(*last)
}

pub(crate) fn node_at_mut<'a>(
    flow: &'a mut ReportFlow,
    path: &[usize],
) -> Option<&'a mut FlowNode> {
    let (last, rest) = path.split_last()?;
    let body = body_at_mut(flow, rest)?;
    body.get_mut(*last)
}

pub(crate) fn insert_node(flow: &mut ReportFlow, pos: &InsertPos, node: FlowNode) {
    if let Some(body) = body_at_mut(flow, &pos.parent) {
        let idx = pos.index.min(body.len());
        body.insert(idx, node);
    }
}

pub(crate) fn remove_node(flow: &mut ReportFlow, path: &[usize]) -> bool {
    let Some((last, rest)) = path.split_last() else {
        return false;
    };
    if let Some(body) = body_at_mut(flow, rest)
        && *last < body.len()
    {
        body.remove(*last);
        return true;
    }
    false
}

/// Swap the node at `path` with its previous (`up`) / next sibling in the same
/// body. Returns the moved node's new path, or `None` at a boundary.
pub(crate) fn move_node(flow: &mut ReportFlow, path: &[usize], up: bool) -> Option<Vec<usize>> {
    let (last, rest) = path.split_last()?;
    let body = body_at_mut(flow, rest)?;
    let target = if up {
        last.checked_sub(1)?
    } else if last + 1 < body.len() {
        last + 1
    } else {
        return None;
    };
    body.swap(*last, target);
    let mut new_path = rest.to_vec();
    new_path.push(target);
    Some(new_path)
}

/// Replace the node at `path` with `new_node`, carrying the old loop body over
/// when both are loops (so editing a `FOR` header keeps its children).
pub(crate) fn replace_node(flow: &mut ReportFlow, path: &[usize], mut new_node: FlowNode) -> bool {
    let Some(slot) = node_at_mut(flow, path) else {
        return false;
    };
    let old_body = slot.body_mut().map(std::mem::take);
    if let (Some(ob), Some(nb)) = (old_body, new_node.body_mut()) {
        *nb = ob;
    }
    *slot = new_node;
    true
}

/// Parse one edited statement line back into a node. A loop needs a following
/// `END` to re-parse, so both a bare and an `END`-terminated form are tried
/// (loop-first when the original node was a loop). Returns `None` if the text
/// doesn't yield exactly one statement.
pub(crate) fn parse_one_node(text: &str, prefer_loop: bool) -> Option<FlowNode> {
    let t = text.trim();
    if t.is_empty() {
        return None;
    }
    let bare = format!("{t}\n");
    let looped = format!("{t}\nEND\n");
    let attempts = if prefer_loop {
        [looped, bare]
    } else {
        [bare, looped]
    };
    for wrap in attempts {
        if let Ok(flow) = parse_flow(&wrap)
            && flow.nodes.len() == 1
        {
            return flow.nodes.into_iter().next();
        }
    }
    None
}

// ---------------------------------------------------------------------------
// The insert palette's node kinds
// ---------------------------------------------------------------------------

/// The kinds of node the insert palette offers, in display order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum NodeKind {
    Request,
    ReportRequest,
    ReportVar,
    ReportComputed,
    Assign,
    ForFiles,
    ForFolders,
    ForEnvs,
    List,
}

impl NodeKind {
    pub(crate) const ALL: [NodeKind; 9] = [
        NodeKind::Request,
        NodeKind::ReportRequest,
        NodeKind::ReportVar,
        NodeKind::ReportComputed,
        NodeKind::Assign,
        NodeKind::ForFiles,
        NodeKind::ForFolders,
        NodeKind::ForEnvs,
        NodeKind::List,
    ];

    /// The palette label for this kind.
    pub(crate) fn label(self, s: &Strings) -> &'static str {
        match self {
            NodeKind::Request => s.node_kind_request,
            NodeKind::ReportRequest => s.node_kind_report_request,
            NodeKind::ReportVar => s.node_kind_report_var,
            NodeKind::ReportComputed => s.node_kind_report_computed,
            NodeKind::Assign => s.node_kind_assign,
            NodeKind::ForFiles => s.node_kind_for_files,
            NodeKind::ForFolders => s.node_kind_for_folders,
            NodeKind::ForEnvs => s.node_kind_for_envs,
            NodeKind::List => s.node_kind_list,
        }
    }

    /// Whether creating this kind needs a request name from the picker.
    pub(crate) fn needs_request(self) -> bool {
        matches!(self, NodeKind::Request | NodeKind::ReportRequest)
    }

    /// A template node with placeholder fields (for the non-request kinds); the
    /// user then fills the fields in via the "edit as line" prompt.
    pub(crate) fn template(self) -> Option<FlowNode> {
        Some(match self {
            NodeKind::Request | NodeKind::ReportRequest => return None,
            NodeKind::ReportVar => FlowNode::Report(ReportStmt::Vars(vec!["VAR".into()])),
            NodeKind::ReportComputed => FlowNode::Report(ReportStmt::Computed {
                // A placeholder computed column the user edits via its wizard.
                // The template must be a non-empty string and it must carry an
                // AS name, or `REPORT "…"` won't re-parse (kicking the user out
                // of the node editor).
                template: "value".into(),
                name: "column".into(),
                stats: Vec::new(),
                image: None,
                truth: None,
                detail: false,
            }),
            NodeKind::Assign => FlowNode::Assign {
                key: "NAME".into(),
                value: String::new(),
            },
            NodeKind::ForFiles => FlowNode::ForEach {
                pattern: Pattern::single("FILE"),
                producer: Producer::Files {
                    dir: String::new(),
                    glob: None,
                },
                body: Vec::new(),
                parallel: None,
            },
            NodeKind::ForFolders => FlowNode::ForEach {
                pattern: Pattern::single("FOLDER"),
                producer: Producer::Folders {
                    dir: String::new(),
                    glob: None,
                    roles: Vec::new(),
                },
                body: Vec::new(),
                parallel: None,
            },
            NodeKind::ForEnvs => FlowNode::ForEnvs {
                var: "TARGET".into(),
                // A placeholder BASELINE/COMPARISON pair — the comparison is the
                // whole point of an `ENVS` loop, so the inserted template shows
                // the shape to fill in. An empty clause would serialize to a
                // bare `FOR TARGET IN ENVS ` which doesn't re-parse (it would
                // kick the user out of the node editor). The names are just
                // placeholders the user replaces with real loaded environments.
                clause: EnvClause::Roles {
                    baseline: vec![RoleRef::Env("baseline".into())],
                    comparisons: vec![RoleRef::Env("candidate".into())],
                    baseline_show: Vec::new(),
                },
                body: Vec::new(),
                parallel: None,
            },
            NodeKind::List => FlowNode::ListDecl {
                name: "ITEMS".into(),
                producer: Producer::List(Vec::new()),
            },
        })
    }
}

/// A `REQUEST <name>` / `REPORT REQUEST <name>` node with the chosen name.
pub(crate) fn request_node(name: &str, report: bool) -> FlowNode {
    if report {
        FlowNode::Report(ReportStmt::Request {
            name: name.to_string(),
            alias: None,
            depends: Vec::new(),
            using: Vec::new(),
            response_fmt: None,
            show: Vec::new(),
            hide: Vec::new(),
            with: Vec::new(),
        })
    } else {
        FlowNode::Request {
            name: name.to_string(),
            alias: None,
            depends: Vec::new(),
            using: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Compositional modifiers (the drag-on chips: REPORT / PARALLEL / WITH / AS)
// ---------------------------------------------------------------------------

/// A modifier that a compositional block editor drags *onto* an existing node
/// to attach it. Unlike a [`NodeKind`] (a whole new statement), a modifier
/// transforms the node it lands on: `REPORT` wraps a `REQUEST`/marks a report,
/// `PARALLEL` marks a loop concurrent, `WITH` adds an ad-hoc field to a report
/// request, and `AS` names/aliases a report column.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Modifier {
    Report,
    Parallel,
    With,
    As,
    Response,
    Show,
    Hide,
    /// `STATISTICS(…)` — summary rows for a named report column.
    Statistics,
}

impl Modifier {
    pub(crate) const ALL: [Modifier; 8] = [
        Modifier::Report,
        Modifier::Parallel,
        Modifier::With,
        Modifier::As,
        Modifier::Response,
        Modifier::Show,
        Modifier::Hide,
        Modifier::Statistics,
    ];

    /// The palette label for this modifier.
    pub(crate) fn label(self, s: &Strings) -> &'static str {
        match self {
            Modifier::Report => s.node_mod_report,
            Modifier::Parallel => s.node_mod_parallel,
            Modifier::With => s.node_mod_with,
            Modifier::As => s.node_mod_as,
            Modifier::Response => s.node_mod_response,
            Modifier::Show => s.node_mod_show,
            Modifier::Hide => s.node_mod_hide,
            Modifier::Statistics => s.node_mod_statistics,
        }
    }

    /// Whether this modifier can be attached to `node` (drives both the drop
    /// highlight and whether a release does anything). A modifier that is
    /// already present, or nonsensical for the node, is not applicable.
    pub(crate) fn applies_to(self, node: &FlowNode) -> bool {
        match self {
            // REPORT wraps a plain (send-only) request into a reported one, or
            // reports the variable a `SET` assignment defines (by inserting a
            // sibling `REPORT (VAR)` after it — see `report_assignment`).
            Modifier::Report => {
                matches!(node, FlowNode::Request { .. } | FlowNode::Assign { .. })
            }
            // PARALLEL marks a not-yet-parallel loop concurrent.
            Modifier::Parallel => matches!(
                node,
                FlowNode::ForEach { parallel: None, .. } | FlowNode::ForEnvs { parallel: None, .. }
            ),
            // WITH adds an ad-hoc field to a report request.
            Modifier::With => matches!(node, FlowNode::Report(ReportStmt::Request { .. })),
            // AS names a report column: an as-less report request, or a
            // single-variable `REPORT <var>` (which becomes `REPORT <var> AS …`).
            Modifier::As => match node {
                FlowNode::Report(ReportStmt::Request { alias, .. }) => alias.is_none(),
                FlowNode::Report(ReportStmt::Vars(vars)) => vars.len() == 1,
                _ => false,
            },
            // RESPONSE / SHOW / HIDE all decorate a report request, and only
            // when it doesn't already carry that clause (so the drop reads as
            // "add it" and never silently overwrites an existing one).
            Modifier::Response => matches!(
                node,
                FlowNode::Report(ReportStmt::Request {
                    response_fmt: None,
                    ..
                })
            ),
            Modifier::Show => {
                matches!(node, FlowNode::Report(ReportStmt::Request { show, .. }) if show.is_empty())
            }
            Modifier::Hide => {
                matches!(node, FlowNode::Report(ReportStmt::Request { hide, .. }) if hide.is_empty())
            }
            // STATISTICS summarises a *named* report column, so it needs an
            // already-named one: `REPORT <var> AS <name>` or a computed column.
            // A bare `REPORT (A, B)` has no single column to summarise (attach
            // AS first), and a request's own columns are named by its WITH
            // fields, which carry their own STATISTICS.
            Modifier::Statistics => match node {
                FlowNode::Report(ReportStmt::VarAs { stats, .. })
                | FlowNode::Report(ReportStmt::Computed { stats, .. }) => stats.is_empty(),
                _ => false,
            },
        }
    }

    /// Why this modifier refuses to attach to `node`, or `None` when it does
    /// attach. A rejected drop used to be silent — the chip simply sprang back
    /// with no hint that the *block*, not the aim, was the problem. The two
    /// answers a user needs are "wrong kind of block" and "it's already there",
    /// so the reasons split along that line rather than restating `applies_to`.
    pub(crate) fn reject_reason(self, node: &FlowNode, s: &Strings) -> Option<&'static str> {
        if self.applies_to(node) {
            return None;
        }
        // A reported request is the target of most modifiers; when the block is
        // one, the only remaining reason is that the clause is already present.
        let reported = matches!(node, FlowNode::Report(ReportStmt::Request { .. }));
        Some(match self {
            // Any `REPORT …` statement — a reported request, a reported
            // variable, a computed column — already *is* the thing REPORT
            // adds, so the honest answer is "already there" rather than a
            // lecture about where REPORT goes.
            Modifier::Report => {
                if matches!(node, FlowNode::Report(_)) {
                    s.mod_reject_present
                } else {
                    s.mod_reject_report
                }
            }
            Modifier::Parallel => {
                if matches!(node, FlowNode::ForEach { .. } | FlowNode::ForEnvs { .. }) {
                    s.mod_reject_present
                } else {
                    s.mod_reject_parallel
                }
            }
            Modifier::With => s.mod_reject_with,
            Modifier::As => {
                if reported || matches!(node, FlowNode::Report(ReportStmt::Vars(v)) if v.len() == 1)
                {
                    s.mod_reject_present
                } else {
                    s.mod_reject_as
                }
            }
            Modifier::Response | Modifier::Show | Modifier::Hide => {
                if reported {
                    s.mod_reject_present
                } else {
                    s.mod_reject_request_only
                }
            }
            Modifier::Statistics => {
                if matches!(
                    node,
                    FlowNode::Report(ReportStmt::VarAs { .. })
                        | FlowNode::Report(ReportStmt::Computed { .. })
                ) {
                    s.mod_reject_present
                } else {
                    s.mod_reject_statistics
                }
            }
        })
    }
}

/// Which attached modifier a detach (the chip's `×`) targets. `With` carries the
/// index of the field to drop, since a report request can hold several.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum DetachWhich {
    Report,
    Parallel,
    As,
    With(usize),
    /// The `RESPONSE RAW/PRETTY` override on a report request.
    Response,
    /// The `SHOW(…)` field selector on a report request.
    Show,
    /// The `HIDE(…)` field selector on a report request.
    Hide,
    /// The `SHOW(…)` clause hanging off an ENVS loop's `BASELINE`.
    BaselineShow,
    /// One `BASELINE`/`COMPARISON` role of an ENVS compare loop.
    Role {
        baseline: bool,
        index: usize,
    },
    /// The whole `WITH … END` block of a report request (its individual fields
    /// detach one at a time as [`DetachWhich::With`]).
    WithBlock,
    /// The `STATISTICS(…)` clause of a named report column.
    Statistics,
    /// The `IMAGE[(…)]` clause of a named report column.
    ///
    /// The three column clauses attach to a *column*, so these target the
    /// statement's own (`REPORT <var> AS …`, `REPORT "…" AS …`). A `WITH`
    /// field's clauses are written into its row's text alongside its
    /// `STATISTICS(…)` and are edited through the field's own wizard, exactly
    /// as that one is.
    Image,
    /// The `TRUTH "…"` clause of a named report column.
    Truth,
    /// The `DETAIL` flag of a named report column.
    Detail,
}

/// Every variable name in scope at `path` — the candidates a `REPORT <var>`
/// column can name.
///
/// Walks the flow down `path`, collecting what is bound *before* the node at
/// each level: assignments and the captures of requests already sent, plus the
/// binders of every enclosing loop (its pattern, and a `FOLDERS` loop's role
/// names). `entries` is the bound collection, used to resolve each request's
/// `[Captures]`; pass an empty slice when the collection is unknown and the
/// list simply won't include captures.
///
/// This is deliberately the *statically knowable* set: a `TUPLES FROM` or
/// `ZIP` loop can bind names that only exist at run time, and an environment
/// contributes its own keys, so the list is a helpful shortlist rather than an
/// exhaustive one. Both front-ends offer it alongside a free-text row for
/// exactly that reason.
pub(crate) fn vars_in_scope(
    flow: &ReportFlow,
    path: &[usize],
    entries: &[crate::hurl::HurlEntry],
) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let push = |name: &str, out: &mut Vec<String>| {
        if !name.trim().is_empty() && !out.iter().any(|n| n == name) {
            out.push(name.to_string());
        }
    };
    let mut nodes: &[FlowNode] = &flow.nodes;
    for index in path {
        for node in nodes.iter().take(*index) {
            match node {
                FlowNode::Assign { key, .. } => push(key, &mut out),
                FlowNode::Request { name, .. }
                | FlowNode::Report(ReportStmt::Request { name, .. }) => {
                    if let Some(entry) = crate::report::run::resolve_title(entries, name) {
                        for (cap, _) in &entry.captures {
                            push(cap, &mut out);
                        }
                    }
                }
                _ => {}
            }
        }
        // Stepping *into* the loop at `index` brings its binders into scope for
        // everything below, including the node we're heading towards.
        let Some(parent) = nodes.get(*index) else {
            break;
        };
        match parent {
            FlowNode::ForEach {
                pattern,
                producer,
                body,
                ..
            } => {
                for name in pattern.named() {
                    push(name, &mut out);
                }
                if let Producer::Folders { roles, .. } = producer {
                    for role in roles {
                        push(&role.name, &mut out);
                    }
                }
                nodes = body;
            }
            FlowNode::ForEnvs { var, body, .. } => {
                push(var, &mut out);
                nodes = body;
            }
            // The path claims to step into a loop but the node isn't one, so
            // there is nothing further to walk.
            _ => break,
        }
    }
    out
}

/// The fields a `BASELINE(…) SHOW(…)` can name, ticked where the clause already
/// names them.
///
/// A `SHOW` on a baseline selects from what the loop's *body* reports, so the
/// candidates are gathered by walking the body for reported requests and asking
/// the bound collection what each one emits — the same canonical order the
/// request form uses (intrinsics first, then the request's own `[Reports]`
/// fields). Anything already named by the clause is appended even if no request
/// claims it, so opening and applying the form can never silently drop a field
/// the user wrote by hand.
pub(crate) fn baseline_show_choices(
    entries: &[crate::hurl::HurlEntry],
    body: &[FlowNode],
    selected: &[ShowField],
) -> Vec<(String, bool)> {
    let mut names: Vec<String> = Vec::new();
    let push = |n: &str, names: &mut Vec<String>| {
        if !n.trim().is_empty() && !names.iter().any(|x| x == n) {
            names.push(n.to_string());
        }
    };
    for f in crate::report::run::INTRINSIC_FIELDS {
        push(f, &mut names);
    }
    for req in reported_requests(body) {
        if let Some(entry) = crate::report::run::resolve_title(entries, &req) {
            for (f, _) in &entry.reports {
                push(f, &mut names);
            }
        }
    }
    for f in selected {
        push(f.name(), &mut names);
    }
    names
        .iter()
        .map(|n| (n.clone(), selected.iter().any(|sel| sel.name() == n)))
        .collect()
}

/// Every request name reported anywhere beneath `body`, nested loops included.
pub(crate) fn reported_requests(body: &[FlowNode]) -> Vec<String> {
    let mut out = Vec::new();
    fn walk(nodes: &[FlowNode], out: &mut Vec<String>) {
        for n in nodes {
            match n {
                // A bare `REQUEST x` sends but emits nothing, so it has no
                // fields to offer; only `REPORT REQUEST x` does.
                FlowNode::Report(ReportStmt::Request { name, .. }) => out.push(name.clone()),
                FlowNode::ForEnvs { body, .. }
                | FlowNode::ForEach { body, .. }
                | FlowNode::Graph { body, .. } => walk(body, out),
                _ => {}
            }
        }
    }
    walk(body, &mut out);
    out
}

/// Attach `m` to the node at `path` (see [`Modifier::applies_to`]). No-op when
/// the modifier does not apply. Returns whether anything changed.
pub(crate) fn attach_modifier(flow: &mut ReportFlow, path: &[usize], m: Modifier) -> bool {
    match node_at_mut(flow, path) {
        Some(node) => attach_to_node(node, m),
        None => false,
    }
}

/// The body of [`attach_modifier`], on an already-resolved node. Split out so a
/// caller can *rehearse* a drop on a throwaway clone — which is how the block
/// editor previews where a dragged modifier will land without the preview ever
/// being able to disagree with the real thing.
pub(crate) fn attach_to_node(node: &mut FlowNode, m: Modifier) -> bool {
    if !m.applies_to(node) {
        return false;
    }
    match m {
        Modifier::Report => {
            if let FlowNode::Request {
                name,
                alias,
                depends,
                using,
            } = node
            {
                let name = std::mem::take(name);
                // The step name survives the upgrade too: it is this
                // statement's identity, not a property of being reported, and
                // dropping it would silently rename the step.
                let alias = alias.take();
                // The declared edges belong to the step, which is the same step
                // before and after: reporting it changes what comes out, never
                // when it runs.
                let depends = std::mem::take(depends);
                // See `CarriedMod::attach_to`: the clause belongs to the send.
                let using = std::mem::take(using);
                *node = FlowNode::Report(ReportStmt::Request {
                    name,
                    alias,
                    depends,
                    using,
                    response_fmt: None,
                    show: Vec::new(),
                    hide: Vec::new(),
                    with: Vec::new(),
                });
            }
        }
        Modifier::Parallel => match node {
            FlowNode::ForEach { parallel, .. } | FlowNode::ForEnvs { parallel, .. } => {
                *parallel = Some(ParallelSpec::default());
            }
            _ => {}
        },
        Modifier::With => {
            if let FlowNode::Report(ReportStmt::Request { with, .. }) = node {
                with.push(WithItem::Field {
                    name: "field".into(),
                    query: "HttpStatus".into(),
                    stats: Vec::new(),
                    image: None,
                    truth: None,
                    detail: false,
                });
            }
        }
        Modifier::As => match node {
            FlowNode::Report(ReportStmt::Request { alias, .. }) => {
                *alias = Some("alias".into());
            }
            FlowNode::Report(ReportStmt::Vars(vars)) if vars.len() == 1 => {
                let var = vars.remove(0);
                *node = FlowNode::Report(ReportStmt::VarAs {
                    var,
                    name: "name".into(),
                    stats: Vec::new(),
                    image: None,
                    truth: None,
                    detail: false,
                });
            }
            _ => {}
        },
        // RESPONSE / SHOW / HIDE seed a sensible default (PRETTY, and the first
        // intrinsic field) that the user then refines in the request wizard.
        Modifier::Response => {
            if let FlowNode::Report(ReportStmt::Request { response_fmt, .. }) = node {
                *response_fmt = Some(ResponseFmt::Pretty);
            }
        }
        Modifier::Show => {
            if let FlowNode::Report(ReportStmt::Request { show, .. }) = node
                && show.is_empty()
            {
                *show = vec!["HttpStatus".into()];
            }
        }
        Modifier::Hide => {
            if let FlowNode::Report(ReportStmt::Request { hide, .. }) = node
                && hide.is_empty()
            {
                *hide = vec!["HttpStatus".into()];
            }
        }
        // COUNT is the one statistic that means something for every column
        // (text included), so it is the safe seed; the wizard refines it.
        Modifier::Statistics => match node {
            FlowNode::Report(ReportStmt::VarAs { stats, .. })
            | FlowNode::Report(ReportStmt::Computed { stats, .. }) => {
                *stats = vec![StatKind::Count];
            }
            _ => {}
        },
    }
    true
}

/// Attach `STATISTICS(COUNT)` to the `WITH` field at `index` of the report
/// request at `path`, returning whether anything changed.
///
/// A `WITH` field is a report column in its own right — it has a name, and the
/// grammar lets it carry its own `STATISTICS(…)` — but it is not a `FlowNode`,
/// so [`attach_modifier`] (which addresses nodes by path) can't reach it. That
/// left the block editor able to *show* a field's `STATISTICS` while giving no
/// way to add one: the clause bounced off the `WITH` row, and dropping it on the
/// request line above attaches to nothing, because a request's columns are named
/// by its fields rather than by the request.
///
/// `COUNT` is the seed for the same reason it is in [`attach_to_node`]: it is
/// the one statistic that means something for a text column as well as a numeric
/// one. The field wizard refines it.
pub(crate) fn attach_with_stats(flow: &mut ReportFlow, path: &[usize], index: usize) -> bool {
    let Some(FlowNode::Report(ReportStmt::Request { with, .. })) = node_at_mut(flow, path) else {
        return false;
    };
    match with.get_mut(index) {
        Some(WithItem::Field { stats, .. }) if stats.is_empty() => {
            *stats = vec![StatKind::Count];
            true
        }
        _ => false,
    }
}

/// Whether [`attach_with_stats`] would do anything — i.e. whether the `WITH`
/// item at `index` is a named field that hasn't already got a `STATISTICS`
/// clause. Drives the drop highlight, so the preview and the drop agree.
pub(crate) fn with_stats_applies(with: &[WithItem], index: usize) -> bool {
    matches!(with.get(index), Some(WithItem::Field { stats, .. }) if stats.is_empty())
}

/// Report the variable a `SET` assignment at `path` defines: insert a
/// `REPORT (KEY)` statement immediately after the assignment (which itself
/// stays, since it is what actually sets the variable), returning the new
/// statement's path. A no-op (`None`) when `path` is not an `Assign`. This is
/// what dropping the `REPORT` modifier onto a `VARIABLE` block does — unlike a
/// request (transformed in place), an assignment needs a *separate* report
/// line.
pub(crate) fn report_assignment(flow: &mut ReportFlow, path: &[usize]) -> Option<Vec<usize>> {
    let key = match node_at(flow, path)? {
        FlowNode::Assign { key, .. } => key.clone(),
        _ => return None,
    };
    let (last, rest) = path.split_last()?;
    let mut existing = rest.to_vec();
    existing.push(last + 1);
    // Idempotent: if a `REPORT (KEY)` line already immediately follows the
    // assignment, don't stack another duplicate column — just select it.
    if let Some(FlowNode::Report(ReportStmt::Vars(vars))) = node_at(flow, &existing)
        && vars.as_slice() == [key.clone()]
    {
        return Some(existing);
    }
    let pos = InsertPos {
        parent: rest.to_vec(),
        index: last + 1,
    };
    insert_node(flow, &pos, FlowNode::Report(ReportStmt::Vars(vec![key])));
    let mut new = rest.to_vec();
    new.push(last + 1);
    Some(new)
}

/// Rename the request the node at `path` references, in place — preserving all
/// of a report request's modifiers (`AS` alias, `WITH` fields, `RESPONSE` /
/// `SHOW` / `HIDE`). Works for both a plain `REQUEST` and a `REPORT REQUEST`.
/// Returns whether anything changed.
pub(crate) fn set_request_name(flow: &mut ReportFlow, path: &[usize], name: &str) -> bool {
    match node_at_mut(flow, path) {
        Some(FlowNode::Request { name: n, .. })
        | Some(FlowNode::Report(ReportStmt::Request { name: n, .. })) => {
            *n = name.to_string();
            true
        }
        _ => false,
    }
}

/// Set the environment name of one `BASELINE`/`COMPARISON` role reference of a
/// `FOR … IN ENVS` comparison loop at `path`. `baseline` selects the role list;
/// `index` is the position within that list. Only rewrites an `Env(…)` ref (a
/// `FILE(…)` snapshot ref is left unchanged). Returns whether anything changed.
pub(crate) fn set_env_role(
    flow: &mut ReportFlow,
    path: &[usize],
    baseline: bool,
    index: usize,
    name: &str,
) -> bool {
    let Some(FlowNode::ForEnvs {
        clause:
            EnvClause::Roles {
                baseline: b,
                comparisons: c,
                ..
            },
        ..
    }) = node_at_mut(flow, path)
    else {
        return false;
    };
    let list = if baseline { b } else { c };
    match list.get_mut(index) {
        Some(r @ RoleRef::Env(_)) => {
            *r = RoleRef::Env(name.to_string());
            true
        }
        _ => false,
    }
}

/// Set the `AS` alias/name of a reported node at `path`. For a `REPORT REQUEST`
/// the alias is optional, so an empty `text` clears it; for a `REPORT var AS …`
/// or computed column the name is required, so an empty `text` is rejected
/// (returns `false`, leaving the name untouched). Returns whether it changed.
pub(crate) fn set_report_alias(flow: &mut ReportFlow, path: &[usize], text: &str) -> bool {
    let t = text.trim();
    match node_at_mut(flow, path) {
        Some(FlowNode::Report(ReportStmt::Request { alias, .. })) => {
            *alias = (!t.is_empty()).then(|| t.to_string());
            true
        }
        Some(FlowNode::Report(ReportStmt::VarAs { name, .. }))
        | Some(FlowNode::Report(ReportStmt::Computed { name, .. })) => {
            if t.is_empty() {
                return false;
            }
            *name = t.to_string();
            true
        }
        _ => false,
    }
}

/// Set (or clear) the maximum concurrency of the `PARALLEL` modifier on the
/// loop at `path`. `degree: None` means "no explicit limit", which the runner
/// resolves to the prelude's `MAX_PARALLEL` (or the built-in default) — that is
/// the plain `PARALLEL` form. `Some(0)` is rejected, matching the parser, which
/// refuses `PARALLEL(0)` because a zero-wide pool could never run anything.
/// Returns `false` when the node isn't a loop, isn't marked parallel, or the
/// degree is invalid.
pub(crate) fn set_parallel_degree(
    flow: &mut ReportFlow,
    path: &[usize],
    degree: Option<u32>,
) -> bool {
    if degree == Some(0) {
        return false;
    }
    match node_at_mut(flow, path) {
        Some(FlowNode::ForEach { parallel, .. }) | Some(FlowNode::ForEnvs { parallel, .. }) => {
            match parallel {
                Some(spec) => {
                    spec.degree = degree;
                    true
                }
                // Setting a degree on a serial loop would silently make it
                // concurrent — the PARALLEL modifier has to be attached first.
                None => false,
            }
        }
        _ => false,
    }
}

/// Rename the loop variable of the `FOR` at `path` — the inline text box on the
/// loop chip.
///
/// Only a loop that binds a *single* named value can be renamed this way:
/// `FOR f IN FILES "."` and `FOR t IN ENVS …` both can, while a destructuring
/// pattern (`FOR name, url IN …`) or one with a `...` rest cannot, because the
/// chip has one box and there would be no saying which binder it meant. Those
/// keep to the wizard.
///
/// The name is checked against the parser's own identifier rule, so a box left
/// empty or filled with something like `my file` is rejected rather than
/// written out as text that would no longer parse. Returns whether it changed.
pub(crate) fn set_loop_var(flow: &mut ReportFlow, path: &[usize], text: &str) -> bool {
    let t = text.trim();
    if !crate::report::parser::is_ident(t) {
        return false;
    }
    match node_at_mut(flow, path) {
        Some(FlowNode::ForEach { pattern, .. }) => {
            if pattern.rest || pattern.binders.len() != 1 {
                return false;
            }
            match &mut pattern.binders[0] {
                Binder::Named(name) => {
                    if name == t {
                        return false;
                    }
                    *name = t.to_string();
                    true
                }
                // `_` discards the value; renaming it would be introducing a
                // binder, not editing one.
                Binder::Discard => false,
            }
        }
        Some(FlowNode::ForEnvs { var, .. }) => {
            if var == t {
                return false;
            }
            *var = t.to_string();
            true
        }
        _ => false,
    }
}

/// The folder/file a `FOR` loop draws from, when it is a single path the chip
/// can show a picker for: `FILES "dir"`, `FOLDERS "dir"` and `TUPLES FROM
/// "file"`. `None` for every other producer — a list literal, a `ZIP`/`CONCAT`
/// of several, or a named `LIST` have no one path to pick.
pub(crate) fn loop_dir(flow: &ReportFlow, path: &[usize]) -> Option<String> {
    match node_at(flow, path) {
        Some(FlowNode::ForEach { producer, .. }) => match producer {
            Producer::Files { dir, .. } | Producer::Folders { dir, .. } => Some(dir.clone()),
            Producer::Tuples { path } => Some(path.clone()),
            _ => None,
        },
        _ => None,
    }
}

/// Point the loop at `path` at a different folder/file — the chip's picker and
/// its inline path box.
///
/// Empty is rejected: a `FILES ""` reads as the process working directory,
/// which is never what clearing a box was meant to ask for. Returns whether it
/// changed.
pub(crate) fn set_loop_dir(flow: &mut ReportFlow, path: &[usize], text: &str) -> bool {
    let t = text.trim();
    if t.is_empty() {
        return false;
    }
    match node_at_mut(flow, path) {
        Some(FlowNode::ForEach { producer, .. }) => match producer {
            Producer::Files { dir, .. } | Producer::Folders { dir, .. } => {
                if dir == t {
                    return false;
                }
                *dir = t.to_string();
                true
            }
            Producer::Tuples { path } => {
                if path == t {
                    return false;
                }
                *path = t.to_string();
                true
            }
            _ => false,
        },
        _ => false,
    }
}

/// The declared default of the `PARAM` at `path`, and the kind of control it
/// asks for. `None` for any other node.
pub(crate) fn param_decl(
    flow: &ReportFlow,
    path: &[usize],
) -> Option<crate::report::flow::ParamDecl> {
    match node_at(flow, path) {
        Some(FlowNode::Param(p)) => Some(p.clone()),
        _ => None,
    }
}

/// Change the default value of the `PARAM` at `path` — what the block editor's
/// dropdown / picker writes.
///
/// Blank clears it back to "required", which is meaningful: a parameter with no
/// default is one the run settings open on, empty and flagged, rather than one
/// that quietly runs with the last value someone happened to type. Returns
/// whether anything changed.
pub(crate) fn set_param_default(flow: &mut ReportFlow, path: &[usize], text: &str) -> bool {
    let t = text.trim();
    let new = (!t.is_empty()).then(|| t.to_string());
    match node_at_mut(flow, path) {
        Some(FlowNode::Param(p)) => {
            if p.default == new {
                return false;
            }
            p.default = new;
            true
        }
        _ => false,
    }
}

/// Set (or clear, when `text` is blank) the `MATCH "glob"` of a `FILES` loop.
/// Clearing is meaningful here, unlike the folder: a `FILES` with no `MATCH`
/// simply takes every file.
pub(crate) fn set_loop_glob(flow: &mut ReportFlow, path: &[usize], text: &str) -> bool {
    let t = text.trim();
    match node_at_mut(flow, path) {
        Some(FlowNode::ForEach {
            producer: Producer::Files { glob, .. } | Producer::Folders { glob, .. },
            ..
        }) => {
            let next = (!t.is_empty()).then(|| t.to_string());
            if *glob == next {
                return false;
            }
            *glob = next;
            true
        }
        _ => false,
    }
}

// ---------------------------------------------------------------------------
// The report's header directives, as an editable list
// ---------------------------------------------------------------------------

/// A header directive as the editors present it: which of the `# key: value`
/// lines exist, how each one is edited, and whether it is worth showing when
/// unset.
///
/// Lives here rather than in either front-end because *both* editors offer the
/// same settings over the same directives, and when this table lived only in
/// the GUI the terminal UI silently fell behind it — it could bind a collection
/// and nothing else. One table, and a directive added to the language shows up
/// in both editors or neither.
pub(crate) struct HeaderSpec {
    pub(crate) key: &'static str,
    /// `true` for the directives worth showing even when unset (as a prompt),
    /// rather than hiding them behind the "add setting" menu.
    pub(crate) always_shown: bool,
    /// `true` when leaving this unset actually stops the report running, so the
    /// prompt is drawn in the error colour. Only `collection:` qualifies:
    /// everything else either has a working default (`output:` falls back to
    /// `csv`, `root:` to the report's folder) or is simply absent.
    pub(crate) required: bool,
    pub(crate) kind: HeaderKind,
    /// `true` when the directive may appear more than once (`collection:` for
    /// helper collections, `labels:` for label classes). The editors show one
    /// row per occurrence and offer an "add another" entry; every other
    /// directive has exactly one row.
    pub(crate) repeatable: bool,
}

/// How one header directive is edited.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum HeaderKind {
    /// Pick from the open collections.
    Collection,
    /// Pick from the loaded global environments.
    Environment,
    /// Pick one of the writers PaperTrail can produce.
    ///
    /// `# output:` names a *format*, never a filename — the runner derives the
    /// file from the report's own name (only the CLI's `-o` flag takes a path),
    /// and `output_extension_from_header` rejects anything that isn't one of
    /// [`crate::report::writer::OUTPUT_EXTENSIONS`]. So this is a closed list,
    /// and offering a free-text field with a file browser (as this first did)
    /// only invited values the report would refuse to run with.
    Format,
    /// A folder, typed or chosen with the file picker.
    Folder,
    /// A file, typed or chosen with the file picker.
    File,
    /// Free text (the `columns:` list).
    Text,
}

impl HeaderKind {
    /// Whether this directive's value is a filesystem path — the two that are
    /// get a file/folder browser as well as a text field.
    pub(crate) fn is_path(self) -> bool {
        matches!(self, HeaderKind::Folder | HeaderKind::File)
    }
}

/// Every header directive the editors offer, in the order they are shown.
pub(crate) fn header_specs() -> [HeaderSpec; 7] {
    [
        HeaderSpec {
            key: "collection",
            always_shown: true,
            required: true,
            kind: HeaderKind::Collection,
            repeatable: true,
        },
        HeaderSpec {
            key: "output",
            repeatable: false,
            always_shown: true,
            required: false,
            kind: HeaderKind::Format,
        },
        HeaderSpec {
            key: "environment",
            repeatable: false,
            always_shown: false,
            required: false,
            kind: HeaderKind::Environment,
        },
        HeaderSpec {
            key: "root",
            repeatable: false,
            always_shown: false,
            required: false,
            kind: HeaderKind::Folder,
        },
        HeaderSpec {
            key: "baseline",
            repeatable: false,
            always_shown: false,
            required: false,
            kind: HeaderKind::File,
        },
        HeaderSpec {
            key: "columns",
            always_shown: false,
            required: false,
            kind: HeaderKind::Text,
            repeatable: false,
        },
        // Ground truth's vocabulary: one line per label class, so it repeats.
        HeaderSpec {
            key: "labels",
            always_shown: false,
            required: false,
            kind: HeaderKind::Text,
            repeatable: true,
        },
    ]
}

/// The explanation of what one header directive does — the GUI's hover help and
/// the terminal UI's status line, from one place so the two say the same thing.
pub(crate) fn header_help(key: &str, s: &Strings) -> &'static str {
    match key {
        "collection" => s.chip_help_hdr_collection,
        "output" => s.chip_help_hdr_output,
        "environment" => s.chip_help_hdr_environment,
        "root" => s.chip_help_hdr_root,
        "baseline" => s.chip_help_hdr_baseline,
        "labels" => s.chip_help_hdr_labels,
        _ => s.chip_help_hdr_columns,
    }
}

/// The value a freshly-added optional directive starts at.
///
/// Always `?`, the "present but not filled in yet" sentinel every editor here
/// already understands (it renders as the unset prompt). It must not be the
/// empty string: [`set_header`] treats an empty value as *remove this
/// directive*, so an empty placeholder made picking a setting from the add menu
/// do nothing at all — which is exactly what `columns:` used to do.
pub(crate) const HEADER_PLACEHOLDER: &str = "?";

/// Whether a directive's stored value counts as "not filled in yet" — either
/// absent altogether or still holding the [`HEADER_PLACEHOLDER`] sentinel.
pub(crate) fn header_unset(value: &str) -> bool {
    value.is_empty() || value == HEADER_PLACEHOLDER
}

/// The `n`th (0-based) occurrence of a repeatable directive, as `set_header_nth`
/// and the editors index them.
fn nth_directive(flow: &ReportFlow, key: &str, n: usize) -> Option<usize> {
    flow.header
        .lines
        .iter()
        .enumerate()
        .filter(|(_, l)| matches!(l, HeaderLine::Directive { key: k, .. } if k.eq_ignore_ascii_case(key)))
        .map(|(i, _)| i)
        .nth(n)
}

/// Set, change or clear the `n`th occurrence of a repeatable directive.
///
/// Indexing matters because `# collection:` repeats: always editing the first
/// match would silently rewrite the primary collection when the user meant to
/// edit a helper. Clearing (`None`) removes that one line, so removing helper 1
/// of 3 leaves the other two alone.
///
/// Returns `true` when the header actually changed. A request to set an
/// occurrence that doesn't exist yet appends one, so `n == count` adds.
pub(crate) fn set_header_nth(
    flow: &mut ReportFlow,
    key: &str,
    n: usize,
    value: Option<&str>,
) -> bool {
    let value = value.map(str::trim).filter(|v| !v.is_empty());
    match (nth_directive(flow, key, n), value) {
        (Some(i), Some(v)) => {
            let HeaderLine::Directive { value: old, .. } = &mut flow.header.lines[i] else {
                return false;
            };
            if old == v {
                return false;
            }
            *old = v.to_string();
            true
        }
        (Some(i), None) => {
            flow.header.lines.remove(i);
            true
        }
        (None, Some(v)) => add_header(flow, key, v),
        (None, None) => false,
    }
}

/// Append another occurrence of a repeatable directive, after the last existing
/// directive so the header stays one block above any trailing comments.
pub(crate) fn add_header(flow: &mut ReportFlow, key: &str, value: &str) -> bool {
    let value = value.trim();
    if value.is_empty() {
        return false;
    }
    let at = flow
        .header
        .lines
        .iter()
        .rposition(|l| matches!(l, HeaderLine::Directive { .. }))
        .map_or(0, |i| i + 1);
    flow.header.lines.insert(
        at,
        HeaderLine::Directive {
            key: key.to_string(),
            value: value.to_string(),
        },
    );
    true
}

/// Append a new `WITH` field (a `name: query` column) to the report-request at
/// `path`, returning its index. A no-op (`None`) when the node is not a report
/// request.
pub(crate) fn add_with_field(
    flow: &mut ReportFlow,
    path: &[usize],
    name: &str,
    query: &str,
    stats: Vec<StatKind>,
) -> Option<usize> {
    if let Some(FlowNode::Report(ReportStmt::Request { with, .. })) = node_at_mut(flow, path) {
        with.push(WithItem::Field {
            name: name.to_string(),
            query: query.to_string(),
            stats,
            image: None,
            truth: None,
            detail: false,
        });
        Some(with.len() - 1)
    } else {
        None
    }
}

/// The editable state of a column's three trailing clauses — `TRUTH "…"`,
/// `IMAGE[(…)]` and `DETAIL`.
///
/// They attach to every named column form (`REPORT … AS`, a computed column and
/// a `WITH` field) in exactly the same way, so both front-ends' six forms share
/// this one model rather than each re-deriving when a blank height means "no
/// size" and when it means "no clause". Sizes are held as typed *text*, not as
/// numbers: a half-typed `11` must not momentarily rewrite the flow as a
/// 11-pixel picture, and a field the user has cleared has to stay cleared while
/// they think about it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct ClauseForm {
    /// The ground-truth template. Empty ⇒ no `TRUTH` clause.
    pub(crate) truth: String,
    /// The `DETAIL` placement flag.
    pub(crate) detail: bool,
    /// Whether the column carries an `IMAGE` clause at all. Held rather than
    /// derived from the sizes, because a bare `IMAGE` (no options) is a valid
    /// and common spelling — the sizes being empty cannot mean "off".
    pub(crate) image_on: bool,
    /// `FIT`: size to the cell instead of to a box.
    pub(crate) fit: bool,
    /// `HEIGHT`, as typed. Empty or unparseable ⇒ absent.
    pub(crate) height: String,
    /// `WIDTH`, as typed.
    pub(crate) width: String,
}

impl ClauseForm {
    /// The form state for a column that already carries these clauses.
    pub(crate) fn of(image: Option<ImageSpec>, truth: Option<&str>, detail: bool) -> Self {
        let px = |v: Option<u32>| v.map(|n| n.to_string()).unwrap_or_default();
        ClauseForm {
            truth: truth.unwrap_or_default().to_string(),
            detail,
            image_on: image.is_some(),
            fit: image.is_some_and(|i| i.fit),
            height: image.map(|i| px(i.height)).unwrap_or_default(),
            width: image.map(|i| px(i.width)).unwrap_or_default(),
        }
    }

    /// The `TRUTH` clause to write. Blank means *no clause*, so clearing the
    /// row removes it rather than writing an empty truth nothing can match.
    pub(crate) fn truth(&self) -> Option<String> {
        Some(self.truth.trim().to_string()).filter(|t| !t.is_empty())
    }

    /// The `IMAGE` clause to write.
    ///
    /// `FIT` wins over the sizes rather than being combined with them: the two
    /// answer the same question ("how big?") and a spec that says both is one
    /// the writers would have to arbitrate.
    pub(crate) fn image(&self) -> Option<ImageSpec> {
        if !self.image_on {
            return None;
        }
        if self.fit {
            return Some(ImageSpec {
                fit: true,
                ..Default::default()
            });
        }
        let px = |s: &String| s.trim().parse::<u32>().ok().filter(|n| *n > 0);
        Some(ImageSpec {
            height: px(&self.height),
            width: px(&self.width),
            fit: false,
        })
    }

    /// Flip the `IMAGE` clause on or off, keeping the size rows in step, the
    /// same way the `STATISTICS` toggle keeps its checkboxes in step: turning
    /// it off clears the sizes, so a hidden row can never still be
    /// contributing to the clause.
    pub(crate) fn toggle_image(&mut self) {
        self.image_on = !self.image_on;
        if !self.image_on {
            self.fit = false;
            self.height.clear();
            self.width.clear();
        }
    }

    /// Flip `FIT`, clearing the sizes it overrides so the rows never show a
    /// height that isn't going to be used.
    pub(crate) fn toggle_fit(&mut self) {
        self.fit = !self.fit;
        if self.fit {
            self.height.clear();
            self.width.clear();
        }
    }
}

/// Overwrite the `name`/`query` of the `WITH` *field* at `index` of the
/// report-request at `path`, along with its `STATISTICS(…)` and the three
/// column clauses. Returns whether it changed (`false` if the node/index is not
/// a `WITH` field).
pub(crate) fn set_with_field(
    flow: &mut ReportFlow,
    path: &[usize],
    index: usize,
    name: &str,
    query: &str,
    stats: Vec<StatKind>,
    clauses: &ClauseForm,
) -> bool {
    if let Some(FlowNode::Report(ReportStmt::Request { with, .. })) = node_at_mut(flow, path)
        && let Some(WithItem::Field {
            name: n,
            query: q,
            stats: st,
            image: im,
            truth: tr,
            detail: de,
        }) = with.get_mut(index)
    {
        *n = name.to_string();
        *q = query.to_string();
        *st = stats;
        *im = clauses.image();
        *tr = clauses.truth();
        *de = clauses.detail;
        true
    } else {
        false
    }
}
/// whole node should now be *removed* — detaching `REPORT` from a reported
/// variable/computed column leaves no valid statement behind (there is no bare
/// variable node), so the caller drops the row entirely.
pub(crate) fn detach_modifier(flow: &mut ReportFlow, path: &[usize], which: DetachWhich) -> bool {
    let Some(node) = node_at_mut(flow, path) else {
        return false;
    };
    detach_from_node(node, which)
}

/// Whether detaching `which` from `node` would leave a statement that still
/// stands on its own.
///
/// This is the rule the block editor uses to decide whether a chip can be
/// pulled out of a line by itself: a clause whose removal would take the whole
/// row with it (`REPORT` on a reported *column*, say — there is no statement
/// left without it) is load-bearing, so grabbing that chip moves the line
/// instead. Answered by probing the real detach on a throwaway clone, so the
/// two can never drift apart.
pub(crate) fn detach_leaves_statement(node: &FlowNode, which: DetachWhich) -> bool {
    !detach_from_node(&mut node.clone(), which)
}

/// A modifier lifted **off a node with the value it was carrying**, so that
/// dropping it somewhere else re-creates it as it was rather than as a fresh
/// default.
///
/// [`Modifier`] describes a modifier in the abstract — it is what the palette
/// hands out, and attaching it seeds a placeholder the user then fills in. That
/// is exactly wrong for a clause pulled off an existing line: dragging
/// `SHOW(Time, Status)` from one reported request to another has to bring
/// `Time, Status` along, or the gesture silently rewrites the user's work.
/// A `CarriedMod` is therefore the modifier *and its contents*.
#[derive(Clone, PartialEq, Debug)]
pub(crate) enum CarriedMod {
    Report,
    Parallel(Option<ParallelSpec>),
    As(String),
    /// One `WITH` field. A report request may hold several, so unlike the rest
    /// this one always has room at the destination.
    With(WithItem),
    Response(ResponseFmt),
    Show(Vec<ShowField>),
    Hide(Vec<String>),
    BaselineShow(Vec<ShowField>),
    Role {
        baseline: bool,
        role: RoleRef,
    },
    /// A whole `WITH … END` block.
    WithBlock(Vec<WithItem>),
    Statistics(Vec<StatKind>),
}

/// Read the value the modifier `which` holds on `node`, ready to be grafted
/// onto another node. `None` when `node` doesn't actually carry it.
pub(crate) fn carry_modifier(node: &FlowNode, which: DetachWhich) -> Option<CarriedMod> {
    Some(match (which, node) {
        (DetachWhich::Report, FlowNode::Report(_)) => CarriedMod::Report,
        (
            DetachWhich::Parallel,
            FlowNode::ForEach { parallel, .. } | FlowNode::ForEnvs { parallel, .. },
        ) => CarriedMod::Parallel(parallel.clone()),
        (DetachWhich::As, FlowNode::Report(ReportStmt::Request { alias, .. })) => {
            CarriedMod::As(alias.clone()?)
        }
        (DetachWhich::As, FlowNode::Report(ReportStmt::VarAs { name, .. })) => {
            CarriedMod::As(name.clone())
        }
        (DetachWhich::With(i), FlowNode::Report(ReportStmt::Request { with, .. })) => {
            CarriedMod::With(with.get(i)?.clone())
        }
        (DetachWhich::Response, FlowNode::Report(ReportStmt::Request { response_fmt, .. })) => {
            CarriedMod::Response(*response_fmt.as_ref()?)
        }
        (DetachWhich::Show, FlowNode::Report(ReportStmt::Request { show, .. })) => {
            CarriedMod::Show(non_empty(show)?)
        }
        (DetachWhich::Hide, FlowNode::Report(ReportStmt::Request { hide, .. })) => {
            CarriedMod::Hide(non_empty(hide)?)
        }
        (
            DetachWhich::BaselineShow,
            FlowNode::ForEnvs {
                clause: EnvClause::Roles { baseline_show, .. },
                ..
            },
        ) => CarriedMod::BaselineShow(non_empty(baseline_show)?),
        (
            DetachWhich::Role { baseline, index },
            FlowNode::ForEnvs {
                clause:
                    EnvClause::Roles {
                        baseline: b,
                        comparisons,
                        ..
                    },
                ..
            },
        ) => CarriedMod::Role {
            baseline,
            role: if baseline { b } else { comparisons }.get(index)?.clone(),
        },
        (DetachWhich::WithBlock, FlowNode::Report(ReportStmt::Request { with, .. })) => {
            CarriedMod::WithBlock(non_empty(with)?)
        }
        (
            DetachWhich::Statistics,
            FlowNode::Report(ReportStmt::VarAs { stats, .. } | ReportStmt::Computed { stats, .. }),
        ) => CarriedMod::Statistics(non_empty(stats)?),
        _ => return None,
    })
}

/// `Some(clone)` for a non-empty list — the "is this clause actually present?"
/// test every list-shaped modifier shares.
fn non_empty<T: Clone>(v: &[T]) -> Option<Vec<T>> {
    (!v.is_empty()).then(|| v.to_vec())
}

impl CarriedMod {
    /// The abstract modifier this is an instance of, when there is one. The
    /// role clauses of an `ENVS` loop (and a whole `WITH` block) have no
    /// palette counterpart, so they answer `None` and carry their own rules.
    fn kind(&self) -> Option<Modifier> {
        Some(match self {
            CarriedMod::Report => Modifier::Report,
            CarriedMod::Parallel(_) => Modifier::Parallel,
            CarriedMod::As(_) => Modifier::As,
            CarriedMod::With(_) => Modifier::With,
            CarriedMod::Response(_) => Modifier::Response,
            CarriedMod::Show(_) => Modifier::Show,
            CarriedMod::Hide(_) => Modifier::Hide,
            CarriedMod::Statistics(_) => Modifier::Statistics,
            CarriedMod::BaselineShow(_) | CarriedMod::Role { .. } | CarriedMod::WithBlock(_) => {
                return None;
            }
        })
    }

    /// Whether this clause can be grafted onto `node`.
    pub(crate) fn applies_to(&self, node: &FlowNode) -> bool {
        match self {
            // A carried REPORT only ever re-wraps a plain request. Dropping it
            // on an assignment *inserts a line* rather than changing this one
            // (see `report_assignment`), which is not a move of the clause in
            // hand, so that stays the palette's job.
            CarriedMod::Report => matches!(node, FlowNode::Request { .. }),
            CarriedMod::BaselineShow(_) => matches!(
                node,
                FlowNode::ForEnvs {
                    clause: EnvClause::Roles { baseline_show, .. },
                    ..
                } if baseline_show.is_empty()
            ),
            // A role joins any comparison loop that doesn't already list it —
            // the point of dragging `COMPARISON(stage)` to another loop.
            CarriedMod::Role { baseline, role } => matches!(
                node,
                FlowNode::ForEnvs {
                    clause: EnvClause::Roles { baseline: b, comparisons, .. },
                    ..
                } if !if *baseline { b } else { comparisons }.contains(role)
            ),
            CarriedMod::WithBlock(_) => matches!(
                node,
                FlowNode::Report(ReportStmt::Request { with, .. }) if with.is_empty()
            ),
            other => other.kind().is_some_and(|m: Modifier| m.applies_to(node)),
        }
    }

    /// Why this clause refuses to graft onto `node`, or `None` when it does.
    pub(crate) fn reject_reason(&self, node: &FlowNode, s: &Strings) -> Option<&'static str> {
        if self.applies_to(node) {
            return None;
        }
        Some(match self {
            CarriedMod::Report => {
                if matches!(node, FlowNode::Report(_)) {
                    s.mod_reject_present
                } else {
                    s.mod_reject_report
                }
            }
            CarriedMod::BaselineShow(_) | CarriedMod::Role { .. } => {
                if matches!(
                    node,
                    FlowNode::ForEnvs {
                        clause: EnvClause::Roles { .. },
                        ..
                    }
                ) {
                    s.mod_reject_present
                } else {
                    s.mod_reject_compare_only
                }
            }
            CarriedMod::WithBlock(_) => {
                if matches!(node, FlowNode::Report(ReportStmt::Request { .. })) {
                    s.mod_reject_present
                } else {
                    s.mod_reject_with
                }
            }
            other => other.kind()?.reject_reason(node, s)?,
        })
    }

    /// Graft this clause onto `node`, keeping the value it was carrying.
    /// Returns whether anything changed.
    pub(crate) fn attach_to(&self, node: &mut FlowNode) -> bool {
        if !self.applies_to(node) {
            return false;
        }
        match self {
            CarriedMod::Report => {
                if let FlowNode::Request {
                    name,
                    alias,
                    depends,
                    using,
                } = node
                {
                    let name = std::mem::take(name);
                    // The step name is this statement's identity and survives
                    // the upgrade with it.
                    let alias = alias.take();
                    // Declared edges say when the step runs, which the upgrade
                    // does not touch.
                    let depends = std::mem::take(depends);
                    // `USING` describes the *send*, which survives the upgrade
                    // to a reported one — dropping it here would silently
                    // discard a required-parameter check.
                    let using = std::mem::take(using);
                    *node = FlowNode::Report(ReportStmt::Request {
                        name,
                        alias,
                        depends,
                        using,
                        response_fmt: None,
                        show: Vec::new(),
                        hide: Vec::new(),
                        with: Vec::new(),
                    });
                }
            }
            CarriedMod::Parallel(spec) => match node {
                FlowNode::ForEach { parallel, .. } | FlowNode::ForEnvs { parallel, .. } => {
                    *parallel = Some(spec.clone().unwrap_or_default());
                }
                _ => {}
            },
            CarriedMod::As(name) => match node {
                FlowNode::Report(ReportStmt::Request { alias, .. }) => *alias = Some(name.clone()),
                FlowNode::Report(ReportStmt::Vars(vars)) if vars.len() == 1 => {
                    let var = vars.remove(0);
                    *node = FlowNode::Report(ReportStmt::VarAs {
                        var,
                        name: name.clone(),
                        stats: Vec::new(),
                        image: None,
                        truth: None,
                        detail: false,
                    });
                }
                _ => {}
            },
            CarriedMod::With(item) => {
                if let FlowNode::Report(ReportStmt::Request { with, .. }) = node {
                    with.push(item.clone());
                }
            }
            CarriedMod::Response(fmt) => {
                if let FlowNode::Report(ReportStmt::Request { response_fmt, .. }) = node {
                    *response_fmt = Some(*fmt);
                }
            }
            CarriedMod::Show(cols) => {
                if let FlowNode::Report(ReportStmt::Request { show, .. }) = node {
                    *show = cols.clone();
                }
            }
            CarriedMod::Hide(cols) => {
                if let FlowNode::Report(ReportStmt::Request { hide, .. }) = node {
                    *hide = cols.clone();
                }
            }
            CarriedMod::BaselineShow(cols) => {
                if let FlowNode::ForEnvs {
                    clause: EnvClause::Roles { baseline_show, .. },
                    ..
                } = node
                {
                    *baseline_show = cols.clone();
                }
            }
            CarriedMod::Role { baseline, role } => {
                if let FlowNode::ForEnvs {
                    clause:
                        EnvClause::Roles {
                            baseline: b,
                            comparisons,
                            ..
                        },
                    ..
                } = node
                {
                    if *baseline { b } else { comparisons }.push(role.clone());
                }
            }
            CarriedMod::WithBlock(items) => {
                if let FlowNode::Report(ReportStmt::Request { with, .. }) = node {
                    *with = items.clone();
                }
            }
            CarriedMod::Statistics(stats) => match node {
                FlowNode::Report(ReportStmt::VarAs { stats: s, .. })
                | FlowNode::Report(ReportStmt::Computed { stats: s, .. }) => *s = stats.clone(),
                _ => {}
            },
        }
        true
    }
}

/// Move (or, with `copy`, clone) the modifier `which` from the node at `from`
/// onto the node at `to`. This is what dropping a clause pulled off one line
/// onto another line does. A no-op returning `false` unless the clause is
/// really there *and* the destination will take it — and the two are never
/// half-applied, so a refused drop leaves the source untouched.
///
/// Detaching first is safe because only clauses whose removal leaves a valid
/// statement can be picked up in the first place (see
/// [`detach_leaves_statement`]), so no row disappears and no path shifts.
pub(crate) fn transfer_modifier(
    flow: &mut ReportFlow,
    from: &[usize],
    which: DetachWhich,
    to: &[usize],
    copy: bool,
) -> bool {
    if from == to {
        return false;
    }
    let Some(carried) = node_at(flow, from).and_then(|n| carry_modifier(n, which)) else {
        return false;
    };
    if !node_at(flow, to).is_some_and(|n| carried.applies_to(n)) {
        return false;
    }
    if !copy {
        detach_modifier(flow, from, which);
    }
    node_at_mut(flow, to).is_some_and(|n| carried.attach_to(n))
}

/// The body of [`detach_modifier`], on an already-resolved node. Returns `true`
/// when nothing coherent is left and the caller should remove the row.
pub(crate) fn detach_from_node(node: &mut FlowNode, which: DetachWhich) -> bool {
    match which {
        DetachWhich::Report => match node {
            // A reported request keeps sending: downgrade to a plain REQUEST.
            FlowNode::Report(ReportStmt::Request {
                name,
                alias,
                depends,
                using,
                ..
            }) => {
                let name = std::mem::take(name);
                // The step name is identity, not a reporting option, so it
                // survives the downgrade with the send it names.
                let alias = alias.take();
                let depends = std::mem::take(depends);
                let using = std::mem::take(using);
                *node = FlowNode::Request {
                    name,
                    alias,
                    depends,
                    using,
                };
                false
            }
            // A reported variable/computed column has nothing left without
            // REPORT — signal the caller to remove the row.
            FlowNode::Report(_) => true,
            _ => false,
        },
        DetachWhich::Parallel => {
            match node {
                FlowNode::ForEach { parallel, .. } | FlowNode::ForEnvs { parallel, .. } => {
                    *parallel = None;
                }
                _ => {}
            }
            false
        }
        DetachWhich::As => {
            match node {
                FlowNode::Report(ReportStmt::Request { alias, .. }) => *alias = None,
                FlowNode::Report(ReportStmt::VarAs { var, .. }) => {
                    let var = std::mem::take(var);
                    *node = FlowNode::Report(ReportStmt::Vars(vec![var]));
                }
                _ => {}
            }
            false
        }
        DetachWhich::With(i) => {
            if let FlowNode::Report(ReportStmt::Request { with, .. }) = node
                && i < with.len()
            {
                with.remove(i);
            }
            false
        }
        DetachWhich::Response => {
            if let FlowNode::Report(ReportStmt::Request { response_fmt, .. }) = node {
                *response_fmt = None;
            }
            false
        }
        DetachWhich::Show => {
            if let FlowNode::Report(ReportStmt::Request { show, .. }) = node {
                show.clear();
            }
            false
        }
        DetachWhich::Hide => {
            if let FlowNode::Report(ReportStmt::Request { hide, .. }) = node {
                hide.clear();
            }
            false
        }
        DetachWhich::BaselineShow => {
            if let FlowNode::ForEnvs {
                clause: EnvClause::Roles { baseline_show, .. },
                ..
            } = node
            {
                baseline_show.clear();
            }
            false
        }
        DetachWhich::Role { baseline, index } => {
            if let FlowNode::ForEnvs { clause, .. } = node
                && let EnvClause::Roles {
                    baseline: b,
                    comparisons,
                    ..
                } = clause
            {
                let side = if baseline { &mut *b } else { &mut *comparisons };
                if index < side.len() {
                    side.remove(index);
                }
                // A comparison needs both halves. Emptying either one leaves
                // nothing to compare against, so the loop degrades to a plain
                // pass over whichever environments are left rather than
                // serializing a half-written `BASELINE(…)` with no
                // `COMPARISON(…)` (which would not re-parse). Snapshot refs
                // have no plain form and so drop out.
                if b.is_empty() || comparisons.is_empty() {
                    let names: Vec<String> = b
                        .iter()
                        .chain(comparisons.iter())
                        .filter_map(|r| match r {
                            RoleRef::Env(n) => Some(n.clone()),
                            RoleRef::File(_) => None,
                        })
                        .collect();
                    *clause = EnvClause::Plain(names);
                }
            }
            false
        }
        DetachWhich::WithBlock => {
            if let FlowNode::Report(ReportStmt::Request { with, .. }) = node {
                with.clear();
            }
            false
        }
        DetachWhich::Statistics => {
            match node {
                FlowNode::Report(ReportStmt::VarAs { stats, .. })
                | FlowNode::Report(ReportStmt::Computed { stats, .. }) => stats.clear(),
                _ => {}
            }
            false
        }
        // The three column clauses are cleared through one helper each, since
        // every one of them has to reach both the statement's own column and a
        // `WITH` field, and the only difference between them is the field.
        DetachWhich::Image => {
            clear_clause(node, |image, _, _| *image = None);
            false
        }
        DetachWhich::Truth => {
            clear_clause(node, |_, truth, _| *truth = None);
            false
        }
        DetachWhich::Detail => {
            clear_clause(node, |_, _, detail| *detail = false);
            false
        }
    }
}

/// Apply `f` to a named report column's `(image, truth, detail)`, if `node` is
/// one. The lookup is the same for all three clauses, so it lives here rather
/// than three times over.
fn clear_clause(
    node: &mut FlowNode,
    f: impl FnOnce(&mut Option<ImageSpec>, &mut Option<String>, &mut bool),
) {
    if let FlowNode::Report(
        ReportStmt::VarAs {
            image,
            truth,
            detail,
            ..
        }
        | ReportStmt::Computed {
            image,
            truth,
            detail,
            ..
        },
    ) = node
    {
        f(image, truth, detail);
    }
}

/// Take (remove and return) the node at `path`, or `None` when the path does
/// not address a node. Used to relocate an existing node for drag-to-reorder.
pub(crate) fn take_node(flow: &mut ReportFlow, path: &[usize]) -> Option<FlowNode> {
    let (last, rest) = path.split_last()?;
    let body = body_at_mut(flow, rest)?;
    if *last < body.len() {
        Some(body.remove(*last))
    } else {
        None
    }
}

/// Move the existing node at `from` to the insert position `pos`, returning the
/// moved node's new path. Used when an in-report block is dragged onto a drop
/// strip to reorder it. A no-op (returns `None`) when `from` would move into its
/// own subtree (a loop cannot contain itself), keeping the tree well-formed.
///
/// Because removing the source shifts later siblings down by one, the
/// destination index is adjusted when both share a parent and the target sits
/// after the removed slot.
pub(crate) fn move_node_to(
    flow: &mut ReportFlow,
    from: &[usize],
    pos: &InsertPos,
) -> Option<Vec<usize>> {
    // Refuse to drop a loop inside itself (its own body / a descendant body):
    // `pos.parent` starting with `from` would orphan the subtree.
    if pos.parent.len() >= from.len() && pos.parent[..from.len()] == *from {
        return None;
    }
    let node = take_node(flow, from)?;
    let (from_last, from_parent) = from.split_last()?;
    // Removing the source shifts the later children of *its* body down by one.
    // A destination that traverses that same body at a slot after the removed
    // one must have that single index decremented — whether the slot is the
    // insertion index itself (same body) or a component of the parent path (the
    // destination nests through the body below the removed node).
    let d = from_parent.len();
    let mut parent = pos.parent.clone();
    let mut index = pos.index;
    if parent.len() > d && parent[..d] == *from_parent {
        if parent[d] > *from_last {
            parent[d] -= 1;
        }
    } else if parent == *from_parent && *from_last < index {
        index -= 1;
    }
    let dest = InsertPos { parent, index };
    insert_node(flow, &dest, node);
    let mut new_path = dest.parent;
    new_path.push(dest.index);
    Some(new_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::flow::FlowNode;

    fn flow(src: &str) -> ReportFlow {
        parse_flow(src).expect("test flow must parse")
    }

    fn always_ok(_: &str) -> bool {
        true
    }

    #[test]
    fn flatten_marks_begin_body_and_loop_end() {
        let f = flow("REQUEST A\nFOR X IN FILES \"/d\"\n    REQUEST B\nEND\n");
        let rows = flatten(&f, &always_ok);
        let kinds: Vec<RowKind> = rows.iter().map(|r| r.kind).collect();
        assert_eq!(
            kinds,
            vec![
                RowKind::Begin,
                RowKind::Leaf,
                RowKind::LoopHead,
                RowKind::Leaf,
                RowKind::LoopEnd,
            ]
        );
        // The loop head and its END share the same path; the body is deeper.
        assert_eq!(rows[2].path, rows[4].path);
        assert_eq!(rows[3].path, vec![1, 0]);
    }

    /// The block editor writes a parameter's default straight back into the
    /// script, and clearing it makes the parameter required again rather than
    /// leaving `= ""` behind — an empty default is a value, "no default" is not.
    #[test]
    fn a_parameters_default_can_be_set_and_cleared() {
        let mut f = flow("PARAM ENV TARGET = \"staging\" LABEL \"Environment\"\n");

        assert!(set_param_default(&mut f, &[0], "prod"));
        assert!(
            f.to_text().contains("PARAM ENV TARGET = \"prod\""),
            "{}",
            f.to_text()
        );
        assert!(
            f.to_text().contains("LABEL \"Environment\""),
            "the rest of the declaration is untouched: {}",
            f.to_text()
        );
        assert!(
            !set_param_default(&mut f, &[0], "prod"),
            "setting the same value again is not an edit"
        );

        assert!(set_param_default(&mut f, &[0], "  "));
        assert_eq!(param_decl(&f, &[0]).expect("still a PARAM").default, None);
        assert!(
            !f.to_text().contains('='),
            "cleared, not emptied: {}",
            f.to_text()
        );
    }

    #[test]
    fn insert_pos_after_targets_the_right_body() {
        let f = flow("REQUEST A\nFOR X IN FILES \"/d\"\n    REQUEST B\nEND\n");
        let rows = flatten(&f, &always_ok);
        // On Begin (row 0): front of the top level.
        let p = insert_pos_after(&rows, 0);
        assert_eq!(p.parent, Vec::<usize>::new());
        assert_eq!(p.index, 0);
        // On the leaf REQUEST A (row 1): after it, same (top) level.
        let p = insert_pos_after(&rows, 1);
        assert_eq!(p.parent, Vec::<usize>::new());
        assert_eq!(p.index, 1);
        // On the loop head (row 2): inside the loop, at its front.
        let p = insert_pos_after(&rows, 2);
        assert_eq!(p.parent, vec![1]);
        assert_eq!(p.index, 0);
        // On END (row 4): after the whole loop, at the top level.
        let p = insert_pos_after(&rows, 4);
        assert_eq!(p.parent, Vec::<usize>::new());
        assert_eq!(p.index, 2);
    }

    #[test]
    fn insert_and_remove_round_trip() {
        let mut f = flow("REQUEST A\n");
        let pos = InsertPos {
            parent: Vec::new(),
            index: 1,
        };
        insert_node(&mut f, &pos, request_node("B", false));
        assert_eq!(
            f.nodes.iter().map(|n| n.request_name()).collect::<Vec<_>>(),
            vec![Some("A"), Some("B")]
        );
        assert!(remove_node(&mut f, &[0]));
        assert_eq!(
            f.nodes.iter().map(|n| n.request_name()).collect::<Vec<_>>(),
            vec![Some("B")]
        );
    }

    #[test]
    fn move_node_swaps_siblings_and_reports_boundaries() {
        let mut f = flow("REQUEST A\nREQUEST B\n");
        // Move B (index 1) up -> becomes index 0.
        let np = move_node(&mut f, &[1], true).expect("can move up");
        assert_eq!(np, vec![0]);
        assert_eq!(
            f.nodes.iter().map(|n| n.request_name()).collect::<Vec<_>>(),
            vec![Some("B"), Some("A")]
        );
        // The first node can't move up any further.
        assert!(move_node(&mut f, &[0], true).is_none());
    }

    #[test]
    fn replace_node_keeps_a_loops_body() {
        let mut f = flow("FOR X IN FILES \"/a\"\n    REQUEST Inner\nEND\n");
        // Re-parse an edited FOR header (a different dir) and swap it in.
        let edited = parse_one_node("FOR X IN FILES \"/b\"", true).expect("loop parses");
        assert!(replace_node(&mut f, &[0], edited));
        // The body survived the header replacement.
        let body = match &f.nodes[0] {
            FlowNode::ForEach { body, .. } => body,
            other => panic!("expected a loop, got {other:?}"),
        };
        assert_eq!(body.len(), 1);
        assert_eq!(body[0].request_name(), Some("Inner"));
        // And the new dir is reflected in the serialized text.
        assert!(f.to_text().contains("\"/b\""));
    }

    #[test]
    fn parse_one_node_needs_exactly_one_statement() {
        assert!(parse_one_node("REQUEST A", false).is_some());
        assert!(parse_one_node("FOR X IN FILES \"/d\"", true).is_some());
        // Two statements is not a single node.
        assert!(parse_one_node("REQUEST A\nREQUEST B", false).is_none());
        // A bare FOR with no END never closes.
        assert!(parse_one_node("FOR", false).is_none());
        assert!(parse_one_node("   ", false).is_none());
    }

    /// The node editor's raw line prompt routes through `parse_one_node`, so a
    /// `REPORT VAR AS <pretty name>` line becomes a renamed-variable node.
    #[test]
    fn parse_one_node_accepts_report_var_as() {
        use crate::report::flow::ReportStmt;
        match parse_one_node("REPORT FILE AS \"Pretty name\"", false) {
            Some(FlowNode::Report(ReportStmt::VarAs { var, name, .. })) => {
                assert_eq!(var, "FILE");
                assert_eq!(name, "Pretty name");
            }
            other => panic!("expected a VarAs node, got {other:?}"),
        }
    }

    // ── Compositional modifiers ────────────────────────────────────────────

    #[test]
    fn report_modifier_wraps_and_unwraps_a_request() {
        let mut f = flow("REQUEST login\n");
        assert!(Modifier::Report.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(attach_modifier(&mut f, &[0], Modifier::Report));
        assert!(matches!(
            node_at(&f, &[0]),
            Some(FlowNode::Report(ReportStmt::Request { .. }))
        ));
        // REPORT no longer applies (already reported); detaching restores the send.
        assert!(!Modifier::Report.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(!detach_modifier(&mut f, &[0], DetachWhich::Report));
        assert!(matches!(node_at(&f, &[0]), Some(FlowNode::Request { .. })));
    }

    #[test]
    fn detaching_report_from_a_variable_asks_to_remove_the_row() {
        let mut f = flow("REPORT userId\n");
        // A reported variable has nothing valid left without REPORT.
        assert!(detach_modifier(&mut f, &[0], DetachWhich::Report));
    }

    /// The loop chip's inline name box: it renames the one thing a single-binder
    /// loop binds, and refuses anything the parser would not take back.
    #[test]
    fn set_loop_var_renames_a_single_binder_and_rejects_names_that_would_not_parse() {
        let mut f = flow("FOR file IN FILES \".\" MATCH \"*.json\"\n  REQUEST A\nEND\n");
        assert!(set_loop_var(&mut f, &[0], "doc"));
        assert!(
            f.to_text().contains("FOR doc IN FILES"),
            "the rename reached the source: {}",
            f.to_text()
        );

        assert!(
            !set_loop_var(&mut f, &[0], "doc"),
            "no change is not a change"
        );
        for bad in ["", "   ", "my file", "2fast", "a-b"] {
            assert!(
                !set_loop_var(&mut f, &[0], bad),
                "{bad:?} is not an identifier and must be refused"
            );
        }
        assert!(
            f.to_text().contains("FOR doc IN FILES"),
            "and a refused name leaves the loop alone"
        );

        // An ENVS loop binds one name too, so it renames the same way.
        let mut e = flow("FOR t IN ENVS BASELINE(\"prod\")\n  REQUEST A\nEND\n");
        assert!(set_loop_var(&mut e, &[0], "target"));
        assert!(e.to_text().contains("FOR target IN ENVS"));
    }

    /// A destructuring loop has more than one name, and the chip has one box --
    /// there would be no saying which binder it meant, so it stays with the
    /// wizard rather than guessing.
    #[test]
    fn set_loop_var_refuses_a_pattern_that_binds_more_than_one_name() {
        let mut f = flow("FOR (NAME, URL) IN DOCS\n  REQUEST A\nEND\n");
        assert!(!set_loop_var(&mut f, &[0], "x"));
        assert!(
            f.to_text().contains("FOR (NAME, URL) IN"),
            "the pattern is untouched: {}",
            f.to_text()
        );

        // A `...` rest binds an unknown number of positions, so one box can
        // speak for none of them either.
        let mut r = flow("FOR (HEAD, ...) IN DOCS\n  REQUEST A\nEND\n");
        assert!(!set_loop_var(&mut r, &[0], "x"));

        // `_` discards its position; renaming it would be adding a binder.
        let mut d = flow("FOR _ IN FILES \".\"\n  REQUEST A\nEND\n");
        assert!(!set_loop_var(&mut d, &[0], "x"));
    }

    /// The folder box and its picker, over the three producers that have one
    /// path to point at.
    #[test]
    fn the_loop_folder_can_be_read_and_repointed_for_the_producers_that_have_one() {
        let mut files = flow("FOR f IN FILES \"cases\" MATCH \"*.json\"\n  REQUEST A\nEND\n");
        assert_eq!(loop_dir(&files, &[0]).as_deref(), Some("cases"));
        assert!(set_loop_dir(&mut files, &[0], "other/cases"));
        assert!(files.to_text().contains("FILES \"other/cases\""));
        assert!(
            !set_loop_dir(&mut files, &[0], "   "),
            "clearing the folder would silently mean the working directory"
        );

        let mut folders = flow("FOR d IN FOLDERS \"envs\"\n  REQUEST A\nEND\n");
        assert_eq!(loop_dir(&folders, &[0]).as_deref(), Some("envs"));
        assert!(set_loop_dir(&mut folders, &[0], "environments"));
        assert!(folders.to_text().contains("FOLDERS \"environments\""));

        let mut tuples = flow("FOR t IN TUPLES FROM \"rows.csv\"\n  REQUEST A\nEND\n");
        assert_eq!(loop_dir(&tuples, &[0]).as_deref(), Some("rows.csv"));
        assert!(set_loop_dir(&mut tuples, &[0], "data/rows.csv"));
        assert!(tuples.to_text().contains("TUPLES FROM \"data/rows.csv\""));

        // A list literal has no single path, so the chip shows no picker.
        let list = flow("FOR x IN [\"a\", \"b\"]\n  REQUEST A\nEND\n");
        assert_eq!(loop_dir(&list, &[0]), None);
    }

    /// Unlike the folder, an empty glob is a real answer: `FILES` with no
    /// `MATCH` takes every file.
    #[test]
    fn the_loop_glob_can_be_set_and_cleared() {
        let mut f = flow("FOR f IN FILES \"cases\"\n  REQUEST A\nEND\n");
        assert!(!f.to_text().contains("MATCH"));
        assert!(set_loop_glob(&mut f, &[0], "*.json"));
        assert!(f.to_text().contains("MATCH \"*.json\""));

        assert!(set_loop_glob(&mut f, &[0], ""));
        assert!(
            !f.to_text().contains("MATCH"),
            "clearing the box drops the clause: {}",
            f.to_text()
        );
    }

    #[test]
    fn set_parallel_degree_edits_the_concurrency_limit_and_rejects_zero() {
        let mut f = flow("PARALLEL FOR X IN FILES \"/d\"\n    REQUEST A\nEND\n");

        assert!(set_parallel_degree(&mut f, &[0], Some(4)));
        assert!(f.to_text().contains("PARALLEL(4) FOR"));

        // Clearing the degree goes back to the plain PARALLEL form, where the
        // limit comes from the prelude rather than the loop.
        assert!(set_parallel_degree(&mut f, &[0], None));
        assert!(f.to_text().contains("PARALLEL FOR"));

        // The parser refuses PARALLEL(0), so the editor must too — otherwise a
        // saved flow wouldn't load back.
        assert!(set_parallel_degree(&mut f, &[0], Some(4)));
        assert!(!set_parallel_degree(&mut f, &[0], Some(0)));
        assert!(f.to_text().contains("PARALLEL(4) FOR"));
    }

    #[test]
    fn set_header_adds_edits_and_removes_directives() {
        let mut f = flow(
            "# collection: api.hurl
REQUEST A
",
        );

        // Editing in place keeps the directive where the user put it.
        assert!(set_header_nth(&mut f, "collection", 0, Some("other.hurl")));
        assert!(f.to_text().contains("# collection: other.hurl"));
        assert_eq!(f.header.collection(), Some("other.hurl"));

        // A new directive lands with the others, not at the top of the file.
        assert!(set_header_nth(&mut f, "output", 0, Some("out.csv")));
        assert_eq!(f.header.output(), Some("out.csv"));
        let text = f.to_text();
        assert!(
            text.find("# collection:") < text.find("# output:"),
            "new directives are appended after the existing ones: {text:?}"
        );

        // Setting the same value again is not a change, so it can't push a
        // pointless undo entry or mark the report dirty.
        assert!(!set_header_nth(&mut f, "output", 0, Some("out.csv")));

        // Clearing removes the line rather than leaving `# output:` empty,
        // which the parser would read as a directive set to the empty string.
        assert!(set_header_nth(&mut f, "output", 0, None));
        assert_eq!(f.header.output(), None);
        assert!(!f.to_text().contains("# output"));
        assert!(!set_header_nth(&mut f, "output", 0, None));

        // Blank input means "unset", not "set to nothing".
        assert!(!set_header_nth(&mut f, "root", 0, Some("   ")));
        assert_eq!(f.header.root(), None);
    }

    /// Free-form `#` comments are the user's own notes; editing a directive must
    /// never reorder or drop them.
    #[test]
    fn set_header_leaves_free_form_comments_alone() {
        let mut f = flow(
            "# collection: api.hurl
# a note to self
REQUEST A
",
        );
        assert!(set_header_nth(&mut f, "environment", 0, Some("dev")));
        let text = f.to_text();
        assert!(text.contains("# a note to self"), "{text:?}");
        assert!(
            text.find("# environment:") < text.find("# a note"),
            "the new directive joins the directive block, above the notes: {text:?}"
        );
    }

    #[test]
    fn a_degree_cannot_be_set_on_a_loop_that_is_not_parallel() {
        // Accepting this would silently turn a serial loop concurrent; the
        // PARALLEL modifier has to be attached first.
        let mut f = flow("FOR X IN FILES \"/d\"\n    REQUEST A\nEND\n");
        assert!(!set_parallel_degree(&mut f, &[0], Some(2)));
        assert!(!f.to_text().contains("PARALLEL"));

        // Nor on a node that has no PARALLEL concept at all.
        let mut g = flow("REQUEST A\n");
        assert!(!set_parallel_degree(&mut g, &[0], Some(2)));
    }

    #[test]
    fn parallel_modifier_toggles_a_loop() {
        let mut f = flow("FOR X IN FILES \"/d\"\n    REQUEST A\nEND\n");
        assert!(Modifier::Parallel.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(attach_modifier(&mut f, &[0], Modifier::Parallel));
        assert!(matches!(
            node_at(&f, &[0]),
            Some(FlowNode::ForEach {
                parallel: Some(_),
                ..
            })
        ));
        // Body is preserved and PARALLEL no longer applies.
        assert!(!Modifier::Parallel.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(!detach_modifier(&mut f, &[0], DetachWhich::Parallel));
        assert!(matches!(
            node_at(&f, &[0]),
            Some(FlowNode::ForEach { parallel: None, .. })
        ));
    }

    #[test]
    fn with_modifier_adds_and_removes_a_report_request_field() {
        let mut f = flow("REPORT REQUEST analyze\n");
        assert!(Modifier::With.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(attach_modifier(&mut f, &[0], Modifier::With));
        match node_at(&f, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request { with, .. })) => {
                assert_eq!(with.len(), 1);
            }
            other => panic!("expected a report request with a field, got {other:?}"),
        }
        assert!(!detach_modifier(&mut f, &[0], DetachWhich::With(0)));
        match node_at(&f, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request { with, .. })) => assert!(with.is_empty()),
            other => panic!("expected an empty WITH, got {other:?}"),
        }
    }

    #[test]
    fn as_modifier_names_a_request_alias_and_a_variable_column() {
        // On a report request → sets the alias.
        let mut f = flow("REPORT REQUEST analyze\n");
        assert!(attach_modifier(&mut f, &[0], Modifier::As));
        assert!(matches!(
            node_at(&f, &[0]),
            Some(FlowNode::Report(ReportStmt::Request { alias: Some(_), .. }))
        ));
        // AS no longer applies once aliased.
        assert!(!Modifier::As.applies_to(node_at(&f, &[0]).unwrap()));

        // On a single-variable REPORT → becomes a VarAs column.
        let mut g = flow("REPORT userId\n");
        assert!(Modifier::As.applies_to(node_at(&g, &[0]).unwrap()));
        assert!(attach_modifier(&mut g, &[0], Modifier::As));
        assert!(matches!(
            node_at(&g, &[0]),
            Some(FlowNode::Report(ReportStmt::VarAs { .. }))
        ));
        // Detaching AS returns it to a bare REPORT <var>.
        assert!(!detach_modifier(&mut g, &[0], DetachWhich::As));
        assert!(matches!(
            node_at(&g, &[0]),
            Some(FlowNode::Report(ReportStmt::Vars(_)))
        ));
    }

    #[test]
    fn modifiers_do_not_apply_where_they_make_no_sense() {
        let f = flow("k = v\n");
        let n = node_at(&f, &[0]).unwrap();
        // REPORT now applies to a plain assignment (dropping it inserts a
        // sibling `REPORT (VAR)` line — see `report_assignment`); the loop /
        // request-only modifiers still do not.
        assert!(Modifier::Report.applies_to(n));
        assert!(!Modifier::Parallel.applies_to(n));
        assert!(!Modifier::With.applies_to(n));
        assert!(!Modifier::As.applies_to(n));
    }

    /// A clause is only pullable-out if the statement survives without it.
    /// `REPORT` is load-bearing on a reported column (there is no statement left
    /// at all) but not on a reported request, which falls back to a plain send.
    #[test]
    fn report_is_load_bearing_on_a_column_but_not_on_a_request() {
        let flow =
            parse_flow("REPORT REQUEST A\nREPORT TIER AS Plan\nREPORT \"x\" AS c\nREPORT (A, B)\n")
                .expect("fixture parses");
        assert!(
            detach_leaves_statement(&flow.nodes[0], DetachWhich::Report),
            "a reported request downgrades to a plain REQUEST, so REPORT snaps off"
        );
        for (i, what) in [
            (1, "REPORT … AS"),
            (2, "a computed column"),
            (3, "REPORT (…)"),
        ] {
            assert!(
                !detach_leaves_statement(&flow.nodes[i], DetachWhich::Report),
                "nothing is left of {what} without REPORT, so it must move the whole row"
            );
        }
    }

    /// STATISTICS needs a named column to summarise; a bare `REPORT (A, B)` has
    /// no single column to attach it to, and it is refused with a reason.
    #[test]
    fn statistics_attaches_to_a_named_column_and_only_once() {
        let mut flow = parse_flow("REPORT TIER AS Plan\nREPORT (A, B)\n").expect("fixture parses");
        assert!(
            attach_modifier(&mut flow, &[0], Modifier::Statistics),
            "a named column accepts STATISTICS"
        );
        assert!(
            flow.to_text().contains("STATISTICS("),
            "the clause is written out: {}",
            flow.to_text()
        );
        assert!(
            !attach_modifier(&mut flow, &[0], Modifier::Statistics),
            "a column that already has STATISTICS refuses a second one"
        );
        assert!(
            !attach_modifier(&mut flow, &[1], Modifier::Statistics),
            "REPORT (A, B) names no single column"
        );
        detach_modifier(&mut flow, &[0], DetachWhich::Statistics);
        assert!(
            !flow.to_text().contains("STATISTICS(") && flow.to_text().contains("AS Plan"),
            "detaching leaves the column itself alone: {}",
            flow.to_text()
        );
    }

    /// A `WITH` field is the report column a request actually names, so it is
    /// what STATISTICS attaches to — the request line above summarises nothing.
    /// The block editor could show a field's STATISTICS but had no way to add
    /// one, because a field isn't a node a modifier can be dropped on.
    #[test]
    fn statistics_attaches_to_a_with_field() {
        let mut flow =
            parse_flow("REPORT REQUEST svc WITH\n    Elapsed: Time\n    RESPONSE RAW\nEND\n")
                .expect("fixture parses");
        // The request line itself still refuses it: its columns are its fields.
        assert!(
            !attach_modifier(&mut flow, &[0], Modifier::Statistics),
            "a report request names no single column"
        );

        assert!(
            with_stats_applies(with_of(&flow), 0),
            "a named field takes it"
        );
        assert!(attach_with_stats(&mut flow, &[0], 0));
        assert!(
            flow.to_text().contains("Elapsed: Time STATISTICS(COUNT)"),
            "the clause lands on the field: {}",
            flow.to_text()
        );

        // Only once, and never on a bare `WITH RESPONSE` item (which has no name
        // to put a column under) or a field that isn't there.
        assert!(!with_stats_applies(with_of(&flow), 0), "already has one");
        assert!(!attach_with_stats(&mut flow, &[0], 0));
        assert!(
            !with_stats_applies(with_of(&flow), 1),
            "RESPONSE RAW is not a column"
        );
        assert!(!attach_with_stats(&mut flow, &[0], 1));
        assert!(!attach_with_stats(&mut flow, &[0], 9), "no such field");

        // And it round-trips back through the parser as a field clause.
        let again = parse_flow(&flow.to_text()).expect("reparses");
        assert_eq!(again.to_text(), flow.to_text());
    }

    /// The `WITH` items of the report request at the root of `flow`.
    fn with_of(flow: &ReportFlow) -> &[WithItem] {
        match &flow.nodes[0] {
            FlowNode::Report(ReportStmt::Request { with, .. }) => with,
            other => panic!("expected a report request, got {other:?}"),
        }
    }

    /// Every refusal has to distinguish "wrong kind of block" from "it's
    /// already there" — telling someone REPORT only goes on a request while
    /// they hover a reported request is worse than saying nothing.
    #[test]
    fn a_duplicate_modifier_is_refused_as_a_duplicate_not_as_a_wrong_block() {
        let flow = parse_flow("REPORT REQUEST A\nREQUEST B\nREPORT TIER AS Plan\n")
            .expect("fixture parses");
        let s = Strings::english();

        assert_eq!(
            Modifier::Report.reject_reason(&flow.nodes[0], s),
            Some(s.mod_reject_present),
            "an already-reported request has REPORT, it isn't the wrong shape for it"
        );
        assert_eq!(
            Modifier::Report.reject_reason(&flow.nodes[2], s),
            Some(s.mod_reject_present),
            "a reported column is a REPORT statement too"
        );
        assert_eq!(
            Modifier::Report.reject_reason(&flow.nodes[1], s),
            None,
            "a plain request still takes REPORT"
        );

        // The same clause carried off another line answers the same way.
        let carried = carry_modifier(&flow.nodes[0], DetachWhich::Report).expect("carries REPORT");
        assert_eq!(
            carried.reject_reason(&flow.nodes[0], s),
            Some(s.mod_reject_present)
        );
    }

    /// The whole point of dragging a clause between lines: it has to arrive
    /// with the value it left with, not as a fresh placeholder.
    #[test]
    fn a_show_dragged_to_another_request_brings_its_columns_with_it() {
        let mut flow = parse_flow("REPORT REQUEST A SHOW(Time, HttpStatus)\nREPORT REQUEST B\n")
            .expect("fixture parses");

        assert!(
            transfer_modifier(&mut flow, &[0], DetachWhich::Show, &[1], false),
            "an as-yet SHOW-less reported request accepts the clause"
        );
        let text = flow.to_text();
        assert!(
            text.contains("REQUEST B SHOW(Time, HttpStatus)"),
            "the columns travel with the clause: {text}"
        );
        assert!(
            !text.contains("REQUEST A SHOW"),
            "a move leaves nothing behind on the source line: {text}"
        );

        // The destination already has one now, so dragging it back is refused
        // outright rather than half-applied (the source must survive intact).
        assert!(
            !transfer_modifier(&mut flow, &[1], DetachWhich::Show, &[1], false),
            "a line never transfers a clause to itself"
        );
    }

    /// Shift-dropping copies instead of moving, which is how one loop's
    /// `PARALLEL(4)` gets cloned onto its neighbours.
    #[test]
    fn a_copied_parallel_clones_its_degree_and_leaves_the_original_alone() {
        let mut flow = parse_flow(
            "PARALLEL(4) FOR X IN FILES \"/a\"\n    REQUEST A\nEND\nFOR Y IN FILES \"/b\"\n    REQUEST B\nEND\n",
        )
        .expect("fixture parses");

        assert!(
            transfer_modifier(&mut flow, &[0], DetachWhich::Parallel, &[1], true),
            "a plain loop accepts a copied PARALLEL"
        );
        let text = flow.to_text();
        assert_eq!(
            text.matches("PARALLEL(4)").count(),
            2,
            "a copy keeps the original and reproduces its degree: {text}"
        );

        // Moving it onto a loop that now has one is refused, so the source keeps
        // its own clause rather than losing it to a drop that did nothing.
        assert!(
            !transfer_modifier(&mut flow, &[0], DetachWhich::Parallel, &[1], false),
            "a loop that is already parallel takes no second PARALLEL"
        );
        assert!(
            flow.to_text().matches("PARALLEL(4)").count() == 2,
            "a refused transfer is not half-applied: {}",
            flow.to_text()
        );
    }

    /// A clause is only offered where it makes sense, and the refusal says why.
    #[test]
    fn a_carried_clause_is_refused_by_a_block_that_cannot_hold_it() {
        let flow = parse_flow("REPORT REQUEST A SHOW(Time)\nK = \"v\"\n").expect("parses");
        let carried =
            carry_modifier(&flow.nodes[0], DetachWhich::Show).expect("the SHOW is really there");
        let s = Strings::english();

        assert!(!carried.applies_to(&flow.nodes[1]), "SET has no columns");
        assert_eq!(
            carried.reject_reason(&flow.nodes[1], s),
            Some(s.mod_reject_request_only),
            "the refusal names the kind of block that would take it"
        );

        // Nothing to carry when the clause isn't on the node at all.
        assert!(
            carry_modifier(&flow.nodes[1], DetachWhich::Show).is_none(),
            "a node without the clause carries nothing"
        );
    }

    /// The baseline's `SHOW(…)` is a chip of its own, so dragging it out has to
    /// clear only that clause and leave the comparison intact.
    #[test]
    fn detaching_the_baseline_show_leaves_the_rest_of_the_compare_loop() {
        let mut flow = parse_flow(
            "FOR E IN ENVS BASELINE(\"prod\") SHOW(Time), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        )
        .expect("fixture parses");
        assert!(
            !detach_modifier(&mut flow, &[0], DetachWhich::BaselineShow),
            "clearing SHOW never removes the loop itself"
        );
        let text = flow.to_text();
        assert!(
            !text.contains("SHOW(") && text.contains("BASELINE(") && text.contains("COMPARISON("),
            "only the SHOW clause goes: {text}"
        );
    }

    /// Dropping either half of a comparison leaves nothing to compare against,
    /// so the loop has to degrade to a plain pass rather than serialize a
    /// `BASELINE(…)` with no `COMPARISON(…)` (which would not re-parse).
    #[test]
    fn detaching_a_comparison_role_degrades_the_loop_to_a_plain_pass() {
        let mut flow = parse_flow(
            "FOR E IN ENVS BASELINE(\"prod\"), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        )
        .expect("fixture parses");
        detach_modifier(
            &mut flow,
            &[0],
            DetachWhich::Role {
                baseline: false,
                index: 0,
            },
        );
        let text = flow.to_text();
        assert!(
            !text.contains("COMPARISON(") && !text.contains("BASELINE(") && text.contains("prod"),
            "the surviving environment is still iterated: {text}"
        );
        assert!(
            parse_flow(&text).is_ok(),
            "the degraded loop re-parses: {text}"
        );
    }

    #[test]
    fn a_refused_modifier_says_whether_the_block_is_wrong_or_the_clause_is_already_there() {
        let s = crate::i18n::Strings::english();
        // Wrong kind of block: PARALLEL on an assignment names what it *does*
        // take, so the user can aim somewhere useful.
        let assign = flow("k = v\n");
        assert_eq!(
            Modifier::Parallel.reject_reason(node_at(&assign, &[0]).unwrap(), s),
            Some(s.mod_reject_parallel),
            "PARALLEL on an assignment should point at FOR loops"
        );
        // Right kind of block, clause already present: the reason must not
        // claim the block is wrong, or the user will move the chip elsewhere.
        let looped = flow(
            "PARALLEL FOR E IN ENVS BASELINE(\"prod\"), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        );
        assert_eq!(
            Modifier::Parallel.reject_reason(node_at(&looped, &[0]).unwrap(), s),
            Some(s.mod_reject_present),
            "an already-parallel loop should say the clause is already there"
        );
        // And an accepted drop has no reason at all.
        let plain =
            flow("FOR E IN ENVS BASELINE(\"prod\"), COMPARISON(\"stage\")\n    REQUEST A\nEND\n");
        assert_eq!(
            Modifier::Parallel.reject_reason(node_at(&plain, &[0]).unwrap(), s),
            None,
            "a modifier that applies should give no refusal reason"
        );
    }

    #[test]
    fn renaming_a_report_request_preserves_its_modifiers() {
        let mut f = flow("REPORT REQUEST analyze AS proc WITH\n    latency: Time\nEND\n");
        assert!(set_request_name(&mut f, &[0], "verify"));
        match node_at(&f, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request {
                name, alias, with, ..
            })) => {
                assert_eq!(name, "verify");
                assert_eq!(alias.as_deref(), Some("proc"));
                assert_eq!(with.len(), 1);
            }
            other => panic!("expected the report request kept its modifiers, got {other:?}"),
        }
    }

    #[test]
    fn detaching_response_show_hide_clears_only_that_clause() {
        let mut f =
            flow("REPORT REQUEST analyze RESPONSE RAW SHOW(Time, HttpStatus) HIDE(Response)\n");
        assert!(!detach_modifier(&mut f, &[0], DetachWhich::Response));
        assert!(!detach_modifier(&mut f, &[0], DetachWhich::Show));
        assert!(!detach_modifier(&mut f, &[0], DetachWhich::Hide));
        match node_at(&f, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request {
                name,
                response_fmt,
                show,
                hide,
                ..
            })) => {
                assert_eq!(name, "analyze");
                assert!(response_fmt.is_none());
                assert!(show.is_empty());
                assert!(hide.is_empty());
            }
            other => panic!("expected the request kept only its name, got {other:?}"),
        }
    }

    #[test]
    fn response_show_hide_modifiers_attach_defaults_and_round_trip() {
        let mut f = flow("REPORT REQUEST analyze\n");
        // Each applies to a bare report request…
        assert!(Modifier::Response.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(Modifier::Show.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(Modifier::Hide.applies_to(node_at(&f, &[0]).unwrap()));
        // …and drops a sensible default in place.
        assert!(attach_modifier(&mut f, &[0], Modifier::Response));
        assert!(attach_modifier(&mut f, &[0], Modifier::Show));
        assert!(attach_modifier(&mut f, &[0], Modifier::Hide));
        // Now attached, none applies a second time (no silent overwrite).
        assert!(!Modifier::Response.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(!Modifier::Show.applies_to(node_at(&f, &[0]).unwrap()));
        assert!(!Modifier::Hide.applies_to(node_at(&f, &[0]).unwrap()));
        // The serialized text re-parses with the same clauses intact.
        let reparsed = flow(&f.to_text());
        match node_at(&reparsed, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request {
                response_fmt,
                show,
                hide,
                ..
            })) => {
                assert_eq!(*response_fmt, Some(ResponseFmt::Pretty));
                assert_eq!(show, &vec!["HttpStatus".to_string()]);
                assert_eq!(hide, &vec!["HttpStatus".to_string()]);
            }
            other => panic!("expected a decorated report request, got {other:?}"),
        }
    }

    #[test]
    fn report_computed_kind_template_round_trips() {
        // The palette's computed-column template must round-trip through the
        // serializer/parser or dropping it would kick the user out of the editor.
        let node = NodeKind::ReportComputed
            .template()
            .expect("computed kind has a template");
        let mut f = flow("REQUEST A\n");
        insert_node(
            &mut f,
            &InsertPos {
                parent: Vec::new(),
                index: 1,
            },
            node,
        );
        let reparsed = flow(&f.to_text());
        match node_at(&reparsed, &[1]) {
            Some(FlowNode::Report(ReportStmt::Computed { template, name, .. })) => {
                assert!(!template.is_empty());
                assert!(!name.is_empty());
            }
            other => panic!("expected a computed column, got {other:?}"),
        }
    }

    #[test]
    fn move_node_to_reorders_within_a_body_and_adjusts_the_index() {
        // A, B, C at top level. Move A (index 0) to index 2 (after B, before C).
        let mut f = flow("REQUEST A\nREQUEST B\nREQUEST C\n");
        let pos = InsertPos {
            parent: Vec::new(),
            index: 2,
        };
        let new = move_node_to(&mut f, &[0], &pos).expect("move should succeed");
        // The removal of index 0 shifts the target down by one → lands at 1.
        assert_eq!(new, vec![1]);
        let names: Vec<String> = f
            .nodes
            .iter()
            .map(|n| match n {
                FlowNode::Request { name, .. } => name.clone(),
                _ => String::new(),
            })
            .collect();
        assert_eq!(names, vec!["B", "A", "C"]);
    }

    #[test]
    fn move_node_to_can_nest_into_a_loop_body() {
        let mut f = flow("REQUEST A\nFOR X IN FILES \"/d\"\n    REQUEST B\nEND\n");
        // Move A (index 0) into the loop body (path [1]) at index 0.
        let pos = InsertPos {
            parent: vec![1],
            index: 0,
        };
        let new = move_node_to(&mut f, &[0], &pos).expect("move should succeed");
        assert_eq!(new, vec![0, 0]);
        // Now the loop is the only top-level node, holding A then B.
        match &f.nodes[0] {
            FlowNode::ForEach { body, .. } => {
                assert_eq!(body.len(), 2);
                assert!(matches!(&body[0], FlowNode::Request { name, .. } if name == "A"));
            }
            other => panic!("expected the loop, got {other:?}"),
        }
    }

    #[test]
    fn move_node_to_refuses_to_drop_a_loop_into_itself() {
        let mut f = flow("FOR X IN FILES \"/d\"\n    REQUEST B\nEND\n");
        // Try to move the loop (path [0]) into its own body (parent [0]).
        let pos = InsertPos {
            parent: vec![0],
            index: 0,
        };
        assert!(move_node_to(&mut f, &[0], &pos).is_none());
        // The tree is untouched.
        assert!(matches!(&f.nodes[0], FlowNode::ForEach { .. }));
    }

    #[test]
    fn report_assignment_inserts_a_sibling_report_after_the_set() {
        let mut f = flow("TOKEN=abc\nREQUEST A\n");
        let new = report_assignment(&mut f, &[0]).expect("assign is reportable");
        // A new REPORT (TOKEN) lands right after the assignment.
        assert_eq!(new, vec![1]);
        assert!(matches!(&f.nodes[0], FlowNode::Assign { key, .. } if key == "TOKEN"));
        match &f.nodes[1] {
            FlowNode::Report(ReportStmt::Vars(vars)) => {
                assert_eq!(vars, &vec!["TOKEN".to_string()])
            }
            other => panic!("expected REPORT (TOKEN), got {other:?}"),
        }
        // The assignment survives (it still defines the variable), and the
        // request that followed is pushed down by one.
        assert!(matches!(&f.nodes[2], FlowNode::Request { .. }));
    }

    #[test]
    fn report_assignment_is_a_no_op_on_a_non_assignment() {
        let mut f = flow("REQUEST A\n");
        assert!(report_assignment(&mut f, &[0]).is_none());
        assert_eq!(f.nodes.len(), 1);
    }

    #[test]
    fn report_assignment_is_idempotent_when_already_reported() {
        let mut f = flow("TOKEN=abc\n");
        let first = report_assignment(&mut f, &[0]).expect("assign is reportable");
        assert_eq!(first, vec![1]);
        assert_eq!(f.nodes.len(), 2);
        // Dropping REPORT again selects the existing report line instead of
        // stacking a duplicate column.
        let again = report_assignment(&mut f, &[0]).expect("still reportable");
        assert_eq!(again, vec![1]);
        assert_eq!(f.nodes.len(), 2);
    }

    #[test]
    fn set_env_role_rewrites_one_live_environment_reference() {
        let mut f =
            flow("FOR E IN ENVS BASELINE(\"prod\"), COMPARISON(\"stage\")\n    REQUEST A\nEND\n");
        // Repoint the comparison env; the baseline is untouched.
        assert!(set_env_role(&mut f, &[0], false, 0, "canary"));
        match &f.nodes[0] {
            FlowNode::ForEnvs {
                clause:
                    EnvClause::Roles {
                        baseline,
                        comparisons,
                        ..
                    },
                ..
            } => {
                assert_eq!(baseline, &vec![RoleRef::Env("prod".into())]);
                assert_eq!(comparisons, &vec![RoleRef::Env("canary".into())]);
            }
            other => panic!("expected an ENVS compare loop, got {other:?}"),
        }
    }

    #[test]
    fn set_env_role_leaves_file_snapshots_and_plain_loops_alone() {
        // A FILE(…) snapshot ref is not a live env name, so it is not rewritten.
        let mut f = flow(
            "FOR E IN ENVS BASELINE(FILE(\"snap.baseline\")), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        );
        assert!(!set_env_role(&mut f, &[0], true, 0, "prod"));
        // A plain (non-compare) ENVS loop has no role lists to edit.
        let mut g = flow("FOR E IN ENVS \"dev\", \"prod\"\n    REQUEST A\nEND\n");
        assert!(!set_env_role(&mut g, &[0], false, 0, "stage"));
    }

    #[test]
    fn set_report_alias_sets_clears_and_requires() {
        // A report request's alias is optional: set, then clear with "".
        let mut f = flow("REPORT REQUEST analyze AS Result\n");
        assert!(set_report_alias(&mut f, &[0], "Renamed"));
        assert!(matches!(
            node_at(&f, &[0]),
            Some(FlowNode::Report(ReportStmt::Request { alias: Some(a), .. })) if a == "Renamed"
        ));
        assert!(set_report_alias(&mut f, &[0], "   "));
        assert!(matches!(
            node_at(&f, &[0]),
            Some(FlowNode::Report(ReportStmt::Request { alias: None, .. }))
        ));

        // A reported-variable column's name is required: empty is rejected.
        let mut g = flow("REPORT userId AS Id\n");
        assert!(set_report_alias(&mut g, &[0], "UserId"));
        assert!(matches!(
            node_at(&g, &[0]),
            Some(FlowNode::Report(ReportStmt::VarAs { name, .. })) if name == "UserId"
        ));
        assert!(!set_report_alias(&mut g, &[0], ""));
        assert!(matches!(
            node_at(&g, &[0]),
            Some(FlowNode::Report(ReportStmt::VarAs { name, .. })) if name == "UserId"
        ));
    }

    #[test]
    fn add_and_set_with_field_edit_the_with_block() {
        let mut f = flow("REPORT REQUEST analyze RESPONSE PRETTY\n");
        // Append two fields; indices come back in order.
        assert_eq!(
            add_with_field(&mut f, &[0], "Status", "HttpStatus", Vec::new()),
            Some(0)
        );
        assert_eq!(
            add_with_field(&mut f, &[0], "Body", "jsonpath \"$.x\"", Vec::new()),
            Some(1)
        );
        match node_at(&f, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request { with, .. })) => assert_eq!(with.len(), 2),
            other => panic!("expected a report request, got {other:?}"),
        }
        // Rewrite the first field's name/query/statistics in place.
        assert!(set_with_field(
            &mut f,
            &[0],
            0,
            "Code",
            "HttpStatus",
            vec![StatKind::Count, StatKind::Mean],
            &ClauseForm::default(),
        ));
        match node_at(&f, &[0]) {
            Some(FlowNode::Report(ReportStmt::Request { with, .. })) => {
                assert!(matches!(
                    &with[0],
                    WithItem::Field {
                        name, query, stats, ..
                    }
                        if name == "Code"
                            && query == "HttpStatus"
                            && stats == &[StatKind::Count, StatKind::Mean]
                ));
            }
            other => panic!("expected a report request, got {other:?}"),
        }
        assert!(f.to_text().contains("STATISTICS(COUNT, MEAN)"));

        // Clearing the checklist drops the clause entirely.
        assert!(set_with_field(
            &mut f,
            &[0],
            0,
            "Code",
            "HttpStatus",
            Vec::new(),
            &ClauseForm::default(),
        ));
        assert!(!f.to_text().contains("STATISTICS"));

        // A non-request node has no WITH block to add to.
        let mut g = flow("REPORT userId\n");
        assert_eq!(add_with_field(&mut g, &[0], "X", "Y", Vec::new()), None);
        assert!(!set_with_field(
            &mut g,
            &[0],
            0,
            "X",
            "Y",
            Vec::new(),
            &ClauseForm::default()
        ));
    }
}

#[cfg(test)]
mod repeatable_header_tests {
    use super::*;
    use crate::report::parser::parse_flow;

    fn flow(src: &str) -> ReportFlow {
        parse_flow(src).expect("parses")
    }

    /// The bug `set_header_nth` exists to avoid: editing helper 1 must not
    /// rewrite the primary collection.
    #[test]
    fn editing_a_helper_leaves_the_primary_collection_alone() {
        let mut f = flow("# collection: ./api.hurl\n# collection: ./a.hurl AS a\n\nREQUEST x\n");
        assert!(set_header_nth(
            &mut f,
            "collection",
            1,
            Some("./b.hurl AS b")
        ));
        let all = f.header.get_all("collection");
        assert_eq!(all, vec!["./api.hurl", "./b.hurl AS b"]);
    }

    #[test]
    fn clearing_one_helper_keeps_the_others() {
        let mut f = flow(
            "# collection: ./api.hurl\n# collection: ./a.hurl AS a\n# collection: ./b.hurl AS b\n\nREQUEST x\n",
        );
        assert!(set_header_nth(&mut f, "collection", 1, None));
        assert_eq!(
            f.header.get_all("collection"),
            vec!["./api.hurl", "./b.hurl AS b"]
        );
    }

    /// Setting an occurrence that doesn't exist yet appends one, which is how
    /// the editors' "add a helper collection" works.
    #[test]
    fn setting_past_the_end_appends_another_directive() {
        let mut f = flow("# collection: ./api.hurl\n\nREQUEST x\n");
        assert!(set_header_nth(
            &mut f,
            "collection",
            1,
            Some("./h.hurl AS h")
        ));
        assert_eq!(
            f.header.get_all("collection"),
            vec!["./api.hurl", "./h.hurl AS h"]
        );
        // And it lands in the header block, above the flow.
        assert!(
            f.to_text()
                .starts_with("# collection: ./api.hurl\n# collection: ./h.hurl AS h\n"),
            "{:?}",
            f.to_text()
        );
    }

    /// `set_header` keeps its old first-match-wins meaning for the directives
    /// that only ever appear once.
    #[test]
    fn set_header_still_edits_the_first_occurrence() {
        let mut f = flow("# collection: ./api.hurl\n# collection: ./a.hurl AS a\n\nREQUEST x\n");
        assert!(set_header_nth(&mut f, "collection", 0, Some("./new.hurl")));
        assert_eq!(
            f.header.get_all("collection"),
            vec!["./new.hurl", "./a.hurl AS a"]
        );
    }

    // ---- the USING(…) requirement checklist -----------------------------

    fn ov(target: &str, value: &str) -> UsingItem {
        UsingItem::Override {
            target: crate::report::flow::OverrideTarget::parse(target).unwrap(),
            value: value.into(),
        }
    }

    fn decl(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(a, b)| (a.to_string(), b.to_string()))
            .collect()
    }

    /// The override rows a node form edits are the clause's non-requirement
    /// items, and they go back out unchanged — a round trip through the form
    /// must not rewrite what the source view wrote.
    #[test]
    fn override_rows_round_trip_through_the_form() {
        let using = vec![
            UsingItem::Require("FILE".into()),
            ov("multipart.document", "{{FILE}}"),
            ov("header.X-Trace", "abc"),
        ];
        let rows = override_rows(&using);
        assert_eq!(
            rows.iter()
                .map(|r| (r.target.as_str(), r.value.as_str()))
                .collect::<Vec<_>>(),
            vec![
                ("multipart.document", "{{FILE}}"),
                ("header.X-Trace", "abc")
            ],
            "the requirement is not an override"
        );
        assert_eq!(override_items(&rows), using[1..].to_vec());
    }

    /// A half-typed target is not yet wrong; one that can never name a part of
    /// a request is, and the front-ends paint it so.
    #[test]
    fn a_target_is_wrong_only_once_it_cannot_work() {
        assert!(
            override_target_valid(""),
            "an empty box isn't filled in yet"
        );
        assert!(override_target_valid("multipart.document"));
        assert!(override_target_valid("url"));
        assert!(!override_target_valid("multipart"), "a section needs a key");
        assert!(!override_target_valid("nonsense.x"));
    }

    /// A row that names nothing is dropped rather than written out as a clause
    /// that wouldn't parse.
    #[test]
    fn an_unusable_override_row_never_reaches_the_clause() {
        let rows = vec![
            OverrideRow {
                target: "multipart.document".into(),
                value: "{{FILE}}".into(),
            },
            OverrideRow::default(),
            OverrideRow {
                target: "nonsense.x".into(),
                value: "v".into(),
            },
        ];
        assert_eq!(
            override_items(&rows),
            vec![ov("multipart.document", "{{FILE}}")]
        );
    }

    /// The whole clause a node form describes: ticked requirements first, then
    /// the overrides it edited.
    #[test]
    fn a_form_builds_requirements_and_overrides_into_one_clause() {
        let params = param_rows(
            &decl(&[("FILE", "./s.pdf")]),
            &[UsingItem::Require("FILE".into())],
        );
        let rows = vec![OverrideRow {
            target: "header.X-Trace".into(),
            value: "{{ID}}".into(),
        }];
        let out = using_items(&params, &override_items(&rows));
        assert_eq!(
            out.iter().map(UsingItem::text).collect::<Vec<_>>(),
            vec!["FILE", "header.X-Trace = \"{{ID}}\""]
        );
    }

    /// Every declared parameter gets a row, ticked only when the clause
    /// requires it — the checklist is the request's parameters, not the
    /// statement's, so an unused one is still offered.
    #[test]
    fn the_checklist_offers_every_declared_parameter_and_ticks_the_required_ones() {
        let rows = param_rows(
            &decl(&[("FILE", "./sample.pdf"), ("KIND", "invoice")]),
            &[UsingItem::Require("FILE".into())],
        );
        let seen: Vec<(&str, bool, Option<&str>)> = rows
            .iter()
            .map(|r| (r.name.as_str(), r.required, r.default.as_deref()))
            .collect();
        assert_eq!(
            seen,
            vec![
                ("FILE", true, Some("./sample.pdf")),
                ("KIND", false, Some("invoice")),
            ]
        );
    }

    /// A requirement the request doesn't declare is the validation error the
    /// feature exists to raise. It still gets a row — with no default, which is
    /// how the form shows it as wrong — so it can be un-ticked where it is seen.
    #[test]
    fn a_requirement_the_request_does_not_declare_is_kept_as_an_undeclared_row() {
        let rows = param_rows(
            &decl(&[("FILE", "./x")]),
            &[UsingItem::Require("NOPE".into())],
        );
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[1].name, "NOPE");
        assert!(rows[1].required);
        assert!(
            rows[1].default.is_none(),
            "no default is what marks the row as undeclared"
        );
    }

    /// Overrides have no row, so rebuilding the clause from the checklist must
    /// carry them through untouched — the exact way the form could otherwise
    /// silently delete what the source view wrote.
    #[test]
    fn rebuilding_the_clause_preserves_the_overrides_the_checklist_has_no_row_for() {
        let carried = vec![
            UsingItem::Require("FILE".into()),
            ov("multipart.document", "{{FILE}}"),
            ov("header.X-Run", "{{RUN}}"),
        ];
        let rows = param_rows(&decl(&[("FILE", "./x")]), &carried);
        let out = using_items(&rows, &carried);
        assert_eq!(
            out.iter().map(UsingItem::text).collect::<Vec<_>>(),
            vec![
                "FILE".to_string(),
                "multipart.document = \"{{FILE}}\"".to_string(),
                "header.X-Run = \"{{RUN}}\"".to_string(),
            ]
        );
    }

    /// Un-ticking drops only that requirement, and ticking adds one — the
    /// overrides are untouched either way.
    #[test]
    fn ticking_and_unticking_only_moves_requirements() {
        let carried = vec![UsingItem::Require("FILE".into()), ov("header.X-Run", "1")];
        let mut rows = param_rows(&decl(&[("FILE", "./x"), ("KIND", "invoice")]), &carried);
        rows[0].required = false;
        rows[1].required = true;
        assert_eq!(
            using_items(&rows, &carried)
                .iter()
                .map(UsingItem::text)
                .collect::<Vec<_>>(),
            vec!["KIND".to_string(), "header.X-Run = \"1\"".to_string()]
        );
    }

    /// Requirements are grouped first even when the source wrote them last, so
    /// the checklist and the text read the same way round.
    #[test]
    fn rebuilding_groups_the_requirements_before_the_overrides() {
        let carried = vec![ov("header.X-Run", "1"), UsingItem::Require("FILE".into())];
        let rows = param_rows(&decl(&[("FILE", "./x")]), &carried);
        assert_eq!(
            using_items(&rows, &carried)
                .iter()
                .map(UsingItem::text)
                .collect::<Vec<_>>(),
            vec!["FILE".to_string(), "header.X-Run = \"1\"".to_string()]
        );
    }

    /// A request that declares nothing and a clause that requires nothing give
    /// no rows at all — both front-ends hide the whole section on that.
    #[test]
    fn an_ordinary_request_has_no_checklist() {
        assert!(param_rows(&[], &[]).is_empty());
        assert!(param_rows(&[], &[ov("url", "http://x")]).is_empty());
    }
}