paperboy 0.4.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
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
//! The structured ("node") editor for PaperTrail report flows — the TUI-native
//! realisation of the "Scratch-like" authoring goal.
//!
//! A report flow is a linear/nested list of statements (an outline), so instead
//! of a mouse-driven block canvas (which fits a GUI, not a terminal) the node
//! editor renders the flow's [`ReportFlow`] AST as a **navigable outline** and
//! lets the user assemble it by inserting / removing / moving whole *nodes*
//! rather than typing text. It delivers Scratch's real goals natively — you can
//! only build valid structures, request names come from a picker seeded by the
//! bound collection, and the node kinds are discoverable from a palette.
//!
//! Both editor views (this one and the source text editor in `reports.rs`) are
//! front-ends over the *same* AST: every structural edit re-serializes the AST
//! back into `report.text` via [`ReportFlow::to_text`], so the two round-trip
//! and a future GUI can reuse the AST and these helpers unchanged.

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use super::app::{
    FileAction, MouseHitTarget, MouseLayer, MouseScrollTarget, Overlay, PromptKind, TuiApp,
};
use super::draw::panel;
use super::editor::Editor;
use super::new_request::draw_scrollbar;
use super::theme::Theme;
use crate::i18n::{Status, Strings};
use crate::report::flow::{
    Element, EnvClause, FlowNode, ImageSpec, ParallelSpec, Pattern, Producer, ReportStmt,
    ResponseFmt, RoleBinding, RoleRef, ShowField, WithItem,
};
use crate::report::model::StatKind;

// The pure structural-editing core (flatten/insert/remove/move/replace/parse
// of the flow AST, plus the node-kind palette templates) lives in the
// front-end-agnostic `report::edit` module so the GUI's block editor shares
// one implementation. Re-export it under the historical names so this file's
// TUI-specific rendering / key handling / overlays read unchanged.
pub(crate) use crate::report::edit::{
    ClauseForm, DetachWhich, HEADER_PLACEHOLDER, HeaderKind, InsertPos, NodeKind, NodeRow, RowKind,
    detach_modifier, flatten_expanded, header_specs, header_unset, insert_node, insert_pos_after,
    loop_producer_dir, loop_producer_dir_mut, move_node, node_at, node_at_mut, node_with_items,
    parse_one_node, remove_node, replace_node, request_node,
};

/// The two-step insert/pick palette overlay ([`Overlay::ReportNodeMenu`]).
pub(crate) struct NodeMenu {
    pub(crate) step: NodeMenuStep,
    /// The rows shown: node-kind labels in `PickKind`, request titles in
    /// `PickRequest`.
    pub(crate) options: Vec<String>,
    pub(crate) selected: usize,
    /// Where a newly created node is inserted (ignored when `edit_path` is set).
    pub(crate) pos: InsertPos,
    /// The report being edited (looked up by id so a tab reorder can't misroute).
    pub(crate) report_id: u64,
    /// In `PickRequest`: whether we're building a `REPORT REQUEST` (`true`) or a
    /// plain `REQUEST` (`false`).
    pub(crate) report_kind: bool,
    /// When `Some`, we're changing an existing request node's name at this path
    /// rather than inserting a new node.
    pub(crate) edit_path: Option<Vec<usize>>,
}

/// Which step the [`NodeMenu`] is on.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum NodeMenuStep {
    /// Choosing a node kind to insert.
    PickKind,
    /// Choosing a request name (for `REQUEST` / `REPORT REQUEST`).
    PickRequest,
}

impl NodeMenu {
    /// The overlay title for the current step.
    pub(crate) fn title<'a>(&self, s: &'a Strings) -> &'a str {
        match self.step {
            NodeMenuStep::PickKind => s.node_menu_title,
            NodeMenuStep::PickRequest => s.node_pick_request_title,
        }
    }
}

/// One selectable field in the reported-request form's field checklist.
pub(crate) struct ShowRow {
    pub(crate) name: String,
    pub(crate) included: bool,
}

/// One visible row of a [`RequestForm`]. The layout is dynamic: a plain
/// `REQUEST` shows only Name + Report; ticking Report reveals the reporting
/// options (response format, alias, and the field checklist).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum FormRow {
    /// The request name (cycles through the bound collection's request titles).
    Name,
    /// The `REPORT` toggle — off = plain `REQUEST`, on = `REPORT REQUEST`.
    Report,
    /// The `RESPONSE RAW/PRETTY` override (only when reporting).
    Response,
    /// The `AS <alias>` namespace (only when reporting).
    Alias,
    /// A `SHOW(…)` field checkbox (index into [`RequestForm::fields`]).
    Field(usize),
    /// A `HIDE(…)` field checkbox (index into [`RequestForm::hide_fields`]).
    Hidden(usize),
    /// One `WITH name: query` field (index into [`RequestForm::with`]).
    /// Activating it opens the [`WithFieldForm`].
    With(usize),
    /// The "add a `WITH` field" row, which opens an empty [`WithFieldForm`].
    AddWith,
}

/// The request configure form ([`Overlay::ReportNodeRequest`]), reached with
/// Enter on a `REQUEST` / `REPORT REQUEST` node: one place to pick the request
/// name, toggle whether it's *reported* (`REPORT`), and — when reported — shape
/// how (its response format `RESPONSE RAW/PRETTY`, its column namespace
/// `AS <alias>`, and which of the fields it can emit are shown via `SHOW(…)`,
/// e.g. to drop a noisy base64 `Response`).
pub(crate) struct RequestForm {
    /// The report being edited (looked up by id, resilient to tab reorder).
    pub(crate) report_id: u64,
    /// Path of the node this edits.
    pub(crate) path: Vec<usize>,
    /// The request name.
    pub(crate) request: String,
    /// Candidate request titles from the bound collection (Name row cycles
    /// through these). Empty when unbound/unresolved.
    pub(crate) titles: Vec<String>,
    /// Whether this is a `REPORT REQUEST` (`true`) or a plain `REQUEST`.
    pub(crate) report: bool,
    /// The `RESPONSE` override: `None` = default (no clause), else RAW/PRETTY.
    pub(crate) response: Option<ResponseFmt>,
    /// The `AS <alias>` namespace; empty = no alias (default = the request name).
    pub(crate) alias: String,
    /// The `SHOW(…)` field checklist.
    pub(crate) fields: Vec<ShowRow>,
    /// Any `STATISTICS(…)` the `SHOW(…)` fields carried, kept so editing the
    /// checklist can't silently delete a clause the form has no row for — the
    /// same carry-through rule the `IMAGE`/`TRUTH` clauses get.
    pub(crate) show_stats: std::collections::HashMap<String, Vec<StatKind>>,
    /// The node's `WITH … END` items, preserved verbatim across an edit (the
    /// form doesn't edit them, but must not drop them when re-serializing).
    pub(crate) with: Vec<WithItem>,
    /// The `HIDE(…)` checklist, over the same field names as [`Self::fields`].
    /// A ticked row is *hidden*; nothing ticked ⇒ no `HIDE` clause. `SHOW` and
    /// `HIDE` are separate clauses in the grammar, so they get separate lists
    /// rather than one tri-state per field.
    pub(crate) hide_fields: Vec<ShowRow>,
    /// Selected row: an index into [`Self::visible_rows`] (clamped on use).
    pub(crate) selected: usize,
}

impl RequestForm {
    /// Build the form for a request node. Field rows are the fields the request
    /// can emit, in canonical output order (intrinsics, then its `[Reports]`
    /// fields, then the node's `WITH` fields), de-duplicated. A field is ticked
    /// when the current `show` is empty (no clause ⇒ all emitted) or names it;
    /// any unknown `show` entry is kept as a ticked row so applying can't
    /// silently drop it.
    #[allow(clippy::too_many_arguments)]
    fn build(
        report_id: u64,
        path: Vec<usize>,
        request: String,
        titles: Vec<String>,
        report: bool,
        alias: Option<String>,
        response: Option<ResponseFmt>,
        current_show: &[ShowField],
        report_fields: &[String],
        with: Vec<WithItem>,
        hide: Vec<String>,
    ) -> Self {
        let with_fields: Vec<String> = with
            .iter()
            .filter_map(|w| match w {
                WithItem::Field { name, .. } => Some(name.clone()),
                _ => None,
            })
            .collect();
        let mut names: Vec<String> = Vec::new();
        let push = |name: &str, names: &mut Vec<String>| {
            if !names.iter().any(|n| n == name) {
                names.push(name.to_string());
            }
        };
        for f in crate::report::run::INTRINSIC_FIELDS {
            push(f, &mut names);
        }
        for f in report_fields {
            push(f, &mut names);
        }
        for f in &with_fields {
            push(f, &mut names);
        }
        // Preserve any unknown SHOW entry so applying can't drop it.
        for f in current_show {
            push(f.name(), &mut names);
        }
        // A `HIDE` entry naming something no request offers is kept too, for
        // the same reason: applying must not drop what the user wrote.
        for f in &hide {
            push(f, &mut names);
        }
        // No SHOW clause means "everything this request already emits" — which
        // excludes the opt-in timing intrinsics, so they must start un-ticked or
        // simply opening and applying the form would switch them on.
        let all = current_show.is_empty();
        let fields: Vec<ShowRow> = names
            .iter()
            .map(|name| {
                let included = (all
                    && !crate::report::run::OPT_IN_INTRINSIC_FIELDS.contains(&name.as_str()))
                    || current_show.iter().any(|s| s.name() == name);
                ShowRow {
                    name: name.clone(),
                    included,
                }
            })
            .collect();
        let hide_fields = names
            .iter()
            .map(|name| ShowRow {
                name: name.clone(),
                included: hide.iter().any(|h| h == name),
            })
            .collect();
        RequestForm {
            report_id,
            path,
            request,
            titles,
            report,
            // Carried, never edited: the checklist has no row for a statistic.
            show_stats: current_show
                .iter()
                .filter(|f| !f.stats.is_empty())
                .map(|f| (f.field.clone(), f.stats.clone()))
                .collect(),
            response,
            alias: alias.unwrap_or_default(),
            fields,
            with,
            hide_fields,
            selected: 0,
        }
    }

    /// The rows currently on screen, in order. Reporting-only rows (response,
    /// alias, field checklist) appear only when [`Self::report`] is set.
    pub(crate) fn visible_rows(&self) -> Vec<FormRow> {
        let mut rows = vec![FormRow::Name, FormRow::Report];
        if self.report {
            rows.push(FormRow::Response);
            rows.push(FormRow::Alias);
            rows.extend((0..self.fields.len()).map(FormRow::Field));
            rows.extend((0..self.hide_fields.len()).map(FormRow::Hidden));
            rows.extend((0..self.with.len()).map(FormRow::With));
            rows.push(FormRow::AddWith);
        }
        rows
    }

    /// The `HIDE(…)` list for the ticked rows, in row order. Nothing ticked ⇒
    /// no clause (unlike `SHOW`, where *everything* ticked is the no-clause
    /// case — `HIDE` hides only what it names).
    fn hide(&self) -> Vec<String> {
        self.hide_fields
            .iter()
            .filter(|r| r.included)
            .map(|r| r.name.clone())
            .collect()
    }

    /// The last selectable row index.
    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// The `SHOW(…)` field list for the ticked rows, in row order. When the
    /// ticked set is exactly what the request emits with no clause — every
    /// field except the opt-in timing intrinsics — it returns empty (⇒ no
    /// `SHOW` clause), so leaving the form as it opened removes any existing
    /// clause rather than freezing the current selection into one.
    fn show(&self) -> Vec<ShowField> {
        if self.fields.iter().all(|r| {
            r.included != crate::report::run::OPT_IN_INTRINSIC_FIELDS.contains(&r.name.as_str())
        }) {
            return Vec::new();
        }
        self.fields
            .iter()
            .filter(|r| r.included)
            .map(|r| ShowField {
                field: r.name.clone(),
                stats: self.show_stats.get(&r.name).cloned().unwrap_or_default(),
            })
            .collect()
    }

    /// The `AS <alias>` value, `None` when blank.
    fn alias_opt(&self) -> Option<String> {
        let a = self.alias.trim();
        if a.is_empty() {
            None
        } else {
            Some(a.to_string())
        }
    }

    /// Cycle the request name through the bound collection's titles (a no-op
    /// when there are none). Wraps; starts at the first title when the current
    /// name isn't one of them.
    fn cycle_name(&mut self, forward: bool) {
        let n = self.titles.len();
        if n == 0 {
            return;
        }
        let next = match self.titles.iter().position(|t| t == &self.request) {
            Some(i) if forward => (i + 1) % n,
            Some(i) => (i + n - 1) % n,
            None => 0,
        };
        self.request = self.titles[next].clone();
    }

    /// Cycle the response-format override: Default → RAW → PRETTY → Default
    /// (reverse when `forward` is false).
    fn cycle_response(&mut self, forward: bool) {
        self.response = if forward {
            match self.response {
                None => Some(ResponseFmt::Raw),
                Some(ResponseFmt::Raw) => Some(ResponseFmt::Pretty),
                Some(ResponseFmt::Pretty) => None,
            }
        } else {
            match self.response {
                None => Some(ResponseFmt::Pretty),
                Some(ResponseFmt::Pretty) => Some(ResponseFmt::Raw),
                Some(ResponseFmt::Raw) => None,
            }
        };
    }
}

/// One row of the [`VarsForm`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum VarsRow {
    /// One in-scope variable checkbox (index into [`VarsForm::vars`]).
    Var(usize),
    /// The free-text row for a variable the static scan can't see (a value
    /// that only exists at run time, or one supplied by the environment).
    Other,
    /// The `AS <name>` column name — only offered when exactly one variable is
    /// picked, since `REPORT (A, B)` has no single column to name.
    Alias,
    /// One `STATISTICS(…)` checkbox — likewise single-variable only.
    Stat(usize),
    /// One row of the shared trailing-clause block ([`ClauseRow`]) — likewise
    /// single-variable only, since the clauses attach to a column.
    Clause(ClauseRow),
}

/// The `REPORT <var>` configure form ([`Overlay::ReportNodeVars`]): which
/// variables become columns, and — for a single variable — the `AS <name>`
/// column name and its `STATISTICS(…)`.
///
/// The two grammar forms it writes are `REPORT (A, B)` for several variables
/// and `REPORT A AS name STATISTICS(…)` for one, so the alias and stat rows
/// appear and disappear with the number ticked rather than being written into
/// a shape that can't hold them.
pub(crate) struct VarsForm {
    pub(crate) report_id: u64,
    pub(crate) path: Vec<usize>,
    /// `(name, ticked)` over the variables in scope at this point in the flow,
    /// plus anything the statement already names.
    pub(crate) vars: Vec<ShowRow>,
    /// A variable typed by hand, for the run-time-only names the static scan
    /// can't enumerate (see [`crate::report::edit::vars_in_scope`]).
    pub(crate) other: String,
    pub(crate) alias: String,
    pub(crate) stats: Vec<(StatKind, bool)>,
    /// The `TRUTH`/`IMAGE`/`DETAIL` clause block, as edited.
    pub(crate) clauses: ClauseForm,
    pub(crate) selected: usize,
}

impl VarsForm {
    /// Build the form from the statement's current variables and the names in
    /// scope. Anything the statement already names is ticked and kept, even if
    /// it isn't in scope — applying must never drop what the user wrote.
    fn build(
        report_id: u64,
        path: Vec<usize>,
        chosen: &[String],
        alias: Option<String>,
        stats: &[StatKind],
        image: Option<ImageSpec>,
        truth: Option<String>,
        detail: bool,
        in_scope: Vec<String>,
    ) -> Self {
        let mut names = in_scope;
        for c in chosen {
            if !names.iter().any(|n| n == c) {
                names.push(c.clone());
            }
        }
        VarsForm {
            clauses: ClauseForm::of(image, truth.as_deref(), detail),
            report_id,
            path,
            vars: names
                .into_iter()
                .map(|name| {
                    let included = chosen.iter().any(|c| c == &name);
                    ShowRow { name, included }
                })
                .collect(),
            other: String::new(),
            alias: alias.unwrap_or_default(),
            stats: StatKind::CHOOSABLE
                .iter()
                .map(|k| (*k, stats.contains(k)))
                .collect(),
            selected: 0,
        }
    }

    /// The ticked variables, in row order.
    fn chosen(&self) -> Vec<String> {
        let mut out: Vec<String> = self
            .vars
            .iter()
            .filter(|r| r.included)
            .map(|r| r.name.clone())
            .collect();
        let other = self.other.trim();
        if !other.is_empty() && !out.iter().any(|n| n == other) {
            out.push(other.to_string());
        }
        out
    }

    pub(crate) fn visible_rows(&self) -> Vec<VarsRow> {
        let mut rows: Vec<VarsRow> = (0..self.vars.len()).map(VarsRow::Var).collect();
        rows.push(VarsRow::Other);
        // `AS` and `STATISTICS` belong to `REPORT <var> AS <name>`, which holds
        // exactly one variable.
        if self.chosen().len() == 1 {
            rows.push(VarsRow::Alias);
            rows.extend((0..self.stats.len()).map(VarsRow::Stat));
            rows.extend(clause_rows(&self.clauses).into_iter().map(VarsRow::Clause));
        }
        rows
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// The node the rows describe, or `None` when nothing is picked (a
    /// `REPORT` with no variables can't be serialized).
    fn node(&self) -> Option<FlowNode> {
        let chosen = self.chosen();
        let (first, rest) = chosen.split_first()?;
        let alias = self.alias.trim();
        let stats: Vec<StatKind> = self
            .stats
            .iter()
            .filter(|(_, on)| *on)
            .map(|(k, _)| *k)
            .collect();
        // A single variable with a name or statistics is the `VarAs` form;
        // anything else is the plain variable list.
        let image = self.clauses.image();
        let truth = self.clauses.truth();
        if rest.is_empty()
            && (!alias.is_empty()
                || !stats.is_empty()
                || image.is_some()
                || truth.is_some()
                || self.clauses.detail)
        {
            return Some(FlowNode::Report(ReportStmt::VarAs {
                truth,
                detail: self.clauses.detail,
                var: first.clone(),
                // `STATISTICS` needs a column to attach to, so an unnamed one
                // falls back to the variable's own name.
                name: if alias.is_empty() {
                    first.clone()
                } else {
                    alias.to_string()
                },
                stats,
                image,
            }));
        }
        Some(FlowNode::Report(ReportStmt::Vars(chosen)))
    }
}

/// One row of the [`ComputedForm`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ComputedRow {
    /// The quoted template the column's value is built from.
    Template,
    /// The `AS <name>` column name.
    Alias,
    /// One `STATISTICS(…)` checkbox.
    Stat(usize),
    /// One row of the shared trailing-clause block ([`ClauseRow`]).
    Clause(ClauseRow),
}

/// The `REPORT "<template>" AS <name>` configure form
/// ([`Overlay::ReportNodeComputed`]): a computed column's template, its name
/// and its `STATISTICS(…)`.
///
/// The template is free text because it interpolates `{{ … }}` references —
/// there is nothing to pick from a list — but the name and the statistics are
/// structured, and both are required for the statement to re-parse, which is
/// exactly why typing the whole line by hand was easy to get wrong.
pub(crate) struct ComputedForm {
    pub(crate) report_id: u64,
    pub(crate) path: Vec<usize>,
    pub(crate) template: String,
    pub(crate) alias: String,
    pub(crate) stats: Vec<(StatKind, bool)>,
    /// The `TRUTH`/`IMAGE`/`DETAIL` clause block, as edited.
    pub(crate) clauses: ClauseForm,
    pub(crate) selected: usize,
}

impl ComputedForm {
    pub(crate) fn visible_rows(&self) -> Vec<ComputedRow> {
        let mut rows = vec![ComputedRow::Template, ComputedRow::Alias];
        rows.extend((0..self.stats.len()).map(ComputedRow::Stat));
        rows.extend(
            clause_rows(&self.clauses)
                .into_iter()
                .map(ComputedRow::Clause),
        );
        rows
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// The node the rows describe. `None` when either half is blank: an empty
    /// template or a missing `AS` name won't re-parse, which would kick the
    /// user out of the node editor entirely.
    fn node(&self) -> Option<FlowNode> {
        let template = self.template.trim();
        let alias = self.alias.trim();
        if template.is_empty() || alias.is_empty() {
            return None;
        }
        Some(FlowNode::Report(ReportStmt::Computed {
            truth: self.clauses.truth(),
            detail: self.clauses.detail,
            template: template.to_string(),
            name: alias.to_string(),
            stats: self
                .stats
                .iter()
                .filter(|(_, on)| *on)
                .map(|(k, _)| *k)
                .collect(),
            image: self.clauses.image(),
        }))
    }
}

/// One row of the [`AssignForm`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum AssignRow {
    /// The variable name (`VAR = …`).
    Key,
    /// The value it is set to.
    Value,
}

/// The `VARIABLE = VALUE` configure form ([`Overlay::ReportNodeAssign`]): two
/// free-text rows. It exists so a `SET` line doesn't have to be typed as raw
/// source just to change the value it assigns.
pub(crate) struct AssignForm {
    pub(crate) report_id: u64,
    pub(crate) path: Vec<usize>,
    pub(crate) key: String,
    pub(crate) value: String,
    pub(crate) selected: usize,
}

impl AssignForm {
    pub(crate) fn visible_rows(&self) -> Vec<AssignRow> {
        vec![AssignRow::Key, AssignRow::Value]
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// The node the rows describe, or `None` when the variable is unnamed (an
    /// assignment with no left-hand side can't be serialized).
    fn node(&self) -> Option<FlowNode> {
        let key = self.key.trim();
        (!key.is_empty()).then(|| FlowNode::Assign {
            key: key.to_string(),
            value: self.value.trim().to_string(),
        })
    }
}

/// One row of the [`ListForm`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ListRow {
    /// The list's name (`LIST NAME = [ … ]`).
    Name,
    /// One scalar element (index into [`ListForm::values`]).
    Value(usize),
    /// The "add an element" row.
    Add,
}

/// The `LIST NAME = [ … ]` configure form ([`Overlay::ReportNodeList`]): the
/// list's name and one row per element.
///
/// Only a *literal* list of scalars is edited here — a tuple list or a computed
/// producer (`ZIP`, `CONCAT`, `TUPLES FROM`) has structure this flat form would
/// flatten away, so those fall through to the raw line editor instead.
pub(crate) struct ListForm {
    pub(crate) report_id: u64,
    pub(crate) path: Vec<usize>,
    pub(crate) name: String,
    pub(crate) values: Vec<String>,
    pub(crate) selected: usize,
}

impl ListForm {
    pub(crate) fn visible_rows(&self) -> Vec<ListRow> {
        let mut rows = vec![ListRow::Name];
        rows.extend((0..self.values.len()).map(ListRow::Value));
        rows.push(ListRow::Add);
        rows
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// The node the rows describe, or `None` when the list is unnamed. Blank
    /// element rows are dropped, so deleting an element is just clearing it.
    fn node(&self) -> Option<FlowNode> {
        let name = self.name.trim();
        (!name.is_empty()).then(|| FlowNode::ListDecl {
            name: name.to_string(),
            producer: Producer::List(
                self.values
                    .iter()
                    .map(|v| v.trim())
                    .filter(|v| !v.is_empty())
                    .map(|v| Element::Scalar(v.to_string()))
                    .collect(),
            ),
        })
    }
}

/// One row of the trailing-clause block shared by every named-column form.
///
/// `TRUTH`, `IMAGE` and `DETAIL` attach identically to a `REPORT … AS`, a
/// computed column and a `WITH` field, so all three forms embed this block
/// rather than growing three near-identical sets of rows (and three chances to
/// let one of them drift).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum ClauseRow {
    /// The `TRUTH "…"` template, editable inline. A plain text row rather than
    /// a toggle: it is a value, usually a `{{ … }}` reference to a label the
    /// loop bound, and blank means the column isn't scored.
    Truth,
    /// The `DETAIL` on/off toggle.
    Detail,
    /// The `IMAGE` on/off toggle. Like the `STATISTICS` toggle, the sizing rows
    /// below only exist while it is on -- most columns are not pictures, and
    /// three permanently-showing size rows would bury the two rows every column
    /// actually needs.
    Image,
    /// `FIT`: size to the cell. Only shown while [`ClauseRow::Image`] is on.
    Fit,
    /// `HEIGHT`, typed as digits. Only shown while `IMAGE` is on and `FIT` off,
    /// since `FIT` is what makes a fixed size meaningless.
    Height,
    /// `WIDTH`, likewise.
    Width,
}

/// The clause rows to show for `c`, in order.
pub(crate) fn clause_rows(c: &ClauseForm) -> Vec<ClauseRow> {
    let mut rows = vec![ClauseRow::Truth, ClauseRow::Detail, ClauseRow::Image];
    if c.image_on {
        rows.push(ClauseRow::Fit);
        if !c.fit {
            rows.push(ClauseRow::Height);
            rows.push(ClauseRow::Width);
        }
    }
    rows
}

/// Apply `key` to the clause block. Returns whether the row consumed it, so a
/// form can fall through to its own handling for a row this block doesn't own.
pub(crate) fn clause_key(c: &mut ClauseForm, row: ClauseRow, key: KeyEvent) -> bool {
    // Sizes take digits only: the clause holds pixels, and letting a stray
    // letter in would silently drop the whole size when it failed to parse.
    let digits = |field: &mut String, key: KeyEvent| match key.code {
        KeyCode::Char(ch) if ch.is_ascii_digit() => {
            field.push(ch);
            true
        }
        KeyCode::Backspace => {
            field.pop();
            true
        }
        _ => false,
    };
    match row {
        ClauseRow::Truth => match key.code {
            KeyCode::Char(ch) => {
                c.truth.push(ch);
                true
            }
            KeyCode::Backspace => {
                c.truth.pop();
                true
            }
            _ => false,
        },
        ClauseRow::Detail => {
            if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x')) {
                c.detail = !c.detail;
                return true;
            }
            false
        }
        ClauseRow::Image => {
            if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x')) {
                c.toggle_image();
                return true;
            }
            false
        }
        ClauseRow::Fit => {
            if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x')) {
                c.toggle_fit();
                return true;
            }
            false
        }
        ClauseRow::Height => digits(&mut c.height, key),
        ClauseRow::Width => digits(&mut c.width, key),
    }
}

/// One row of the [`WithFieldForm`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum WithFieldRow {
    /// The column name (`WITH name: …`), editable inline.
    Name,
    /// The Hurl query the column's value comes from, editable inline.
    Query,
    /// One row of the shared trailing-clause block ([`ClauseRow`]).
    Clause(ClauseRow),
    /// The `STATISTICS(…)` on/off toggle. The individual statistic checkboxes
    /// only exist while it is on: most columns want no summary at all, and a
    /// permanently-showing list of six checkboxes buried the two rows that
    /// every field actually needs.
    Stats,
    /// One `STATISTICS(…)` checkbox (index into [`StatKind::CHOOSABLE`]). Only
    /// present while [`WithFieldRow::Stats`] is on.
    Stat(usize),
}

/// The `WITH name: query` field form ([`Overlay::ReportNodeWithField`]): one
/// ad-hoc column of a report request's `WITH … END` block.
///
/// It edits a single field rather than the whole block because a `WITH` item is
/// two free-text values plus a checklist — far more than a row of the request
/// form can carry — and because adding one field at a time is how the block is
/// actually built up.
pub(crate) struct WithFieldForm {
    /// The report being edited (looked up by id, resilient to tab reorder).
    pub(crate) report_id: u64,
    /// Path of the report-request node whose `WITH` block this edits.
    pub(crate) path: Vec<usize>,
    /// The index being edited, or `None` to append a new field.
    pub(crate) index: Option<usize>,
    pub(crate) name: String,
    pub(crate) query: String,
    /// `(stat, ticked)` over [`StatKind::CHOOSABLE`], in that order. None
    /// ticked ⇒ no `STATISTICS(…)` clause.
    pub(crate) stats: Vec<(StatKind, bool)>,
    /// Whether the field carries a `STATISTICS(…)` clause at all — the state of
    /// the [`WithFieldRow::Stats`] toggle, which is what reveals the individual
    /// checkboxes. Held rather than derived from `stats` so that unticking the
    /// last statistic doesn't collapse the list out from under the user; the
    /// two are kept in step by the toggle (see the key handler).
    pub(crate) stats_on: bool,
    /// Where Enter/Esc return to: `true` when this form was opened as a
    /// sub-form of the request form (so it hands back there), `false` when it
    /// was opened straight from a `WITH` row of the node outline, where the
    /// only sensible thing to return to is the outline itself. Getting this
    /// wrong dumped the user into a request form they never asked for.
    pub(crate) return_to_request: bool,
    /// The `TRUTH`/`IMAGE`/`DETAIL` clause block, as edited.
    pub(crate) clauses: ClauseForm,
    /// Selected row: an index into [`Self::visible_rows`] (clamped on use).
    pub(crate) selected: usize,
}

impl WithFieldForm {
    fn build(
        report_id: u64,
        path: Vec<usize>,
        index: Option<usize>,
        existing: Option<&WithItem>,
        return_to_request: bool,
    ) -> Self {
        let (name, query, stats, clauses) = match existing {
            Some(WithItem::Field {
                name,
                query,
                stats,
                image,
                truth,
                detail,
            }) => (
                name.clone(),
                query.clone(),
                stats.clone(),
                ClauseForm::of(*image, truth.as_deref(), *detail),
            ),
            // A bare `WITH RESPONSE` isn't a named field, so editing it falls
            // through to a fresh one rather than silently rewriting it.
            _ => (
                String::new(),
                String::new(),
                Vec::new(),
                ClauseForm::default(),
            ),
        };
        WithFieldForm {
            clauses,
            report_id,
            path,
            index,
            name,
            query,
            stats_on: !stats.is_empty(),
            stats: StatKind::CHOOSABLE
                .iter()
                .map(|k| (*k, stats.contains(k)))
                .collect(),
            return_to_request,
            selected: 0,
        }
    }

    pub(crate) fn visible_rows(&self) -> Vec<WithFieldRow> {
        let mut rows = vec![WithFieldRow::Name, WithFieldRow::Query];
        rows.extend(
            clause_rows(&self.clauses)
                .into_iter()
                .map(WithFieldRow::Clause),
        );
        rows.push(WithFieldRow::Stats);
        if self.stats_on {
            rows.extend((0..self.stats.len()).map(WithFieldRow::Stat));
        }
        rows
    }

    /// Flip the `STATISTICS(…)` clause on or off, keeping the checkboxes in
    /// step with it: turning it on with nothing ticked seeds `COUNT` (the one
    /// statistic that means something for a text column as well as a numeric
    /// one, as elsewhere in the editors), and turning it off clears the ticks,
    /// so a hidden list can never still be contributing a clause.
    fn toggle_stats(&mut self) {
        self.stats_on = !self.stats_on;
        if self.stats_on {
            if !self.stats.iter().any(|(_, on)| *on) {
                let seed = self
                    .stats
                    .iter()
                    .position(|(k, _)| *k == StatKind::Count)
                    .unwrap_or(0);
                if let Some((_, on)) = self.stats.get_mut(seed) {
                    *on = true;
                }
            }
        } else {
            for (_, on) in &mut self.stats {
                *on = false;
            }
        }
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// The field the rows describe, or `None` when it has no name (an unnamed
    /// column can't be written, so the caller leaves the block unchanged).
    fn item(&self) -> Option<WithItem> {
        let name = self.name.trim();
        if name.is_empty() {
            return None;
        }
        Some(WithItem::Field {
            name: name.to_string(),
            query: self.query.trim().to_string(),
            stats: self
                .stats
                .iter()
                .filter(|(_, on)| *on)
                .map(|(k, _)| *k)
                .collect(),
            image: self.clauses.image(),
            detail: self.clauses.detail,
            truth: self.clauses.truth(),
        })
    }
}

/// One row of the [`EnvsForm`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum EnvsRow {
    /// The loop variable name (a free identifier, editable inline).
    Var,
    /// The Iterate (`Plain`) vs Compare (`Roles`) mode toggle.
    Mode,
    /// The `PARALLEL` on/off toggle (run iterations concurrently).
    Parallel,
    /// `PARALLEL(n)`'s max-concurrency, typed as digits. Only shown while
    /// `PARALLEL` is on, since a degree without the marker means nothing.
    Degree,
    /// One environment entry (index into [`EnvsForm::entries`]).
    Env(usize),
    /// One `BASELINE(…) SHOW(…)` field checkbox (index into
    /// [`EnvsForm::baseline_show`]). Compare mode only.
    BaselineShow(usize),
}

/// One chosen environment in the [`EnvsForm`]. `baseline` is only meaningful in
/// Compare mode (at most one entry is the baseline; the rest are comparisons).
/// `file` marks a `FILE("…")` snapshot reference (a saved baseline reused in
/// place of a live run) rather than a loaded environment name.
pub(crate) struct EnvEntry {
    pub(crate) name: String,
    pub(crate) baseline: bool,
    pub(crate) file: bool,
}

/// The `FOR … IN ENVS` configure form ([`Overlay::ReportNodeEnvs`]), reached
/// with Enter on an `ENVS` loop node. It picks the loop variable, the mode
/// (Iterate = `ENVS "a", "b"` vs Compare = `ENVS BASELINE(…), COMPARISON(…)`)
/// and — the point of #11 — the environment names from the *loaded*
/// environments rather than typing them by hand.
pub(crate) struct EnvsForm {
    /// The report being edited (looked up by id, resilient to tab reorder).
    pub(crate) report_id: u64,
    /// Path of the node this edits.
    pub(crate) path: Vec<usize>,
    /// The loop variable name.
    pub(crate) var: String,
    /// `false` = Iterate (`Plain`), `true` = Compare (`Roles`).
    pub(crate) compare: bool,
    /// `true` when the loop is marked `PARALLEL` (iterations run concurrently).
    pub(crate) parallel: bool,
    /// The chosen environments, in row order.
    pub(crate) entries: Vec<EnvEntry>,
    /// Loaded environment names the env rows cycle through (empty ⇒ no picker).
    pub(crate) choices: Vec<String>,
    /// Discovered `.baseline` snapshot paths (relative to the report root) that a
    /// `FILE(…)` role entry cycles through — the file analogue of [`Self::choices`].
    /// Seeded from the report directory plus any snapshot paths already in the
    /// clause, so an existing `FILE(…)` value is always in the cycle.
    pub(crate) snapshots: Vec<String>,
    /// Any `STATISTICS(…)` the `BASELINE(…) SHOW(…)` fields carried — carried
    /// through untouched, like [`RequestForm::show_stats`].
    pub(crate) show_stats: std::collections::HashMap<String, Vec<StatKind>>,
    /// Selected row: an index into [`Self::visible_rows`] (clamped on use).
    pub(crate) selected: usize,
    /// `PARALLEL(n)`'s max-concurrency as typed text, so the row can be left
    /// blank (meaning "use the prelude's `MAX_PARALLEL`") and half-typed input
    /// isn't clamped under the cursor.
    pub(crate) degree: String,
    /// `BASELINE(…) SHOW(…)` as a checklist over every field the loop body's
    /// reported requests can emit. Nothing ticked means *no* `SHOW` clause,
    /// which for a baseline is "carry nothing across" — the opposite of a
    /// request's `SHOW`, where empty means "emit everything". So nothing is
    /// ticked by default.
    pub(crate) baseline_show: Vec<ShowRow>,
}

impl EnvsForm {
    /// Build the form from a node's current variable and [`EnvClause`].
    /// `choices` are the loaded environment names an env entry cycles through;
    /// `snapshots` are the discovered `.baseline` paths a `FILE(…)` entry cycles.
    #[allow(clippy::too_many_arguments)]
    fn build(
        report_id: u64,
        path: Vec<usize>,
        var: String,
        clause: &EnvClause,
        parallel: Option<ParallelSpec>,
        choices: Vec<String>,
        mut snapshots: Vec<String>,
        show_choices: Vec<(String, bool)>,
    ) -> Self {
        let (compare, mut entries, baseline_show_names) = match clause {
            EnvClause::Plain(names) => (
                false,
                names
                    .iter()
                    .map(|n| EnvEntry {
                        name: n.clone(),
                        baseline: false,
                        file: false,
                    })
                    .collect::<Vec<_>>(),
                Vec::new(),
            ),
            EnvClause::Roles {
                baseline,
                comparisons,
                baseline_show,
            } => {
                let entry = |r: &RoleRef, is_baseline: bool| EnvEntry {
                    name: r.target().to_string(),
                    baseline: is_baseline,
                    file: matches!(r, RoleRef::File(_)),
                };
                let mut es: Vec<EnvEntry> = baseline.iter().map(|r| entry(r, true)).collect();
                es.extend(comparisons.iter().map(|r| entry(r, false)));
                (true, es, baseline_show.clone())
            }
        };
        // Ensure any snapshot path already used by a FILE entry is in the cycle,
        // even if it no longer exists on disk (so an existing value survives and
        // is reachable by cycling).
        for e in &entries {
            if e.file && !e.name.trim().is_empty() && !snapshots.iter().any(|s| s == &e.name) {
                snapshots.push(e.name.clone());
            }
        }
        // The clause always keeps at least one entry so it can't serialize to an
        // empty (unparseable) `FOR VAR IN ENVS `.
        if entries.is_empty() {
            entries.push(EnvEntry {
                name: choices.first().cloned().unwrap_or_default(),
                baseline: compare,
                file: false,
            });
        }
        // The checklist is built by the caller (it needs the loop body and the
        // bound collection); anything the clause already names but the body no
        // longer offers is appended there, so applying can't silently drop a
        // field the user wrote by hand.
        let mut baseline_show: Vec<ShowRow> = show_choices
            .into_iter()
            .map(|(name, included)| ShowRow { name, included })
            .collect();
        let show_stats: std::collections::HashMap<String, Vec<StatKind>> = baseline_show_names
            .iter()
            .filter(|f| !f.stats.is_empty())
            .map(|f| (f.field.clone(), f.stats.clone()))
            .collect();
        for f in &baseline_show_names {
            if !baseline_show.iter().any(|r| r.name == f.field) {
                baseline_show.push(ShowRow {
                    name: f.field.clone(),
                    included: true,
                });
            }
        }
        EnvsForm {
            report_id,
            path,
            var,
            show_stats,
            compare,
            parallel: parallel.is_some(),
            degree: parallel
                .and_then(|p| p.degree)
                .map(|d| d.to_string())
                .unwrap_or_default(),
            entries,
            choices,
            snapshots,
            selected: 0,
            baseline_show,
        }
    }

    pub(crate) fn visible_rows(&self) -> Vec<EnvsRow> {
        let mut rows = vec![EnvsRow::Var, EnvsRow::Mode, EnvsRow::Parallel];
        if self.parallel {
            rows.push(EnvsRow::Degree);
        }
        rows.extend((0..self.entries.len()).map(EnvsRow::Env));
        // `SHOW` selects what the baseline carries across into the comparison,
        // so it only exists in Compare mode — and only once there is a baseline
        // for it to qualify.
        if self.compare && self.entries.iter().any(|e| e.baseline) {
            rows.extend((0..self.baseline_show.len()).map(EnvsRow::BaselineShow));
        }
        rows
    }

    /// The `PARALLEL` spec the rows describe: `None` when the toggle is off,
    /// else the typed degree (a blank or unparseable box means "no explicit
    /// limit", i.e. fall back to the prelude's `MAX_PARALLEL`).
    fn parallel_spec(&self) -> Option<ParallelSpec> {
        self.parallel.then(|| ParallelSpec {
            degree: self.degree.trim().parse::<u32>().ok().filter(|d| *d > 0),
        })
    }

    /// The ticked `BASELINE(…) SHOW(…)` fields, in checklist order.
    fn selected_baseline_show(&self) -> Vec<ShowField> {
        self.baseline_show
            .iter()
            .filter(|r| r.included)
            .map(|r| ShowField {
                field: r.name.clone(),
                stats: self.show_stats.get(&r.name).cloned().unwrap_or_default(),
            })
            .collect()
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    /// Cycle one entry's value through the loaded environment names (or, for a
    /// `FILE(…)` entry, the discovered snapshot paths) — a no-op when the
    /// relevant list is empty, so a fresh template's placeholders survive.
    fn cycle_entry(&mut self, i: usize, forward: bool) {
        let list = if self.entries[i].file {
            &self.snapshots
        } else {
            &self.choices
        };
        let n = list.len();
        if n == 0 {
            return;
        }
        let cur = &self.entries[i].name;
        let next = match list.iter().position(|c| c == cur) {
            Some(p) if forward => (p + 1) % n,
            Some(p) => (p + n - 1) % n,
            None => 0,
        };
        self.entries[i].name = list[next].clone();
    }

    /// Toggle whether entry `i` is a `FILE(…)` snapshot reference (Compare mode
    /// only — a plain `ENVS` list can't hold snapshots). Switching sets the
    /// entry's value to the first item of the newly-relevant list so it starts
    /// valid, unless it already matches one.
    fn toggle_file(&mut self, i: usize) {
        if !self.compare {
            return;
        }
        let becoming_file = !self.entries[i].file;
        self.entries[i].file = becoming_file;
        let list = if becoming_file {
            &self.snapshots
        } else {
            &self.choices
        };
        if !list.iter().any(|c| c == &self.entries[i].name)
            && let Some(first) = list.first()
        {
            self.entries[i].name = first.clone();
        }
    }

    /// Toggle whether entry `i` is the baseline (Compare mode only). Enforces
    /// the "at most one baseline" rule by clearing every other entry's flag.
    fn toggle_baseline(&mut self, i: usize) {
        if !self.compare {
            return;
        }
        let becoming = !self.entries[i].baseline;
        for (j, e) in self.entries.iter_mut().enumerate() {
            e.baseline = becoming && j == i;
        }
    }

    /// Flip Iterate ↔ Compare. Entering Compare with no baseline promotes the
    /// first entry so a comparison run has a reference by default.
    fn toggle_mode(&mut self) {
        self.compare = !self.compare;
        if self.compare
            && !self.entries.iter().any(|e| e.baseline)
            && let Some(first) = self.entries.first_mut()
        {
            first.baseline = true;
        }
    }

    /// Flip the `PARALLEL` marker on/off.
    fn toggle_parallel(&mut self) {
        self.parallel = !self.parallel;
    }

    fn add_entry(&mut self) {
        self.entries.push(EnvEntry {
            name: self.choices.first().cloned().unwrap_or_default(),
            baseline: false,
            file: false,
        });
    }

    fn remove_entry(&mut self, i: usize) {
        if self.entries.len() > 1 && i < self.entries.len() {
            self.entries.remove(i);
        }
    }

    fn var_or_default(&self) -> String {
        let v = self.var.trim();
        if v.is_empty() {
            "TARGET".to_string()
        } else {
            v.to_string()
        }
    }

    /// The [`EnvClause`] the current rows describe, or `None` when it would be
    /// empty (nothing named) — the caller then leaves the node unchanged rather
    /// than writing an unparseable clause.
    fn clause(&self) -> Option<EnvClause> {
        if self.compare {
            let refs = |want_baseline: bool| -> Vec<RoleRef> {
                self.entries
                    .iter()
                    .filter(|e| e.baseline == want_baseline)
                    .filter(|e| !e.name.trim().is_empty())
                    .map(|e| {
                        let name = e.name.trim().to_string();
                        if e.file {
                            RoleRef::File(name)
                        } else {
                            RoleRef::Env(name)
                        }
                    })
                    .collect()
            };
            let baseline = refs(true);
            let comparisons = refs(false);
            if baseline.is_empty() && comparisons.is_empty() {
                return None;
            }
            Some(EnvClause::Roles {
                baseline,
                comparisons,
                baseline_show: self.selected_baseline_show(),
            })
        } else {
            let names: Vec<String> = self
                .entries
                .iter()
                .map(|e| e.name.trim().to_string())
                .filter(|n| !n.is_empty())
                .collect();
            if names.is_empty() {
                return None;
            }
            Some(EnvClause::Plain(names))
        }
    }
}

/// One row of the [`FilesForm`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum FilesRow {
    /// The loop variable name (a free identifier, editable inline).
    Var,
    /// The source folder — activating it opens the file picker.
    Folder,
    /// The optional `MATCH "glob"` filter (editable text; empty ⇒ no `MATCH`).
    Match,
    /// The `PARALLEL` on/off toggle (run iterations concurrently).
    Parallel,
    /// `PARALLEL(n)`'s max-concurrency, typed as digits. Only shown while
    /// `PARALLEL` is on.
    Degree,
}

/// The `FOR … IN FILES` / `FOR … IN FOLDERS` configure form
/// ([`Overlay::ReportNodeFiles`]), reached with Enter on either loop — the file
/// analogue of [`EnvsForm`]. It picks the loop variable, the source folder (via
/// the file picker), an optional `MATCH` glob (`FILES` only) and whether the
/// loop runs `PARALLEL`, with an optional max-concurrency.
///
/// The two producers share one form because they differ only in that `FOLDERS`
/// has no `MATCH` and instead carries `WITH role="glob"` clauses, which the
/// form preserves verbatim rather than editing.
pub(crate) struct FilesForm {
    /// The report being edited (looked up by id, resilient to tab reorder).
    pub(crate) report_id: u64,
    /// Path of the node this edits.
    pub(crate) path: Vec<usize>,
    /// The loop variable name.
    pub(crate) var: String,
    /// The source directory the loop reads from (as authored — may be relative
    /// to the report). Chosen via the folder picker on the Folder row.
    pub(crate) dir: String,
    /// The `MATCH "glob"` filter (empty ⇒ no `MATCH` clause).
    pub(crate) glob: String,
    /// `true` when the loop is marked `PARALLEL` (iterations run concurrently).
    pub(crate) parallel: bool,
    /// `PARALLEL(n)`'s max-concurrency as typed text; blank ⇒ no explicit limit.
    pub(crate) degree: String,
    /// `true` when this edits a `FOLDERS` loop rather than a `FILES` one.
    pub(crate) folders: bool,
    /// A `FOLDERS` loop's `WITH role="glob"` clauses, preserved verbatim across
    /// an edit (the form doesn't expose them, but must not drop them).
    pub(crate) roles: Vec<RoleBinding>,
    /// Selected row: an index into [`Self::visible_rows`] (clamped on use).
    pub(crate) selected: usize,
}

impl FilesForm {
    /// Build the form from a `FILES` loop's current variable, directory, glob
    /// and parallel marker. A freshly-inserted loop (empty `dir`) starts with
    /// the Folder row selected so the picker is one keystroke away — the source
    /// directory is the whole point of the loop.
    #[allow(clippy::too_many_arguments)]
    fn build(
        report_id: u64,
        path: Vec<usize>,
        var: String,
        dir: String,
        glob: Option<String>,
        parallel: Option<ParallelSpec>,
        folders: bool,
        roles: Vec<RoleBinding>,
    ) -> Self {
        let selected = if dir.trim().is_empty() { 1 } else { 0 };
        FilesForm {
            report_id,
            path,
            var,
            dir,
            glob: glob.unwrap_or_default(),
            parallel: parallel.is_some(),
            degree: parallel
                .and_then(|p| p.degree)
                .map(|d| d.to_string())
                .unwrap_or_default(),
            folders,
            roles,
            selected,
        }
    }

    pub(crate) fn visible_rows(&self) -> Vec<FilesRow> {
        // Both producers take a `MATCH` glob: over file names for `FILES`, over
        // folder names (recursing on `**`) for `FOLDERS`.
        let mut rows = vec![FilesRow::Var, FilesRow::Folder, FilesRow::Match];
        rows.push(FilesRow::Parallel);
        if self.parallel {
            rows.push(FilesRow::Degree);
        }
        rows
    }

    /// The `PARALLEL` spec the rows describe (see [`EnvsForm::parallel_spec`]).
    fn parallel_spec(&self) -> Option<ParallelSpec> {
        self.parallel.then(|| ParallelSpec {
            degree: self.degree.trim().parse::<u32>().ok().filter(|d| *d > 0),
        })
    }

    /// The producer the rows describe.
    fn producer(&self) -> Producer {
        if self.folders {
            Producer::Folders {
                dir: self.dir.clone(),
                glob: self.glob_opt(),
                roles: self.roles.clone(),
            }
        } else {
            Producer::Files {
                dir: self.dir.clone(),
                glob: self.glob_opt(),
            }
        }
    }

    fn last_row(&self) -> usize {
        self.visible_rows().len().saturating_sub(1)
    }

    fn var_or_default(&self) -> String {
        let v = self.var.trim();
        if v.is_empty() {
            "FILE".to_string()
        } else {
            v.to_string()
        }
    }

    /// The `MATCH` glob as an `Option` (trimmed; empty ⇒ `None`).
    fn glob_opt(&self) -> Option<String> {
        let g = self.glob.trim();
        if g.is_empty() {
            None
        } else {
            Some(g.to_string())
        }
    }

    fn toggle_parallel(&mut self) {
        self.parallel = !self.parallel;
    }
}

// ---------------------------------------------------------------------------
// TuiApp integration
// ---------------------------------------------------------------------------

impl TuiApp {
    pub(crate) fn report_index_by_id(&self, id: u64) -> Option<usize> {
        self.reports.iter().position(|rt| rt.report.id == id)
    }

    /// The flattened node outline for report `idx`, or the parser error message
    /// when its source doesn't currently parse (the node view can't be built
    /// from unparseable text). Request rows are tagged by whether they resolve
    /// in the bound collection.
    pub(crate) fn report_node_rows(&self, idx: usize) -> Result<Vec<NodeRow>, String> {
        let rt = self.reports.get(idx).ok_or("no report")?;
        let flow = rt.report.flow().map_err(|e| e.to_string())?;
        let entries = self
            .resolve_bound_collection(&rt.report)
            .map(|ci| self.collections[ci].entries.as_slice())
            .unwrap_or(&[]);
        let helpers = rt.helpers.as_slice();
        let resolves =
            |name: &str| crate::report::run::resolve_qualified(entries, helpers, name).is_some();
        // Expanded: the TUI outline has no room for the GUI's per-field chips,
        // so a `WITH` block's fields are rows of their own.
        Ok(flatten_expanded(&flow, &resolves, true))
    }

    /// The bound collection's request titles (for the request picker), empty
    /// when the report isn't bound to a loaded collection.
    fn bound_request_titles(&self, report_id: u64) -> Vec<String> {
        let Some(idx) = self.report_index_by_id(report_id) else {
            return Vec::new();
        };
        let entries = self
            .resolve_bound_collection(&self.reports[idx].report)
            .map(|ci| self.collections[ci].entries.as_slice())
            .unwrap_or(&[]);
        // Qualified, so a helper's request is offered in the form the source
        // must contain — and so cycling can find the current value's position
        // when a node already names one.
        crate::report::context::request_choices(entries, &self.reports[idx].helpers)
            .into_iter()
            .map(|c| c.qualified)
            .collect()
    }

    /// Handle a key in the structured node editor. Returns `true` when the key
    /// was consumed (so the caller stops), `false` to fall through to the
    /// report view's shared shortcuts (global menus, tab nav, the `n` toggle…).
    pub(crate) fn on_key_report_nodes(&mut self, key: KeyEvent, idx: usize) -> bool {
        // Without a parseable flow there are no rows to act on; let the shared
        // shortcuts (e.g. `n`/`e` to drop into the source editor) run instead.
        let Ok(rows) = self.report_node_rows(idx) else {
            return false;
        };
        // The cursor may be up in the settings section, which is indexed
        // separately and answers to its own keys.
        if let Some(sel) = self.reports[idx].node_setting {
            return self.on_key_report_settings(key, idx, sel);
        }
        let last = rows.len().saturating_sub(1);
        let sel = self.reports[idx].node_selected.min(last);
        self.reports[idx].node_selected = sel;
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        match key.code {
            // Ctrl+Z reverts the last structural edit (insert/replace/delete/
            // move/folder/detail) — the node editor's undo, mirroring the source
            // editor's in-buffer Ctrl+Z so an accidental change is easy to take
            // back.
            KeyCode::Char('z') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.undo_report_node(idx)
            }
            KeyCode::Up if shift => self.move_selected_node(idx, true),
            KeyCode::Down if shift => self.move_selected_node(idx, false),
            KeyCode::Char('K') => self.move_selected_node(idx, true),
            KeyCode::Char('J') => self.move_selected_node(idx, false),
            KeyCode::Up | KeyCode::Char('k') => {
                if sel == 0 {
                    // Off the top of the flow and into the settings above it,
                    // landing on their last row so the two sections arrow
                    // through as one list.
                    let n = self.setting_row_count(idx);
                    if n > 0 {
                        self.reports[idx].node_setting = Some(n - 1);
                    }
                } else {
                    self.reports[idx].node_selected = sel - 1;
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.reports[idx].node_selected = (sel + 1).min(last);
            }
            KeyCode::Home => {
                // Home is the top of the *pane*, which is the first setting.
                self.reports[idx].node_selected = 0;
                if self.setting_row_count(idx) > 0 {
                    self.reports[idx].node_setting = Some(0);
                }
            }
            KeyCode::End => self.reports[idx].node_selected = last,
            KeyCode::Char('a') | KeyCode::Insert => {
                // Inside a `WITH` block, "add" means another field of that
                // block — asking for a flow node there would land it after the
                // request, which is never what the cursor position implied.
                match rows.get(sel).map(|r| (r.kind, r.path.clone())) {
                    Some((k, path)) if k.is_with() => {
                        self.open_with_field_editor(idx, &path, usize::MAX)
                    }
                    _ => self.open_report_node_menu(idx),
                }
            }
            // Enter opens the friendly, structured "configure this node" form
            // (its shape depends on the node kind — request options, a loop's
            // folder, …). `e` is the raw escape hatch that edits the node's
            // source line directly. `f` is deliberately NOT handled here, so it
            // falls through to the shared File menu — consistent with every
            // other view, instead of the old "detail on some kinds, File menu
            // on others" overload.
            KeyCode::Enter => self.configure_selected_node(idx),
            KeyCode::Char('e') => self.edit_selected_node(idx),
            KeyCode::Delete | KeyCode::Backspace => self.delete_selected_node(idx),
            _ => return false,
        }
        true
    }

    /// Open the insert palette for the position implied by the current
    /// selection.
    fn open_report_node_menu(&mut self, idx: usize) {
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let pos = insert_pos_after(&rows, sel);
        let s = Strings::for_language(&self.language);
        let options = NodeKind::ALL
            .iter()
            .map(|k| k.label(&s).to_string())
            .collect();
        self.overlay = Some(Overlay::ReportNodeMenu(Box::new(NodeMenu {
            step: NodeMenuStep::PickKind,
            options,
            selected: 0,
            pos,
            report_id: self.reports[idx].report.id,
            report_kind: false,
            edit_path: None,
        })));
    }

    /// Open the file browser to choose the source folder for the selected
    /// `FOR … IN FILES/FOLDERS` node. Returns `true` when it applied (the
    /// selection is such a loop), `false` otherwise so the caller falls through
    /// to the shared `f` (File menu) shortcut. The browser reopens at the
    /// loop's current folder when it resolves, else the report's own directory;
    /// the pick is finished on `Space` (see [`Self::commit_report_node_folder`]).
    fn open_report_node_folder(&mut self, idx: usize) -> bool {
        let Ok(rows) = self.report_node_rows(idx) else {
            return false;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else {
            return false;
        };
        let path = row.path.clone();
        let current_dir = {
            let Ok(flow) = self.reports[idx].report.flow() else {
                return false;
            };
            match node_at(&flow, &path).and_then(loop_producer_dir) {
                Some(dir) => dir.to_string(),
                None => return false, // not a FILES/FOLDERS loop
            }
        };
        // Reopen the browser at the loop's current folder when it resolves
        // (absolute, or relative to the report), else the report's directory.
        let start = {
            let p = std::path::Path::new(&current_dir);
            if !current_dir.is_empty() && p.is_dir() {
                Some(p.to_path_buf())
            } else if let Some(base) = self.active_report_base_dir() {
                let joined = base.join(&current_dir);
                Some(if joined.is_dir() { joined } else { base })
            } else {
                None
            }
        };
        if let Some(dir) = start {
            self.last_browse_dir = Some(dir);
        }
        self.pending_node_folder = Some((self.reports[idx].report.id, path));
        self.open_browser(crate::tui::app::FileAction::PickReportNodeFolder);
        true
    }

    /// Finish a [`crate::tui::app::FileAction::PickReportNodeFolder`] pick:
    /// write `dir` into the parked loop node's producer, re-serialize,
    /// revalidate and persist. Called from the browser's `Space` handler.
    pub(crate) fn commit_report_node_folder(&mut self, dir: &str) {
        let Some((report_id, path)) = self.pending_node_folder.take() else {
            return;
        };
        let Some(idx) = self.report_index_by_id(report_id) else {
            return;
        };
        {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return;
            };
            let Some(node) = node_at_mut(&mut flow, &path) else {
                return;
            };
            match loop_producer_dir_mut(node) {
                Some(slot) => *slot = dir.to_string(),
                None => return,
            }
            let text = flow.to_text();
            rt.set_text_undoable(text);
        }
        self.revalidate_report(idx);
        self.select_node_path(idx, &path);
        self.save_state();
    }

    /// Enter — open the friendly, structured "configure this node" editor for
    /// the selected node. The form depends on the node kind: `Begin` opens the
    /// insert palette; a request node opens the request form (name, `REPORT`
    /// toggle, and — when reported — response/alias/`SHOW`); a `FOR FILES/
    /// FOLDERS` loop opens the folder browser; reported variables and computed
    /// columns open their own forms. Only the kinds with no palette entry
    /// (tuple-pattern loops, tuple list literals, exotic producers) fall back to
    /// the raw line editor. Never touches the File menu (that's `f`).
    fn configure_selected_node(&mut self, idx: usize) {
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else { return };
        if row.kind == RowKind::Begin {
            self.open_report_node_menu(idx);
            return;
        }
        // A `WITH` row configures its own field. Its `END` has nothing to
        // configure, and must not fall through to the request's form — that
        // would make the block's last row silently edit the request instead.
        if let Some(wi) = self.with_row_index(row) {
            let path = row.path.clone();
            self.open_with_field_editor(idx, &path, wi);
            return;
        }
        if row.kind == RowKind::WithEnd {
            return;
        }
        let path = row.path.clone();
        // Try the request form, then the loop folder browser; fall back to the
        // raw line editor for kinds without a dedicated form yet.
        if self.open_report_node_request(idx) {
            return;
        }
        if self.open_report_node_envs(idx) {
            return;
        }
        if self.open_report_node_files(idx) {
            return;
        }
        if self.open_report_node_vars(idx) {
            return;
        }
        if self.open_report_node_computed(idx) {
            return;
        }
        if self.open_report_node_assign(idx) {
            return;
        }
        if self.open_report_node_list(idx) {
            return;
        }
        if self.open_report_node_folder(idx) {
            return;
        }
        self.open_report_node_line_prompt(idx, &path);
    }

    /// Open the configure form for the selected request node — a plain `REQUEST`
    /// or a `REPORT REQUEST`. Returns `true` when the selection is a request
    /// node, `false` otherwise so the caller can try another form. The `REPORT`
    /// toggle lets a plain request become reported (and back) from here.
    /// Build a [`RequestForm`] for `node` at `path` in report `idx`, or `None`
    /// when the node isn't a request. Shared by the "open it" gesture and by
    /// the `WITH` sub-form's return path, so both land on an identically
    /// populated form.
    fn build_report_node_request_form(
        &self,
        idx: usize,
        path: Vec<usize>,
        node: &FlowNode,
    ) -> Option<RequestForm> {
        let report_id = self.reports[idx].report.id;
        let (name, report, alias, response, current_show, current_hide, with) = match node {
            FlowNode::Request { name } => (
                name.clone(),
                false,
                None,
                None,
                Vec::new(),
                Vec::new(),
                Vec::new(),
            ),
            FlowNode::Report(ReportStmt::Request {
                name,
                alias,
                response_fmt,
                show,
                hide,
                with,
            }) => (
                name.clone(),
                true,
                alias.clone(),
                *response_fmt,
                show.clone(),
                hide.clone(),
                with.clone(),
            ),
            _ => return None,
        };
        let report_fields = self.request_report_fields(report_id, &name);
        let titles = self.bound_request_titles(report_id);
        Some(RequestForm::build(
            report_id,
            path,
            name,
            titles,
            report,
            alias,
            response,
            &current_show,
            &report_fields,
            with,
            current_hide,
        ))
    }

    fn open_report_node_request(&mut self, idx: usize) -> bool {
        let Ok(rows) = self.report_node_rows(idx) else {
            return false;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else {
            return false;
        };
        let path = row.path.clone();
        let Ok(flow) = self.reports[idx].report.flow() else {
            return false;
        };
        let Some(node) = node_at(&flow, &path).cloned() else {
            return false;
        };
        let Some(form) = self.build_report_node_request_form(idx, path, &node) else {
            return false; // not a request node
        };
        self.overlay = Some(Overlay::ReportNodeRequest(Box::new(form)));
        true
    }

    /// The `[Reports]` field names of the request `name` resolves to in the
    /// report's bound collection, empty when unbound/unresolved.
    fn request_report_fields(&self, report_id: u64, name: &str) -> Vec<String> {
        let Some(idx) = self.report_index_by_id(report_id) else {
            return Vec::new();
        };
        let rt = &self.reports[idx];
        let entries = self
            .resolve_bound_collection(&rt.report)
            .map(|ci| self.collections[ci].entries.as_slice())
            .unwrap_or(&[]);
        crate::report::run::resolve_qualified(entries, &rt.helpers, name)
            .map(|e| e.reports.iter().map(|(f, _)| f.clone()).collect())
            .unwrap_or_default()
    }

    /// Finish a [`RequestForm`]: rebuild the node from the form and write it
    /// back. The `REPORT` toggle chooses the node kind — a plain `REQUEST`
    /// (dropping any reporting options) or a `REPORT REQUEST` carrying the
    /// name, response, alias (blank ⇒ none), `SHOW(…)` (all-ticked ⇒ none), the
    /// preserved `HIDE(…)` clause, and the preserved `WITH … END` items.
    /// Re-serializes, revalidates, persists.
    pub(crate) fn apply_report_node_request(&mut self, form: RequestForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let node = if form.report {
            FlowNode::Report(ReportStmt::Request {
                name: form.request.clone(),
                alias: form.alias_opt(),
                response_fmt: form.response,
                show: form.show(),
                hide: form.hide(),
                with: form.with.clone(),
            })
        } else {
            FlowNode::Request {
                name: form.request.clone(),
            }
        };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Open the `REPORT <var>` form for the selected node. Returns `true` when
    /// the selection is a reported-variable statement.
    fn open_report_node_vars(&mut self, idx: usize) -> bool {
        let Some((report_id, path, node)) = self.selected_node(idx) else {
            return false;
        };
        let (chosen, alias, stats, image, truth, detail) = match &node {
            FlowNode::Report(ReportStmt::Vars(vars)) => {
                (vars.clone(), None, Vec::new(), None, None, false)
            }
            FlowNode::Report(ReportStmt::VarAs {
                var,
                name,
                stats,
                image,
                truth,
                detail,
            }) => (
                vec![var.clone()],
                Some(name.clone()),
                stats.clone(),
                *image,
                truth.clone(),
                *detail,
            ),
            _ => return false,
        };
        // The candidate list needs the bound collection to include the captures
        // of requests already sent; without one it is just the flow's own
        // assignments and loop binders.
        let entries = self
            .resolve_bound_collection(&self.reports[idx].report)
            .map(|ci| self.collections[ci].entries.clone())
            .unwrap_or_default();
        let in_scope = match self.reports[idx].report.flow() {
            Ok(flow) => crate::report::edit::vars_in_scope(&flow, &path, &entries),
            Err(_) => Vec::new(),
        };
        self.overlay = Some(Overlay::ReportNodeVars(Box::new(VarsForm::build(
            report_id, path, &chosen, alias, &stats, image, truth, detail, in_scope,
        ))));
        true
    }

    /// Write a [`VarsForm`] back. Picking nothing is a no-op.
    pub(crate) fn apply_report_node_vars(&mut self, form: VarsForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let Some(node) = form.node() else { return };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Key handling for the `REPORT <var>` form. Variable and stat rows toggle
    /// with Space/`x`; the free-text and alias rows take typed characters.
    pub(crate) fn report_node_vars_key_handler(&mut self, key: KeyEvent, mut form: Box<VarsForm>) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeVars(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => self.apply_report_node_vars(*form),
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    Some(VarsRow::Clause(cr)) => {
                        clause_key(&mut form.clauses, cr, key);
                        // Toggling IMAGE or FIT adds or removes rows below,
                        // which can leave the selection past the end.
                        form.selected = form.selected.min(form.last_row());
                        keep(self, form);
                    }
                    Some(VarsRow::Var(vi)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some(row) = form.vars.get_mut(vi)
                        {
                            row.included = !row.included;
                            // Ticking a second variable hides the alias/stat
                            // rows, which can leave the selection past the end.
                            form.selected = form.selected.min(form.last_row());
                        }
                        keep(self, form);
                    }
                    Some(VarsRow::Other) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => {
                                form.other.push(c)
                            }
                            KeyCode::Backspace => {
                                form.other.pop();
                            }
                            _ => {}
                        }
                        form.selected = form.selected.min(form.last_row());
                        keep(self, form);
                    }
                    Some(VarsRow::Alias) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => {
                                form.alias.push(c)
                            }
                            KeyCode::Backspace => {
                                form.alias.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(VarsRow::Stat(si)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some((_, on)) = form.stats.get_mut(si)
                        {
                            *on = !*on;
                        }
                        keep(self, form);
                    }
                    None => keep(self, form),
                }
            }
        }
    }

    /// Open the `REPORT "<template>" AS <name>` form for the selected node.
    /// Returns `true` when the selection is a computed column.
    fn open_report_node_computed(&mut self, idx: usize) -> bool {
        let Some((report_id, path, node)) = self.selected_node(idx) else {
            return false;
        };
        let FlowNode::Report(ReportStmt::Computed {
            template,
            name,
            stats,
            image,
            truth,
            detail,
        }) = node
        else {
            return false;
        };
        self.overlay = Some(Overlay::ReportNodeComputed(Box::new(ComputedForm {
            report_id,
            path,
            template,
            alias: name,
            clauses: ClauseForm::of(image, truth.as_deref(), detail),
            stats: StatKind::CHOOSABLE
                .iter()
                .map(|k| (*k, stats.contains(k)))
                .collect(),
            selected: 0,
        })));
        true
    }

    /// Write a [`ComputedForm`] back. A blank template or name is a no-op.
    pub(crate) fn apply_report_node_computed(&mut self, form: ComputedForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let Some(node) = form.node() else { return };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Key handling for the computed-column form. The template takes any
    /// printable character (it interpolates `{{ … }}`); the name is an
    /// identifier; stat rows toggle with Space/`x`.
    pub(crate) fn report_node_computed_key_handler(
        &mut self,
        key: KeyEvent,
        mut form: Box<ComputedForm>,
    ) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeComputed(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => self.apply_report_node_computed(*form),
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    Some(ComputedRow::Clause(cr)) => {
                        clause_key(&mut form.clauses, cr, key);
                        form.selected = form.selected.min(form.last_row());
                        keep(self, form);
                    }
                    Some(ComputedRow::Template) => {
                        match key.code {
                            KeyCode::Char(c) => form.template.push(c),
                            KeyCode::Backspace => {
                                form.template.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(ComputedRow::Alias) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => {
                                form.alias.push(c)
                            }
                            KeyCode::Backspace => {
                                form.alias.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(ComputedRow::Stat(si)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some((_, on)) = form.stats.get_mut(si)
                        {
                            *on = !*on;
                        }
                        keep(self, form);
                    }
                    None => keep(self, form),
                }
            }
        }
    }

    /// Open the `VARIABLE = VALUE` form for the selected node. Returns `true`
    /// when the selection is an assignment (so the caller stops trying other
    /// forms).
    fn open_report_node_assign(&mut self, idx: usize) -> bool {
        let Some((report_id, path, node)) = self.selected_node(idx) else {
            return false;
        };
        let FlowNode::Assign { key, value } = node else {
            return false;
        };
        self.overlay = Some(Overlay::ReportNodeAssign(Box::new(AssignForm {
            report_id,
            path,
            key,
            value,
            selected: 0,
        })));
        true
    }

    /// Write an [`AssignForm`] back. A blank variable name is a no-op.
    pub(crate) fn apply_report_node_assign(&mut self, form: AssignForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let Some(node) = form.node() else { return };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Key handling for the `VARIABLE = VALUE` form. Both rows are free text
    /// (a value may be a `{{ … }}` reference or anything else), so they take
    /// any printable character.
    pub(crate) fn report_node_assign_key_handler(
        &mut self,
        key: KeyEvent,
        mut form: Box<AssignForm>,
    ) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeAssign(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => self.apply_report_node_assign(*form),
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                let target = match rows.get(sel).copied() {
                    Some(AssignRow::Key) => &mut form.key,
                    Some(AssignRow::Value) => &mut form.value,
                    None => {
                        keep(self, form);
                        return;
                    }
                };
                match key.code {
                    KeyCode::Char(c) => target.push(c),
                    KeyCode::Backspace => {
                        target.pop();
                    }
                    _ => {}
                }
                keep(self, form);
            }
        }
    }

    /// Open the `LIST NAME = [ … ]` form for the selected node. Returns `true`
    /// only for a *literal* list of scalars — a tuple list or a computed
    /// producer falls through to the raw editor, which can express it.
    fn open_report_node_list(&mut self, idx: usize) -> bool {
        let Some((report_id, path, node)) = self.selected_node(idx) else {
            return false;
        };
        let FlowNode::ListDecl {
            name,
            producer: Producer::List(elems),
        } = node
        else {
            return false;
        };
        let mut values = Vec::with_capacity(elems.len());
        for e in &elems {
            match e {
                Element::Scalar(v) => values.push(v.clone()),
                Element::Tuple(_) => return false, // structure this form would flatten
            }
        }
        self.overlay = Some(Overlay::ReportNodeList(Box::new(ListForm {
            report_id,
            path,
            name,
            values,
            selected: 0,
        })));
        true
    }

    /// Write a [`ListForm`] back. A blank list name is a no-op.
    pub(crate) fn apply_report_node_list(&mut self, form: ListForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let Some(node) = form.node() else { return };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Key handling for the `LIST` form. Name and element rows take any
    /// printable character; the Add row appends an element with Space, and
    /// `x`/Del removes the selected element.
    pub(crate) fn report_node_list_key_handler(&mut self, key: KeyEvent, mut form: Box<ListForm>) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeList(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => self.apply_report_node_list(*form),
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    Some(ListRow::Name) => {
                        match key.code {
                            KeyCode::Char(c) => form.name.push(c),
                            KeyCode::Backspace => {
                                form.name.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(ListRow::Value(vi)) => {
                        match key.code {
                            // Del removes the whole element; Backspace edits it,
                            // so a half-typed value isn't lost to a stray key.
                            KeyCode::Delete => {
                                if vi < form.values.len() {
                                    form.values.remove(vi);
                                }
                                form.selected = form.selected.min(form.last_row());
                            }
                            KeyCode::Char(c) => form.values[vi].push(c),
                            KeyCode::Backspace => {
                                form.values[vi].pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(ListRow::Add) => {
                        if matches!(key.code, KeyCode::Char(' ')) {
                            form.values.push(String::new());
                            // Land on the new (empty) row so it can be typed
                            // into straight away.
                            form.selected = form.values.len();
                        }
                        keep(self, form);
                    }
                    None => keep(self, form),
                }
            }
        }
    }

    /// The report id, path and a clone of the node the node editor's selection
    /// points at — the common preamble of every `open_report_node_*`.
    fn selected_node(&self, idx: usize) -> Option<(u64, Vec<usize>, FlowNode)> {
        let rows = self.report_node_rows(idx).ok()?;
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let path = rows.get(sel)?.path.clone();
        let flow = self.reports[idx].report.flow().ok()?;
        let node = node_at(&flow, &path)?.clone();
        Some((self.reports[idx].report.id, path, node))
    }

    /// Key handling for the `WITH` field form ([`Overlay::ReportNodeWithField`]).
    /// ↑/↓ (or Tab) move; the Name/Query rows take typed text; the statistics
    /// toggle and the stat rows it reveals toggle with Space/`x`; Enter applies
    /// and Esc cancels, both returning where the form was opened from — the
    /// request form when it is a sub-form of one, the node outline otherwise.
    pub(crate) fn report_node_with_field_key_handler(
        &mut self,
        key: KeyEvent,
        mut form: Box<WithFieldForm>,
    ) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeWithField(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => {
                let (report_id, path, back) =
                    (form.report_id, form.path.clone(), form.return_to_request);
                let written = self.apply_report_node_with_field(*form);
                self.close_report_node_with_field(report_id, &path, back);
                // Applying replaces the whole request node, so the shared
                // `select_node_path` puts the cursor on the request line. That
                // was invisible while the form always handed back to the
                // request form; now that it closes to the outline, the cursor
                // has to stay on the field the user was editing.
                if !back && let Some(wi) = written {
                    self.select_with_row(report_id, &path, wi);
                }
            }
            KeyCode::Esc => {
                let (report_id, path, back) =
                    (form.report_id, form.path.clone(), form.return_to_request);
                self.close_report_node_with_field(report_id, &path, back);
            }
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    // The column name is an identifier-ish label; the query is
                    // arbitrary Hurl (JSONPath, headers, …), so it takes any
                    // printable character.
                    Some(WithFieldRow::Name) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => {
                                form.name.push(c)
                            }
                            KeyCode::Backspace => {
                                form.name.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(WithFieldRow::Query) => {
                        match key.code {
                            KeyCode::Char(c) => form.query.push(c),
                            KeyCode::Backspace => {
                                form.query.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(WithFieldRow::Clause(cr)) => {
                        clause_key(&mut form.clauses, cr, key);
                        keep(self, form);
                    }
                    Some(WithFieldRow::Stats) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x')) {
                            form.toggle_stats();
                        }
                        keep(self, form);
                    }
                    Some(WithFieldRow::Stat(si)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some((_, on)) = form.stats.get_mut(si)
                        {
                            *on = !*on;
                        }
                        keep(self, form);
                    }
                    None => keep(self, form),
                }
            }
        }
    }

    /// Write a [`WithFieldForm`] back into its request node's `WITH … END`
    /// block — replacing the field at `index`, or appending when it is `None`.
    /// A blank name is a no-op (an unnamed column can't be serialized), which
    /// is also how "cancel by clearing the name" behaves.
    ///
    /// Returns the `with` index it wrote, so the caller can leave the outline
    /// cursor on the field the user just edited.
    pub(crate) fn apply_report_node_with_field(&mut self, form: WithFieldForm) -> Option<usize> {
        let idx = self.report_index_by_id(form.report_id)?;
        let item = form.item()?;
        let flow = self.reports[idx].report.flow().ok()?;
        let Some(FlowNode::Report(ReportStmt::Request {
            name,
            alias,
            response_fmt,
            show,
            hide,
            with,
        })) = node_at(&flow, &form.path)
        else {
            return None;
        };
        let mut with = with.clone();
        let written = match form.index {
            Some(i) if i < with.len() => {
                with[i] = item;
                i
            }
            _ => {
                with.push(item);
                with.len() - 1
            }
        };
        let node = FlowNode::Report(ReportStmt::Request {
            name: name.clone(),
            alias: alias.clone(),
            response_fmt: *response_fmt,
            show: show.clone(),
            hide: hide.clone(),
            with,
        });
        self.apply_node_replace(idx, &form.path, node);
        Some(written)
    }

    /// Dismiss the `WITH` field form, returning where it was opened from:
    /// the request form when it was a sub-form of one, otherwise simply closing
    /// to the node outline. Closing to the outline is the whole point of the
    /// flag — opened from a `WITH` row (or its "add a field" row), the form
    /// used to hand the user a request form they had never asked for and then
    /// made them dismiss that too.
    fn close_report_node_with_field(&mut self, report_id: u64, path: &[usize], to_request: bool) {
        if to_request {
            self.reopen_report_node_request(report_id, path);
        } else {
            self.overlay = None;
        }
    }

    /// Reopen the request form for the node at `path` after a `WITH` sub-form
    /// closes, so the user lands back where they were rather than in the node
    /// list. Silently does nothing when the node has gone (the report was
    /// closed or edited underneath).
    fn reopen_report_node_request(&mut self, report_id: u64, path: &[usize]) {
        let Some(idx) = self.report_index_by_id(report_id) else {
            return;
        };
        let Ok(flow) = self.reports[idx].report.flow() else {
            return;
        };
        let Some(node) = node_at(&flow, path).cloned() else {
            return;
        };
        if let Some(form) = self.build_report_node_request_form(idx, path.to_vec(), &node) {
            self.overlay = Some(Overlay::ReportNodeRequest(Box::new(form)));
        }
    }

    /// Open the configure form for the selected `FOR … IN ENVS` node (#11) so
    /// its baseline/comparison environments are picked from the loaded ones
    /// instead of typed. Returns `true` when the selection is an ENVS loop,
    /// `false` otherwise so the caller can try another form.
    fn open_report_node_envs(&mut self, idx: usize) -> bool {
        let Ok(rows) = self.report_node_rows(idx) else {
            return false;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else {
            return false;
        };
        let path = row.path.clone();
        let report_id = self.reports[idx].report.id;
        let (var, clause, parallel, body) = {
            let Ok(flow) = self.reports[idx].report.flow() else {
                return false;
            };
            match node_at(&flow, &path) {
                Some(FlowNode::ForEnvs {
                    var,
                    clause,
                    parallel,
                    body,
                }) => (var.clone(), clause.clone(), *parallel, body.clone()),
                _ => return false, // not an ENVS loop
            }
        };
        let choices: Vec<String> = self.global_envs.iter().map(|e| e.name.clone()).collect();
        let snapshots = self.discover_report_snapshots(idx);
        // The `SHOW` checklist offers what the loop *body* reports, so it needs
        // the bound collection to ask each reported request what it emits.
        let selected_show = match &clause {
            crate::report::flow::EnvClause::Roles { baseline_show, .. } => baseline_show.clone(),
            crate::report::flow::EnvClause::Plain(_) => Vec::new(),
        };
        let show_choices = match self.resolve_bound_collection(&self.reports[idx].report) {
            Some(ci) => crate::report::edit::baseline_show_choices(
                &self.collections[ci].entries,
                &body,
                &selected_show,
            ),
            None => crate::report::edit::baseline_show_choices(&[], &body, &selected_show),
        };
        let form = EnvsForm::build(
            report_id,
            path,
            var,
            &clause,
            parallel,
            choices,
            snapshots,
            show_choices,
        );
        self.overlay = Some(Overlay::ReportNodeEnvs(Box::new(form)));
        true
    }

    /// List the `.baseline` snapshot files in report `idx`'s root directory as
    /// paths relative to that root — the candidates a `FILE(…)` role entry cycles
    /// through in the ENVS form. Relative so they match the `# root:`-relative
    /// resolution the runtime uses; empty on any I/O error (the form then just
    /// offers no snapshots, exactly like no loaded environments).
    fn discover_report_snapshots(&self, idx: usize) -> Vec<String> {
        let (root, _) = super::reports::report_base_dir(&self.reports[idx].report);
        let mut out: Vec<String> = Vec::new();
        if let Ok(entries) = std::fs::read_dir(&root) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|e| e == "baseline")
                    && let Some(name) = path.file_name().and_then(|n| n.to_str())
                {
                    out.push(name.to_string());
                }
            }
        }
        out.sort();
        out
    }

    /// Finish an [`EnvsForm`]: rebuild the `FOR … IN ENVS` node from it (keeping
    /// the node's body untouched) and write it back. A no-op when the form
    /// describes no environments (so the node is never replaced by an
    /// unparseable empty clause). The `PARALLEL` marker is taken from the
    /// form's toggle (preserving any explicit `PARALLEL(n)` degree already on
    /// the node when the toggle stays on).
    pub(crate) fn apply_report_node_envs(&mut self, form: EnvsForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let Some(clause) = form.clause() else {
            return;
        };
        // Preserve the existing node's body; var, clause, the SHOW checklist and
        // the PARALLEL marker (including its degree) all come from the form.
        let body = {
            let Ok(flow) = self.reports[idx].report.flow() else {
                return;
            };
            match node_at(&flow, &form.path) {
                Some(FlowNode::ForEnvs { body, .. }) => body.clone(),
                _ => return,
            }
        };
        let node = FlowNode::ForEnvs {
            var: form.var_or_default(),
            clause,
            body,
            parallel: form.parallel_spec(),
        };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Open the `FOR … IN FILES` configure form for the selected node. Returns
    /// `true` when the selection is a single-variable `FILES` loop (so the
    /// caller stops trying other forms), `false` otherwise — a `FOLDERS` loop or
    /// a tuple-pattern loop falls through to the plain folder browser.
    fn open_report_node_files(&mut self, idx: usize) -> bool {
        let Ok(rows) = self.report_node_rows(idx) else {
            return false;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else {
            return false;
        };
        let path = row.path.clone();
        let report_id = self.reports[idx].report.id;
        let (var, dir, glob, parallel, folders, roles) = {
            let Ok(flow) = self.reports[idx].report.flow() else {
                return false;
            };
            match node_at(&flow, &path) {
                Some(FlowNode::ForEach {
                    pattern,
                    producer: Producer::Files { dir, glob },
                    parallel,
                    ..
                }) if pattern.is_single() => (
                    pattern.named().next().unwrap_or("FILE").to_string(),
                    dir.clone(),
                    glob.clone(),
                    *parallel,
                    false,
                    Vec::new(),
                ),
                // `FOLDERS` shares the form: same variable, same folder picker,
                // same `MATCH` glob (which also drives its recursion) and the
                // same PARALLEL rows.
                Some(FlowNode::ForEach {
                    pattern,
                    producer: Producer::Folders { dir, glob, roles },
                    parallel,
                    ..
                }) if pattern.is_single() => (
                    pattern.named().next().unwrap_or("FOLDER").to_string(),
                    dir.clone(),
                    glob.clone(),
                    *parallel,
                    true,
                    roles.clone(),
                ),
                _ => return false, // not a single-var FILES/FOLDERS loop
            }
        };
        let form = FilesForm::build(report_id, path, var, dir, glob, parallel, folders, roles);
        self.overlay = Some(Overlay::ReportNodeFiles(Box::new(form)));
        true
    }

    /// Finish a [`FilesForm`]: rebuild the `FOR … IN FILES` node from it
    /// (keeping the node's body untouched) and write it back.
    pub(crate) fn apply_report_node_files(&mut self, form: &FilesForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let body = {
            let Ok(flow) = self.reports[idx].report.flow() else {
                return;
            };
            match node_at(&flow, &form.path) {
                Some(FlowNode::ForEach { body, .. }) => body.clone(),
                _ => return,
            }
        };
        let node = FlowNode::ForEach {
            pattern: Pattern::single(form.var_or_default()),
            producer: form.producer(),
            body,
            parallel: form.parallel_spec(),
        };
        self.apply_node_replace(idx, &form.path, node);
    }

    /// Key handling for the FILES configure form ([`Overlay::ReportNodeFiles`]).
    /// ↑/↓ (or Tab) move between rows; the Var/Match rows take typed characters;
    /// the Folder row opens the file picker (applying the form's other fields
    /// first so they aren't lost); the Parallel row toggles with Space/←/→;
    /// Enter applies, Esc cancels.
    pub(crate) fn report_node_files_key_handler(
        &mut self,
        key: KeyEvent,
        mut form: Box<FilesForm>,
    ) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeFiles(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                if rows.get(sel).copied() == Some(FilesRow::Folder) {
                    // Persist the rest of the form, then hand off to the folder
                    // picker (which writes the chosen dir back into this node).
                    self.apply_report_node_files(&form);
                    self.open_files_form_folder(&form);
                } else {
                    self.apply_report_node_files(&form);
                }
            }
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    Some(FilesRow::Var) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => form.var.push(c),
                            KeyCode::Backspace => {
                                form.var.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(FilesRow::Match) => {
                        match key.code {
                            KeyCode::Char(c) => form.glob.push(c),
                            KeyCode::Backspace => {
                                form.glob.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(FilesRow::Folder) => {
                        if matches!(key.code, KeyCode::Char(' ')) {
                            self.apply_report_node_files(&form);
                            self.open_files_form_folder(&form);
                        } else {
                            keep(self, form);
                        }
                    }
                    Some(FilesRow::Parallel) => {
                        if matches!(
                            key.code,
                            KeyCode::Char(' ') | KeyCode::Left | KeyCode::Right
                        ) {
                            form.toggle_parallel();
                            // Turning PARALLEL off hides the degree row below.
                            form.selected = form.selected.min(form.last_row());
                        }
                        keep(self, form);
                    }
                    // The max-concurrency box: digits only.
                    Some(FilesRow::Degree) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_ascii_digit() => form.degree.push(c),
                            KeyCode::Backspace => {
                                form.degree.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    None => keep(self, form),
                }
            }
        }
    }

    /// Park the FILES node and open the folder browser to pick its source
    /// directory (reusing the same [`crate::tui::app::FileAction::PickReportNodeFolder`]
    /// flow the plain folder key uses), seeded to the loop's current folder.
    fn open_files_form_folder(&mut self, form: &FilesForm) {
        let Some(idx) = self.report_index_by_id(form.report_id) else {
            return;
        };
        let start = {
            let p = std::path::Path::new(&form.dir);
            if !form.dir.trim().is_empty() && p.is_dir() {
                Some(p.to_path_buf())
            } else if let Some(base) = self.active_report_base_dir() {
                let joined = base.join(&form.dir);
                Some(if joined.is_dir() { joined } else { base })
            } else {
                None
            }
        };
        if let Some(dir) = start {
            self.last_browse_dir = Some(dir);
        }
        self.pending_node_folder = Some((form.report_id, form.path.clone()));
        let _ = idx;
        self.open_browser(crate::tui::app::FileAction::PickReportNodeFolder);
    }

    /// Key handling for the ENVS configure form ([`Overlay::ReportNodeEnvs`]).
    /// ↑/↓ (or Tab) move between rows; the Var row takes identifier characters;
    /// the Mode row toggles Iterate/Compare with Space/←/→; env rows cycle the
    /// environment (or snapshot, for a `FILE` entry) with Space/←/→, set the
    /// baseline with `b`, toggle a `FILE(…)` snapshot reference with `f`, add
    /// with `n` and remove with `x`/Del; Enter applies, Esc cancels.
    pub(crate) fn report_node_envs_key_handler(&mut self, key: KeyEvent, mut form: Box<EnvsForm>) {
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeEnvs(form));
        };
        let last = form.last_row();
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => self.apply_report_node_envs(*form),
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    Some(EnvsRow::Var) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => form.var.push(c),
                            KeyCode::Backspace => {
                                form.var.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(EnvsRow::Mode) => {
                        if matches!(
                            key.code,
                            KeyCode::Char(' ') | KeyCode::Left | KeyCode::Right
                        ) {
                            form.toggle_mode();
                        }
                        keep(self, form);
                    }
                    Some(EnvsRow::Parallel) => {
                        if matches!(
                            key.code,
                            KeyCode::Char(' ') | KeyCode::Left | KeyCode::Right
                        ) {
                            form.toggle_parallel();
                            // Turning PARALLEL off hides the degree row, which
                            // can leave the selection past the end.
                            form.selected = form.selected.min(form.last_row());
                        }
                        keep(self, form);
                    }
                    // The max-concurrency box: digits only, so it can never
                    // hold something that won't serialize as `PARALLEL(n)`.
                    Some(EnvsRow::Degree) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_ascii_digit() => form.degree.push(c),
                            KeyCode::Backspace => {
                                form.degree.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    Some(EnvsRow::BaselineShow(fi)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some(row) = form.baseline_show.get_mut(fi)
                        {
                            row.included = !row.included;
                        }
                        keep(self, form);
                    }
                    Some(EnvsRow::Env(ei)) => {
                        match key.code {
                            KeyCode::Char(' ') | KeyCode::Right => form.cycle_entry(ei, true),
                            KeyCode::Left => form.cycle_entry(ei, false),
                            KeyCode::Char('b') => form.toggle_baseline(ei),
                            KeyCode::Char('f') => form.toggle_file(ei),
                            KeyCode::Char('n') => {
                                form.add_entry();
                                form.selected = form.last_row();
                            }
                            KeyCode::Char('x') | KeyCode::Delete => {
                                form.remove_entry(ei);
                                form.selected = form.selected.min(form.last_row());
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    None => keep(self, form),
                }
            }
        }
    }
    /// name/response rows cycle with Space/←/→; the Report row toggles with
    /// Space; the alias row takes typed identifier characters and Backspace;
    /// field rows toggle with Space/`x`; Enter applies and closes; Esc cancels
    /// (the overlay was already `take`n by the dispatcher).
    pub(crate) fn report_node_request_key_handler(
        &mut self,
        key: KeyEvent,
        mut form: Box<RequestForm>,
    ) {
        let last = form.last_row();
        let keep = |app: &mut TuiApp, form| {
            app.overlay = Some(Overlay::ReportNodeRequest(form));
        };
        match key.code {
            KeyCode::Up => {
                form.selected = form.selected.saturating_sub(1);
                keep(self, form);
            }
            KeyCode::Down | KeyCode::Tab => {
                form.selected = (form.selected + 1).min(last);
                keep(self, form);
            }
            KeyCode::Enter => self.apply_report_node_request(*form),
            KeyCode::Esc => {} // cancel (overlay stays taken)
            _ => {
                // Resolve which logical row is selected via the dynamic layout,
                // so the reporting-only rows shift correctly when Report is off.
                let rows = form.visible_rows();
                let sel = form.selected.min(rows.len().saturating_sub(1));
                match rows.get(sel).copied() {
                    // Name — cycle through the bound collection's request titles.
                    Some(FormRow::Name) => match key.code {
                        KeyCode::Char(' ') | KeyCode::Right => {
                            form.cycle_name(true);
                            keep(self, form);
                        }
                        KeyCode::Left => {
                            form.cycle_name(false);
                            keep(self, form);
                        }
                        _ => keep(self, form),
                    },
                    // Report — toggle plain REQUEST ↔ REPORT REQUEST.
                    Some(FormRow::Report) => {
                        if matches!(
                            key.code,
                            KeyCode::Char(' ') | KeyCode::Left | KeyCode::Right
                        ) {
                            form.report = !form.report;
                            form.selected = form.selected.min(form.last_row());
                        }
                        keep(self, form);
                    }
                    // Response override.
                    Some(FormRow::Response) => match key.code {
                        KeyCode::Char(' ') | KeyCode::Right => {
                            form.cycle_response(true);
                            keep(self, form);
                        }
                        KeyCode::Left => {
                            form.cycle_response(false);
                            keep(self, form);
                        }
                        _ => keep(self, form),
                    },
                    // Alias text field (identifier characters only).
                    Some(FormRow::Alias) => {
                        match key.code {
                            KeyCode::Char(c) if c.is_alphanumeric() || c == '_' => {
                                form.alias.push(c)
                            }
                            KeyCode::Backspace => {
                                form.alias.pop();
                            }
                            _ => {}
                        }
                        keep(self, form);
                    }
                    // A SHOW field checkbox.
                    Some(FormRow::Field(fi)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some(row) = form.fields.get_mut(fi)
                        {
                            row.included = !row.included;
                        }
                        keep(self, form);
                    }
                    // A HIDE field checkbox.
                    Some(FormRow::Hidden(fi)) => {
                        if matches!(key.code, KeyCode::Char(' ') | KeyCode::Char('x'))
                            && let Some(row) = form.hide_fields.get_mut(fi)
                        {
                            row.included = !row.included;
                        }
                        keep(self, form);
                    }
                    // A WITH field: Space/Enter would both mean "open", but
                    // Enter is already "apply the whole form", so Space opens
                    // the field editor and `x`/Del removes the field outright.
                    Some(FormRow::With(wi)) => match key.code {
                        KeyCode::Char(' ') => {
                            let existing = form.with.get(wi).cloned();
                            let sub = WithFieldForm::build(
                                form.report_id,
                                form.path.clone(),
                                Some(wi),
                                existing.as_ref(),
                                true,
                            );
                            // The parent form is applied first so the rows the
                            // user already changed aren't lost behind the
                            // sub-form.
                            self.apply_report_node_request(*form);
                            self.overlay = Some(Overlay::ReportNodeWithField(Box::new(sub)));
                        }
                        KeyCode::Char('x') | KeyCode::Delete => {
                            if wi < form.with.len() {
                                form.with.remove(wi);
                            }
                            form.selected = form.selected.min(form.last_row());
                            keep(self, form);
                        }
                        _ => keep(self, form),
                    },
                    Some(FormRow::AddWith) => {
                        if matches!(key.code, KeyCode::Char(' ')) {
                            let sub = WithFieldForm::build(
                                form.report_id,
                                form.path.clone(),
                                None,
                                None,
                                true,
                            );
                            self.apply_report_node_request(*form);
                            self.overlay = Some(Overlay::ReportNodeWithField(Box::new(sub)));
                        } else {
                            keep(self, form);
                        }
                    }
                    None => keep(self, form),
                }
            }
        }
    }

    /// `e` — edit the selected node's source line directly (the raw escape
    /// hatch). `Begin` opens the insert palette (there's nothing to edit).
    fn edit_selected_node(&mut self, idx: usize) {
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else { return };
        if row.kind == RowKind::Begin {
            self.open_report_node_menu(idx);
            return;
        }
        // A `WITH` row addresses a field of the request at `row.path`, not a
        // node, so it opens the field editor rather than the line prompt (there
        // is no single-line source form for one field of a block).
        if let Some(wi) = self.with_row_index(row) {
            self.open_with_field_editor(idx, &row.path, wi);
            return;
        }
        if row.kind == RowKind::WithEnd {
            return;
        }
        let path = row.path.clone();
        self.open_report_node_line_prompt(idx, &path);
    }

    /// The `WITH` field index a row edits: the field itself, or a fresh one for
    /// the block's add row. `None` for anything that isn't an editable `WITH`
    /// row (a comment inside the block, the block's `END`, or a plain flow
    /// row).
    fn with_row_index(&self, row: &NodeRow) -> Option<usize> {
        match row.kind {
            RowKind::WithField(i) => Some(i),
            RowKind::WithAdd => Some(usize::MAX),
            _ => None,
        }
    }

    /// Open the `WITH` field editor for field `wi` of the request at `path`.
    /// `usize::MAX` means "a new field", which is how the add row and `a` ask
    /// for one.
    fn open_with_field_editor(&mut self, idx: usize, path: &[usize], wi: usize) {
        let report_id = self.reports[idx].report.id;
        let Ok(flow) = self.reports[idx].report.flow() else {
            return;
        };
        let existing = node_at(&flow, path)
            .and_then(node_with_items)
            .and_then(|w| w.get(wi))
            .cloned();
        let form = WithFieldForm::build(
            report_id,
            path.to_vec(),
            existing.is_some().then_some(wi),
            existing.as_ref(),
            false,
        );
        self.overlay = Some(Overlay::ReportNodeWithField(Box::new(form)));
    }

    /// Swap the `WITH` field at `wi` with its neighbour, reordering the report
    /// column it defines.
    fn move_with_field(&mut self, idx: usize, path: &[usize], wi: usize, up: bool) {
        {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return;
            };
            let Some(FlowNode::Report(ReportStmt::Request { with, .. })) =
                node_at_mut(&mut flow, path)
            else {
                return;
            };
            let other = if up {
                match wi.checked_sub(1) {
                    Some(o) => o,
                    None => return, // already first
                }
            } else if wi + 1 < with.len() {
                wi + 1
            } else {
                return; // already last
            };
            with.swap(wi, other);
            let text = flow.to_text();
            rt.set_text_undoable(text);
            // Follow the field: the cursor is on a row number, and the field
            // just moved one row against the direction of travel.
            let sel = rt.node_selected;
            rt.node_selected = if up { sel.saturating_sub(1) } else { sel + 1 };
        }
        self.revalidate_report(idx);
        self.save_state();
    }

    /// Open the single-line "edit as source" prompt for the node at `path`.
    fn open_report_node_line_prompt(&mut self, idx: usize, path: &[usize]) {
        let report_id = self.reports[idx].report.id;
        let Ok(flow) = self.reports[idx].report.flow() else {
            return;
        };
        let Some(node) = node_at(&flow, path) else {
            return;
        };
        let line = node.header_line();
        let s = Strings::for_language(&self.language);
        self.overlay = Some(Overlay::Prompt {
            kind: PromptKind::ReportNodeLine {
                report_id,
                path: path.to_vec(),
            },
            editor: Editor::new(&line, false),
            title: format!(
                "{}  ({})",
                s.report_node_edit_title, s.report_node_edit_hint
            ),
            mask: false,
            reset_to: None,
            secret_intact: false,
            secret_checkbox: None,
        });
    }

    /// Key handling for the insert / request-pick palette
    /// ([`Overlay::ReportNodeMenu`]). Up/Down move; Enter selects (advancing to
    /// the request step or committing); Esc/`q` cancels.
    pub(crate) fn report_node_menu_key_handler(&mut self, key: KeyEvent, mut menu: Box<NodeMenu>) {
        let last = menu.options.len().saturating_sub(1);
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                menu.selected = menu.selected.saturating_sub(1);
                self.overlay = Some(Overlay::ReportNodeMenu(menu));
            }
            KeyCode::Down | KeyCode::Char('j') => {
                menu.selected = (menu.selected + 1).min(last);
                self.overlay = Some(Overlay::ReportNodeMenu(menu));
            }
            KeyCode::Home => {
                menu.selected = 0;
                self.overlay = Some(Overlay::ReportNodeMenu(menu));
            }
            KeyCode::End => {
                menu.selected = last;
                self.overlay = Some(Overlay::ReportNodeMenu(menu));
            }
            KeyCode::Enter => match menu.step {
                NodeMenuStep::PickKind => self.node_menu_pick_kind(*menu),
                NodeMenuStep::PickRequest => self.node_menu_pick_request(*menu),
            },
            // Esc / q / anything else: cancel (overlay stays taken).
            _ => {}
        }
    }

    fn node_menu_pick_kind(&mut self, mut menu: NodeMenu) {
        let Some(&kind) = NodeKind::ALL.get(menu.selected) else {
            return;
        };
        let Some(idx) = self.report_index_by_id(menu.report_id) else {
            return;
        };
        if kind.needs_request() {
            let report_kind = matches!(kind, NodeKind::ReportRequest);
            let titles = self.bound_request_titles(menu.report_id);
            if titles.is_empty() {
                // No bound collection / no requests: insert an empty-name
                // template and let the user type the name in the line prompt.
                let path = self.apply_node_insert(idx, &menu.pos, request_node("", report_kind));
                self.open_report_node_line_prompt(idx, &path);
                return;
            }
            menu.step = NodeMenuStep::PickRequest;
            menu.options = titles;
            menu.selected = 0;
            menu.report_kind = report_kind;
            self.overlay = Some(Overlay::ReportNodeMenu(Box::new(menu)));
        } else if let Some(node) = kind.template() {
            self.apply_node_insert(idx, &menu.pos, node);
            // Land the freshly-inserted node straight in its most helpful
            // editor — the very view Enter would open on it. `apply_node_insert`
            // already selected the new node, so `configure_selected_node` routes
            // on its kind: the ENVS baseline/comparison/mode popup for a
            // `FOR … IN ENVS` loop, the source-folder browser for FILES/FOLDERS,
            // and the raw line editor for the kinds without a dedicated form yet
            // (ReportVar / Assign / List).
            self.configure_selected_node(idx);
        }
    }

    fn node_menu_pick_request(&mut self, menu: NodeMenu) {
        let Some(idx) = self.report_index_by_id(menu.report_id) else {
            return;
        };
        let Some(name) = menu.options.get(menu.selected) else {
            return;
        };
        let node = request_node(name, menu.report_kind);
        match &menu.edit_path {
            Some(path) => self.apply_node_replace(idx, path, node),
            None => {
                self.apply_node_insert(idx, &menu.pos, node);
            }
        }
    }

    /// Insert `node` at `pos`, re-serialize, revalidate, select the new node,
    /// and persist. Returns the inserted node's path.
    fn apply_node_insert(&mut self, idx: usize, pos: &InsertPos, node: FlowNode) -> Vec<usize> {
        let mut path = pos.parent.clone();
        path.push(pos.index);
        {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return path;
            };
            insert_node(&mut flow, pos, node);
            let text = flow.to_text();
            rt.set_text_undoable(text);
        }
        self.revalidate_report(idx);
        self.select_node_path(idx, &path);
        self.save_state();
        path
    }

    /// Replace the node at `path`, re-serialize, revalidate, keep it selected,
    /// and persist.
    fn apply_node_replace(&mut self, idx: usize, path: &[usize], node: FlowNode) {
        {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return;
            };
            if !replace_node(&mut flow, path, node) {
                return;
            }
            let text = flow.to_text();
            rt.set_text_undoable(text);
        }
        self.revalidate_report(idx);
        self.select_node_path(idx, path);
        self.save_state();
    }

    fn delete_selected_node(&mut self, idx: usize) {
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else { return };
        if row.kind == RowKind::Begin {
            return; // the root can't be deleted
        }
        // Deleting on a `WITH` row removes that one field, not the request that
        // owns it — they share a path, so this branch is what keeps Delete from
        // taking the whole block with it.
        if let Some(wi) = row.kind.with_item() {
            let path = row.path.clone();
            {
                let rt = &mut self.reports[idx];
                let Ok(mut flow) = rt.report.flow() else {
                    return;
                };
                // Bounds are checked here rather than from the return value:
                // `detach_modifier`'s bool answers "would this leave a statement
                // that stands on its own", not "did anything change", and for a
                // WITH field it is always false.
                if node_at(&flow, &path)
                    .and_then(node_with_items)
                    .is_none_or(|w| wi >= w.len())
                {
                    return;
                }
                detach_modifier(&mut flow, &path, DetachWhich::With(wi));
                let text = flow.to_text();
                rt.set_text_undoable(text);
            }
            self.revalidate_report(idx);
            self.save_state();
            return;
        }
        if row.kind.is_with() {
            return; // the add row and the block's END aren't deletable
        }
        let path = row.path.clone();
        {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return;
            };
            if !remove_node(&mut flow, &path) {
                return;
            }
            let text = flow.to_text();
            rt.set_text_undoable(text);
        }
        self.revalidate_report(idx);
        // Selection stays at `sel`; the draw pass clamps it to the new length.
        self.save_state();
    }

    fn move_selected_node(&mut self, idx: usize, up: bool) {
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        let sel = self.reports[idx]
            .node_selected
            .min(rows.len().saturating_sub(1));
        let Some(row) = rows.get(sel) else { return };
        if row.kind == RowKind::Begin {
            return;
        }
        // Reordering a `WITH` field reorders a report column, so it stays within
        // its own block rather than moving the request among its siblings.
        if let Some(wi) = row.kind.with_item() {
            self.move_with_field(idx, &row.path.clone(), wi, up);
            return;
        }
        if row.kind.is_with() {
            return;
        }
        let path = row.path.clone();
        let new_path = {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return;
            };
            let Some(np) = move_node(&mut flow, &path, up) else {
                return; // at a boundary — nothing to do
            };
            let text = flow.to_text();
            rt.set_text_undoable(text);
            np
        };
        self.revalidate_report(idx);
        self.select_node_path(idx, &new_path);
        self.save_state();
    }

    /// Undo the last structural node edit (Ctrl+Z in the node editor): pop the
    /// most recent snapshot off this report's [`node_undo`](crate::tui::reports::ReportTab::node_undo)
    /// stack and restore its source text and node selection, then revalidate and
    /// persist. Does nothing (with a brief status) when the stack is empty.
    fn undo_report_node(&mut self, idx: usize) {
        let Some(snap) = self.reports[idx].node_undo.pop() else {
            let s = Strings::for_language(&self.language);
            self.status = Some(Status::ReportNodeNothingToUndo(
                s.report_node_undo_empty.to_string(),
            ));
            return;
        };
        {
            let rt = &mut self.reports[idx];
            rt.report.set_text(snap.text);
            rt.node_selected = snap.node_selected;
        }
        self.revalidate_report(idx);
        self.save_state();
        let s = Strings::for_language(&self.language);
        self.status = Some(Status::ReportNodeUndone(s.report_node_undone.to_string()));
    }

    /// Commit an edited node line (from [`PromptKind::ReportNodeLine`]): re-parse
    /// it and swap it into the flow at `path`, keeping a loop's body.
    pub(crate) fn commit_report_node_line(&mut self, report_id: u64, path: &[usize], text: String) {
        let Some(idx) = self.report_index_by_id(report_id) else {
            return;
        };
        let was_loop = self.reports[idx]
            .report
            .flow()
            .ok()
            .and_then(|flow| node_at(&flow, path).map(FlowNode::is_loop))
            .unwrap_or(false);
        match parse_one_node(&text, was_loop) {
            Some(node) => self.apply_node_replace(idx, path, node),
            None => {
                let s = Strings::for_language(&self.language);
                self.status = Some(Status::ReportRunBlocked(
                    s.report_node_line_invalid.to_string(),
                ));
            }
        }
    }

    /// Move the node-view selection onto the row addressing `path` (the head
    /// row of a loop, or the leaf), clamping if it no longer exists.
    /// Put the outline cursor on the `WITH` row at index `wi` of the request at
    /// `path`. A no-op when the row has gone (the field was removed, or the
    /// block collapsed), leaving the cursor wherever the caller left it.
    fn select_with_row(&mut self, report_id: u64, path: &[usize], wi: usize) {
        let Some(idx) = self.report_index_by_id(report_id) else {
            return;
        };
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        if let Some(at) = rows
            .iter()
            .position(|r| r.path == path && r.kind.with_item() == Some(wi))
        {
            self.reports[idx].node_selected = at;
        }
    }

    fn select_node_path(&mut self, idx: usize, path: &[usize]) {
        let Ok(rows) = self.report_node_rows(idx) else {
            return;
        };
        let target = rows
            .iter()
            .position(|r| r.path == path && r.kind != RowKind::LoopEnd && !r.kind.is_with())
            .unwrap_or_else(|| rows.len().saturating_sub(1));
        self.reports[idx].node_selected = target;
    }
}

// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------

/// Draw the node outline for report `idx` (the middle band of the node view,
/// between the binding row and the validation panel). Renders the flattened
/// rows with the selected row highlighted and auto-scrolls to keep it visible;
/// falls back to the parser error when the source doesn't parse.
pub(crate) fn draw_report_nodes(
    f: &mut Frame,
    area: Rect,
    app: &mut TuiApp,
    idx: usize,
    s: &Strings,
    th: &Theme,
) {
    let focused = app.report_body_focused();
    let title = format!("{}{}", s.report_nodes_heading, s.report_nodes_hint);
    let block = panel(title, focused, th);
    let inner = block.inner(area);
    f.render_widget(block, area);
    app.report_pane_areas[crate::tui::reports::ReportPane::Source.idx()] = Rect::default();
    app.report_pane_bars[crate::tui::reports::ReportPane::Source.idx()] = Rect::default();
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let rows = match app.report_node_rows(idx) {
        Ok(rows) => rows,
        Err(e) => {
            let lines = vec![
                Line::from(Span::styled(
                    s.report_nodes_parse_error,
                    Style::default().fg(th.err),
                )),
                Line::from(Span::styled(e, Style::default().fg(th.dim))),
            ];
            f.render_widget(Paragraph::new(lines), inner);
            return;
        }
    };

    let sel = app.reports[idx]
        .node_selected
        .min(rows.len().saturating_sub(1));
    app.reports[idx].node_selected = sel;

    // The report's own settings are drawn as leading lines of this same list,
    // above `BEGIN`, exactly where the graphical editor's settings strip sits:
    // they describe the whole report rather than running as a step.
    //
    // They scroll *with* the outline rather than being pinned above it. A pinned
    // strip would have to win its rows off a pane that is already the smallest
    // thing on screen — and when there was no room for it, it would vanish while
    // the cursor could still be moved onto it. One list has one cursor and one
    // scroll offset, so whatever is selected is always on screen.
    let settings = app.report_setting_rows(idx);
    let add_row = !app.missing_report_settings(idx).is_empty();
    let set_sel = app.reports[idx].node_setting;
    let w = inner.width as usize;
    let key_w = settings.iter().map(|r| r.key.len()).max().unwrap_or(0);

    // Line 0 is the "Settings" heading; then one line per directive; then the
    // optional "add a setting" row; then a rule; then the flow.
    let head_lines = if settings.is_empty() {
        0
    } else {
        1 + settings.len() + usize::from(add_row) + 1
    };
    let mut lines: Vec<Line> = Vec::with_capacity(head_lines + rows.len());
    // Which mouse target each line carries, parallel to `lines`.
    let mut targets: Vec<Option<MouseHitTarget>> = Vec::with_capacity(head_lines + rows.len());
    if !settings.is_empty() {
        lines.push(Line::from(Span::styled(
            s.report_settings_heading.to_string(),
            Style::default().fg(th.dim).add_modifier(Modifier::BOLD),
        )));
        targets.push(None);
        for (i, row) in settings.iter().enumerate() {
            lines.push(render_setting_row(row, key_w, set_sel == Some(i), w, s, th));
            targets.push(Some(MouseHitTarget::ReportSettingRow(i)));
        }
        if add_row {
            let i = settings.len();
            let style = if set_sel == Some(i) {
                Style::default()
                    .fg(th.bg)
                    .bg(th.accent)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(th.dim)
            };
            lines.push(Line::from(Span::styled(
                format!("  + {}", s.report_setting_add_row),
                style,
            )));
            targets.push(Some(MouseHitTarget::ReportSettingRow(i)));
        }
        // A rule between the settings and the flow, so the outline still reads
        // as starting at BEGIN rather than continuing the list of settings.
        lines.push(Line::from(Span::styled(
            "".repeat(w),
            Style::default().fg(th.dim),
        )));
        targets.push(None);
    }
    for (i, row) in rows.iter().enumerate() {
        lines.push(render_node_row(
            row,
            i == sel && set_sel.is_none(),
            w,
            s,
            th,
        ));
        targets.push(Some(MouseHitTarget::ReportNodeRow(i)));
    }

    // Scroll so the cursor — wherever it is in the combined list — is visible.
    let cursor = match set_sel {
        Some(i) => 1 + i,
        None => head_lines + sel,
    };
    let h = inner.height as usize;
    let total = lines.len();
    let first = if cursor >= h { cursor + 1 - h } else { 0 };

    f.render_widget(
        Paragraph::new(lines.into_iter().skip(first).take(h).collect::<Vec<_>>()),
        inner,
    );
    app.push_mouse_hit(
        MouseLayer::Base,
        inner,
        MouseHitTarget::Scroll(MouseScrollTarget::ReportPane(
            crate::tui::reports::ReportPane::Source,
        )),
    );
    for (line, target) in targets.iter().enumerate().skip(first).take(h) {
        if let Some(target) = target {
            app.push_mouse_hit(
                MouseLayer::Base,
                Rect::new(inner.x, inner.y + (line - first) as u16, inner.width, 1),
                *target,
            );
        }
    }

    if total > h {
        let bar = Rect {
            x: area.x + area.width - 1,
            y: inner.y,
            width: 1,
            height: inner.height,
        };
        draw_scrollbar(f, bar, total, h, first, th);
    }
}

/// One settings row: `KEY  value`, with the key dimmed like a label and the
/// value carrying the colour. An unset **required** directive (only
/// `collection:`) is drawn in the error colour, because it is the one thing
/// standing between the report and a run and should look like it.
fn render_setting_row(
    row: &SettingRow,
    key_w: usize,
    selected: bool,
    width: usize,
    s: &Strings,
    th: &Theme,
) -> Line<'static> {
    let unset = row.unset();
    let (value, value_colour) = if unset {
        (
            s.report_setting_unset.to_string(),
            if row.required { th.err } else { th.dim },
        )
    } else {
        (row.value.clone(), th.text)
    };
    let key_colour = if unset && row.required {
        th.err
    } else {
        th.dim
    };
    let text = format!(
        "  {:<key_w$}  {value}",
        row.key.to_uppercase(),
        key_w = key_w
    );
    let text = truncate_to_width(&text, width);
    if selected {
        return Line::from(Span::styled(
            text,
            Style::default()
                .fg(th.bg)
                .bg(th.accent)
                .add_modifier(Modifier::BOLD),
        ));
    }
    // Split back at the value so the key and the value can be coloured apart
    // without laying the string out twice.
    let head_len = 2 + key_w + 2;
    let (head, tail) = text.split_at(head_len.min(text.len()));
    Line::from(vec![
        Span::styled(head.to_string(), Style::default().fg(key_colour)),
        Span::styled(tail.to_string(), Style::default().fg(value_colour)),
    ])
}

/// Cut `text` to `width` display columns, marking the cut with an ellipsis.
fn truncate_to_width(text: &str, width: usize) -> String {
    if text.chars().count() <= width {
        return text.to_string();
    }
    let mut out: String = text.chars().take(width.saturating_sub(1)).collect();
    out.push('');
    out
}

fn render_node_row(
    row: &NodeRow,
    selected: bool,
    width: usize,
    s: &Strings,
    th: &Theme,
) -> Line<'static> {
    let indent = "  ".repeat(row.depth);
    let (text, base, bold) = match row.kind {
        RowKind::Begin => (s.report_node_begin.to_string(), th.accent, true),
        RowKind::LoopHead => (row.label.clone(), th.accent, false),
        RowKind::LoopEnd => ("END".to_string(), th.accent, false),
        RowKind::Leaf => (row.label.clone(), th.text, false),
        // Dimmed: it is in the file, but it isn't a statement.
        RowKind::Comment => (row.label.clone(), th.dim, false),
        RowKind::WithField(_) => (row.label.clone(), th.text, false),
        RowKind::WithComment(_) => (row.label.clone(), th.dim, false),
        // The affordance that answers "how do I add a column here?" — dimmed
        // like the settings section's own add row, since it isn't source.
        RowKind::WithAdd => (format!("+ {}", s.report_with_add_row), th.dim, false),
        RowKind::WithEnd => ("END".to_string(), th.accent, false),
    };
    // Request rows recolour by whether the name resolves (green / amber),
    // matching the source view's highlighting.
    let colour = match row.req_ok {
        Some(true) => th.ok,
        Some(false) => th.pending,
        None => base,
    };
    let mut content = format!("{indent}{text}");
    if selected {
        // Pad to the panel width so the highlight fills the whole row.
        let len = content.chars().count();
        if len < width {
            content.extend(std::iter::repeat_n(' ', width - len));
        }
    }
    let mut style = if selected {
        Style::default().fg(th.select_fg).bg(th.select_bg)
    } else {
        Style::default().fg(colour)
    };
    if bold {
        style = style.add_modifier(Modifier::BOLD);
    }
    Line::from(Span::styled(content, style))
}

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

    #[test]
    fn envs_form_round_trip_preserves_baseline_show() {
        // Build an EnvsForm from a Roles clause that carries SHOW(Time).
        let clause = EnvClause::Roles {
            baseline: vec![RoleRef::Env("prod".into())],
            comparisons: vec![RoleRef::Env("staging".into())],
            baseline_show: vec!["Time".into()],
        };
        let form = EnvsForm::build(1, vec![], "T".into(), &clause, None, vec![], vec![], vec![]);
        assert_eq!(
            form.selected_baseline_show(),
            vec!["Time".to_string()],
            "a SHOW field the clause names must come back ticked"
        );

        // clause() must hand it back intact — no silent drop.
        let rebuilt = form.clause().expect("clause must be Some");
        assert_eq!(
            rebuilt,
            EnvClause::Roles {
                baseline: vec![RoleRef::Env("prod".into())],
                comparisons: vec![RoleRef::Env("staging".into())],
                baseline_show: vec!["Time".into()],
            }
        );
    }

    #[test]
    fn envs_form_preserves_and_rebuilds_a_file_role() {
        // A FILE(…) role must survive a build → clause() round-trip, and its path
        // must be reachable in the snapshot cycle even when not on disk.
        let clause = EnvClause::Roles {
            baseline: vec![RoleRef::File("prod.baseline".into())],
            comparisons: vec![RoleRef::Env("staging".into())],
            baseline_show: vec![],
        };
        let form = EnvsForm::build(1, vec![], "T".into(), &clause, None, vec![], vec![], vec![]);
        assert!(
            form.snapshots.iter().any(|s| s == "prod.baseline"),
            "existing FILE path must be seeded into the cycle"
        );
        let rebuilt = form.clause().expect("clause must be Some");
        assert_eq!(rebuilt, clause);
    }

    #[test]
    fn envs_form_toggle_file_switches_a_role_to_a_snapshot() {
        // Toggling `f` on an env entry makes it a FILE role that picks the first
        // discovered snapshot; toggling back returns it to a live env.
        let clause = EnvClause::Roles {
            baseline: vec![RoleRef::Env("prod".into())],
            comparisons: vec![RoleRef::Env("staging".into())],
            baseline_show: vec![],
        };
        let mut form = EnvsForm::build(
            1,
            vec![],
            "T".into(),
            &clause,
            None,
            vec!["prod".into(), "staging".into()],
            vec!["snap.baseline".into()],
            vec![],
        );
        form.toggle_file(0);
        assert!(form.entries[0].file);
        assert_eq!(form.entries[0].name, "snap.baseline");
        match form.clause().expect("clause") {
            EnvClause::Roles { baseline, .. } => {
                assert_eq!(baseline, vec![RoleRef::File("snap.baseline".into())]);
            }
            other => panic!("expected roles, got {other:?}"),
        }
        form.toggle_file(0);
        assert!(!form.entries[0].file);
        assert_eq!(form.entries[0].name, "prod");
    }
}

// ---------------------------------------------------------------------------
// The settings section: the report's `# key: value` header directives
// ---------------------------------------------------------------------------
//
// The flow below `BEGIN` says what the report *does*; these say what it does it
// *to* — which collection, which environment, where relative paths resolve,
// what the output is written as. The graphical editor has always shown them as
// a strip of chips above the blocks; the terminal editor could only bind a
// collection (`b`), so every other directive had to be typed into the raw
// source. This section closes that gap, and shares the GUI's directive table
// (`report::edit::header_specs`) so neither editor can quietly fall behind the
// other again.
//
// It reuses the outline's own four keys rather than inventing a second
// vocabulary for the same pane: Enter configures, `e` edits as raw text,
// Delete removes, `a` adds.

/// One row of the node editor's settings section.
pub(crate) struct SettingRow {
    pub(crate) key: &'static str,
    pub(crate) kind: HeaderKind,
    pub(crate) required: bool,
    /// Which occurrence of `key` this row edits. Always 0 except for
    /// `collection:`, which repeats: occurrence 0 is the primary collection and
    /// each one after it is an aliased helper (`path AS alias`). Without this
    /// every helper row would write back over the primary.
    pub(crate) occurrence: usize,
    /// The directive's stored value; empty when the directive is absent, or the
    /// [`HEADER_PLACEHOLDER`] sentinel when it was added but not filled in.
    pub(crate) value: String,
}

impl SettingRow {
    /// Whether this directive is still waiting for a value.
    pub(crate) fn unset(&self) -> bool {
        header_unset(&self.value)
    }
}

impl TuiApp {
    /// The settings rows shown above the flow: every always-shown directive
    /// plus whichever optional ones the report actually sets.
    ///
    /// Returns an empty list when the flow doesn't parse — the node editor
    /// shows a parse error in place of everything in that case, and a settings
    /// strip floating above the error would just be a second thing to read.
    pub(crate) fn report_setting_rows(&self, idx: usize) -> Vec<SettingRow> {
        let Some(rt) = self.reports.get(idx) else {
            return Vec::new();
        };
        let Ok(flow) = rt.report.flow() else {
            return Vec::new();
        };
        header_specs()
            .into_iter()
            .flat_map(|spec| {
                // A repeatable directive gets one row per occurrence —
                // `collection:` for each aliased helper, `labels:` for each
                // class — so they can be seen and edited here rather than only
                // in the raw source.
                let values = if spec.repeatable {
                    let all = flow.header.get_all(spec.key);
                    if all.is_empty() {
                        vec![String::new()]
                    } else {
                        all.into_iter().map(str::to_string).collect()
                    }
                } else {
                    vec![flow.header.get(spec.key).unwrap_or_default().to_string()]
                };
                values
                    .into_iter()
                    .enumerate()
                    .filter(|(_, value)| spec.always_shown || !value.is_empty())
                    .map(|(occurrence, value)| SettingRow {
                        key: spec.key,
                        kind: spec.kind,
                        required: spec.required && occurrence == 0,
                        occurrence,
                        value,
                    })
                    .collect::<Vec<_>>()
            })
            .collect()
    }

    /// The optional directives this report doesn't have yet — the contents of
    /// the "add setting" menu, and (when empty) the reason that row isn't
    /// drawn at all.
    pub(crate) fn missing_report_settings(&self, idx: usize) -> Vec<&'static str> {
        let Some(rt) = self.reports.get(idx) else {
            return Vec::new();
        };
        let Ok(flow) = rt.report.flow() else {
            return Vec::new();
        };
        header_specs()
            .into_iter()
            .filter(|spec| {
                !spec.always_shown && flow.header.get(spec.key).unwrap_or_default().is_empty()
            })
            .map(|spec| spec.key)
            .collect()
    }

    /// How many rows the settings section offers the cursor: the visible
    /// directives, plus the trailing "add setting" row when there is anything
    /// left to add.
    pub(crate) fn setting_row_count(&self, idx: usize) -> usize {
        let rows = self.report_setting_rows(idx).len();
        rows + usize::from(!self.missing_report_settings(idx).is_empty())
    }

    /// Whether the cursor is on the trailing "add setting" row rather than on a
    /// directive.
    fn on_add_setting_row(&self, idx: usize, sel: usize) -> bool {
        sel >= self.report_setting_rows(idx).len()
    }

    /// Handle a key while the node editor's cursor is in the settings section.
    /// Returns `true` when the key was consumed.
    ///
    /// Moving down off the last row (or up off the first flow row, handled by
    /// the caller) crosses between the two sections, so the whole pane still
    /// feels like one list to arrow through even though the two halves are
    /// indexed separately.
    fn on_key_report_settings(&mut self, key: KeyEvent, idx: usize, sel: usize) -> bool {
        let last = self.setting_row_count(idx).saturating_sub(1);
        let sel = sel.min(last);
        self.reports[idx].node_setting = Some(sel);
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                self.reports[idx].node_setting = Some(sel.saturating_sub(1));
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if sel >= last {
                    // Off the bottom of the settings and into the flow.
                    self.reports[idx].node_setting = None;
                    self.reports[idx].node_selected = 0;
                } else {
                    self.reports[idx].node_setting = Some(sel + 1);
                }
            }
            KeyCode::Home => self.reports[idx].node_setting = Some(0),
            KeyCode::End => {
                // End belongs to the flow (the outline is the long list), so it
                // leaves the settings entirely.
                self.reports[idx].node_setting = None;
                let rows = self.report_node_rows(idx).map(|r| r.len()).unwrap_or(1);
                self.reports[idx].node_selected = rows.saturating_sub(1);
            }
            KeyCode::Enter => self.configure_selected_setting(idx, sel),
            KeyCode::Char('e') => self.edit_selected_setting_raw(idx, sel),
            KeyCode::Delete | KeyCode::Backspace => self.clear_selected_setting(idx, sel),
            KeyCode::Char('a') | KeyCode::Insert => self.open_add_setting_menu(idx),
            _ => return false,
        }
        true
    }

    /// Enter on a settings row: open the editor that suits the directive — a
    /// picker for the ones with a closed set of answers, a file browser for the
    /// two that name paths, a text prompt for the rest.
    fn configure_selected_setting(&mut self, idx: usize, sel: usize) {
        if self.on_add_setting_row(idx, sel) {
            self.open_add_setting_menu(idx);
            return;
        }
        let rows = self.report_setting_rows(idx);
        let Some(row) = rows.get(sel) else { return };
        let (key, kind, occurrence) = (row.key, row.kind, row.occurrence);
        match kind {
            // The collection picker already exists (`b`), lists exactly the
            // right things and writes the reference in the right form, so Enter
            // here is that same picker rather than a second one beside it.
            //
            // Only for the *primary* collection, though: it rebinds the report,
            // and a helper also needs its `AS alias`, which the picker has no
            // way to ask for. Helper rows get the raw text prompt, seeded with
            // the whole `path AS alias` line.
            HeaderKind::Collection if occurrence == 0 => self.open_report_bind(),
            HeaderKind::Collection => self.open_setting_text_prompt(idx, sel),
            HeaderKind::Environment | HeaderKind::Format => {
                self.open_setting_value_menu(idx, key, occurrence, kind)
            }
            HeaderKind::Folder | HeaderKind::File => self.open_setting_path_browser(idx, key, kind),
            HeaderKind::Text => self.open_setting_text_prompt(idx, sel),
        }
    }

    /// `e` on a settings row: edit the directive's stored value as raw text,
    /// whatever its kind. The escape hatch that matches the outline's own `e`,
    /// and the only way to type a value the pickers can't offer — a collection
    /// that isn't open, an environment that only exists on another machine.
    fn edit_selected_setting_raw(&mut self, idx: usize, sel: usize) {
        if self.on_add_setting_row(idx, sel) {
            self.open_add_setting_menu(idx);
            return;
        }
        self.open_setting_text_prompt(idx, sel);
    }

    /// Seed and open the text prompt for the settings row at `sel`.
    fn open_setting_text_prompt(&mut self, idx: usize, sel: usize) {
        let rows = self.report_setting_rows(idx);
        let Some(row) = rows.get(sel) else { return };
        // The placeholder is a "not filled in yet" marker, not a value anyone
        // meant to edit, so the prompt opens empty rather than with a `?` to
        // delete first.
        let seed = if row.unset() {
            String::new()
        } else {
            row.value.clone()
        };
        let key = row.key;
        let occurrence = row.occurrence;
        let report_id = self.reports[idx].report.id;
        self.overlay = Some(Overlay::Prompt {
            kind: PromptKind::ReportHeaderValue {
                report_id,
                key,
                occurrence,
            },
            editor: Editor::new(&seed, false),
            title: key.to_uppercase(),
            mask: false,
            reset_to: None,
            secret_intact: false,
            secret_checkbox: None,
        });
    }

    /// Delete on a settings row: remove the directive. An always-shown one
    /// (`collection:`, `output:`) stays on screen as its unset prompt; the rest
    /// go back to the add menu.
    fn clear_selected_setting(&mut self, idx: usize, sel: usize) {
        if self.on_add_setting_row(idx, sel) {
            return;
        }
        let rows = self.report_setting_rows(idx);
        let Some(row) = rows.get(sel) else { return };
        let (key, occurrence) = (row.key, row.occurrence);
        self.apply_report_setting(idx, key, occurrence, None);
        // Removing an optional directive shortens the list under the cursor.
        let last = self.setting_row_count(idx).saturating_sub(1);
        self.reports[idx].node_setting = Some(sel.min(last));
    }

    /// Write (or, with `None`, remove) a header directive on the report at
    /// `idx`, re-serializing through the same undoable path every structural
    /// node edit uses — so Ctrl+Z takes a settings change back too.
    pub(crate) fn apply_report_setting(
        &mut self,
        idx: usize,
        key: &str,
        occurrence: usize,
        value: Option<&str>,
    ) {
        {
            let rt = &mut self.reports[idx];
            let Ok(mut flow) = rt.report.flow() else {
                return;
            };
            if !crate::report::edit::set_header_nth(&mut flow, key, occurrence, value) {
                return;
            }
            let text = flow.to_text();
            rt.set_text_undoable(text);
        }
        self.revalidate_report(idx);
        self.save_state();
    }
}

/// The settings menu overlay ([`Overlay::ReportSettingMenu`]) — one list, two
/// jobs, because they are the same interaction: choose one of a short list of
/// names and something happens to the header.
pub(crate) struct SettingMenu {
    pub(crate) step: SettingMenuStep,
    /// What the rows say — the *whole* list, never narrowed in place, so
    /// backspacing over the filter brings the hidden rows straight back.
    pub(crate) options: Vec<String>,
    /// What has been typed to narrow the list. Empty means "show everything".
    pub(crate) filter: String,
    /// The cursor, as an index into the **visible** (filtered) rows — see
    /// [`SettingMenu::visible`]. Keeping it in filtered space is what makes
    /// "type two letters, press Enter" work without any bookkeeping.
    pub(crate) selected: usize,
    /// The report being edited (by id so a tab reorder can't misroute it).
    pub(crate) report_id: u64,
}

/// Which job a [`SettingMenu`] is doing.
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) enum SettingMenuStep {
    /// Adding one of the not-yet-present optional directives; the options are
    /// directive keys.
    AddSetting,
    /// Choosing the value of `key`; the options are the values themselves.
    PickValue {
        key: &'static str,
        /// Which occurrence of `key` the pick writes to — see
        /// [`SettingRow::occurrence`].
        occurrence: usize,
    },
    /// Choosing the value of a report `PARAM` from the run settings view; the
    /// options are the parameter's `CHOICE(…)` list or the loaded environment
    /// names. Unlike the two above this doesn't touch the source: a parameter's
    /// value belongs to the run, not to the report.
    PickParam { name: String },
}

impl SettingMenu {
    /// The rows the filter leaves standing, in declaration order. A
    /// case-insensitive substring match: the lists these menus show are names
    /// (environments, formats, directives), and people recall a fragment of a
    /// name far more reliably than its first letters.
    pub(crate) fn visible(&self) -> Vec<&String> {
        if self.filter.is_empty() {
            return self.options.iter().collect();
        }
        let needle = self.filter.to_lowercase();
        self.options
            .iter()
            .filter(|o| o.to_lowercase().contains(&needle))
            .collect()
    }

    /// The row the cursor is on, or `None` when the filter matches nothing.
    pub(crate) fn choice(&self) -> Option<String> {
        self.visible().get(self.selected).map(|o| (*o).clone())
    }

    /// Keep the cursor on a row that exists after the filter changed. It goes
    /// to the top rather than trying to follow the previously selected row:
    /// the point of typing is to bring the wanted row *to* the top.
    fn clamp_selection(&mut self) {
        self.selected = 0;
    }

    /// The overlay title for the current job.
    pub(crate) fn title(&self, s: &Strings) -> String {
        match &self.step {
            SettingMenuStep::AddSetting => s.report_add_setting.to_string(),
            SettingMenuStep::PickValue { key, .. } => key.to_uppercase(),
            SettingMenuStep::PickParam { name } => name.clone(),
        }
    }
}

impl TuiApp {
    /// `a` on the settings section: offer the optional directives this report
    /// doesn't have yet. A no-op with a status when they are all present —
    /// better than an empty menu that looks broken.
    fn open_add_setting_menu(&mut self, idx: usize) {
        let s = Strings::for_language(&self.language);
        let missing = self.missing_report_settings(idx);
        // A helper collection is always offerable — `collection:` repeats, so
        // unlike the one-shot directives it is never "already set".
        let mut options: Vec<String> = missing.iter().map(|k| k.to_uppercase()).collect();
        options.push(s.report_add_helper_collection.to_string());
        // A second label class is offered the same way: `labels:` repeats, so
        // once one is set the one-shot "add setting" entry is gone and there
        // would otherwise be no way to declare the other half of the
        // vocabulary without editing the source.
        if self
            .reports
            .get(idx)
            .and_then(|rt| rt.report.flow().ok())
            .is_some_and(|f| !f.header.labels().is_empty())
        {
            options.push(s.report_add_label_class.to_string());
        }
        self.overlay = Some(Overlay::ReportSettingMenu(Box::new(SettingMenu {
            step: SettingMenuStep::AddSetting,
            options,
            filter: String::new(),
            selected: 0,
            report_id: self.reports[idx].report.id,
        })));
    }

    /// Add another `# collection:` line — an aliased helper collection, whose
    /// requests the report can then call as `alias/request`.
    ///
    /// Seeded with the placeholder so the row appears immediately, then its
    /// text prompt is opened on the new row: a helper needs both a path and an
    /// `AS alias`, and typing the line is the only editor that can express
    /// both. Validation says so plainly if the alias is left off.
    fn add_helper_collection(&mut self, idx: usize) {
        let Ok(flow) = self.reports[idx].report.flow() else {
            return;
        };
        let occurrence = flow.header.get_all("collection").len().max(1);
        self.apply_report_setting(idx, "collection", occurrence, Some(HEADER_PLACEHOLDER));
        let rows = self.report_setting_rows(idx);
        if let Some(pos) = rows
            .iter()
            .position(|r| r.key == "collection" && r.occurrence == occurrence)
        {
            self.reports[idx].node_setting = Some(pos);
            self.open_setting_text_prompt(idx, pos);
        }
    }

    /// Add another `# labels:` line — one more class of the answers the report
    /// scores.
    ///
    /// Seeded and opened for typing exactly like a helper collection: a class
    /// is a name and a list of spellings on one line (`Pass = pass, ok, real`),
    /// which only the text prompt can express.
    fn add_label_class(&mut self, idx: usize) {
        let Ok(flow) = self.reports[idx].report.flow() else {
            return;
        };
        let occurrence = flow.header.labels().len();
        self.apply_report_setting(idx, "labels", occurrence, Some(HEADER_PLACEHOLDER));
        let rows = self.report_setting_rows(idx);
        if let Some(pos) = rows
            .iter()
            .position(|r| r.key == "labels" && r.occurrence == occurrence)
        {
            self.reports[idx].node_setting = Some(pos);
            self.open_setting_text_prompt(idx, pos);
        }
    }

    /// Enter on a directive whose answers are a closed list: the output formats
    /// PaperTrail can write, or the environments actually loaded.
    fn open_setting_value_menu(
        &mut self,
        idx: usize,
        key: &'static str,
        occurrence: usize,
        kind: HeaderKind,
    ) {
        let options: Vec<String> = match kind {
            HeaderKind::Format => crate::report::writer::OUTPUT_EXTENSIONS
                .iter()
                .map(|e| e.to_string())
                .collect(),
            _ => self.global_envs.iter().map(|e| e.name.clone()).collect(),
        };
        if options.is_empty() {
            // Only reachable for environments: there is nothing to choose from
            // until one is loaded. `e` still types a name by hand, which is the
            // right answer for an environment that lives on another machine.
            self.status = Some(Status::ReportSettingNoChoices);
            return;
        }
        let current = self
            .report_setting_rows(idx)
            .into_iter()
            .find(|r| r.key == key)
            .map(|r| r.value)
            .unwrap_or_default();
        let selected = options.iter().position(|o| *o == current).unwrap_or(0);
        self.overlay = Some(Overlay::ReportSettingMenu(Box::new(SettingMenu {
            step: SettingMenuStep::PickValue { key, occurrence },
            options,
            filter: String::new(),
            selected,
            report_id: self.reports[idx].report.id,
        })));
    }

    /// Enter on `root:` or `baseline:`: browse for the folder / file, rather
    /// than making the user type a path they can't check.
    fn open_setting_path_browser(&mut self, idx: usize, key: &'static str, kind: HeaderKind) {
        self.pending_header_path = Some((self.reports[idx].report.id, key));
        // Seed the browser at the report's own folder: a report's root and its
        // baseline almost always live beside it.
        if let Some(dir) = self.active_report_base_dir() {
            self.last_browse_dir = Some(dir);
        }
        self.open_browser(match kind {
            HeaderKind::Folder => FileAction::PickReportHeaderFolder,
            _ => FileAction::PickReportHeaderFile,
        });
    }

    /// Store a browsed path (or a typed one) into the parked header directive,
    /// relative to the report when that is shorter — a report and the files it
    /// names usually travel together, so an absolute path would break the
    /// moment the pair moved. Mirrors the GUI's `pick_header_file`.
    /// A `PARAM … FILE`/`FOLDER` pick came back: store it as the parameter's
    /// value for the next run. Relative to the report's own folder when it
    /// lives beneath it, matching what `# root:` does — a report and the files
    /// it feeds on usually travel together.
    pub(crate) fn commit_report_param_path(&mut self, path: &str) {
        let Some((report_id, name)) = self.pending_param_path.take() else {
            return;
        };
        let Some(idx) = self.report_index_by_id(report_id) else {
            return;
        };
        let value = self
            .reports
            .get(idx)
            .and_then(|rt| rt.report.path.as_deref())
            .and_then(|p| p.parent())
            .and_then(|base| std::path::Path::new(path).strip_prefix(base).ok())
            .map(|rel| rel.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.to_string());
        self.set_report_param(report_id, &name, value);
    }

    pub(crate) fn commit_report_header_path(&mut self, path: &str) {
        let Some((report_id, key)) = self.pending_header_path.take() else {
            return;
        };
        let Some(idx) = self.report_index_by_id(report_id) else {
            return;
        };
        let value = self
            .reports
            .get(idx)
            .and_then(|rt| rt.report.path.as_deref())
            .and_then(|p| p.parent())
            .and_then(|base| std::path::Path::new(path).strip_prefix(base).ok())
            .map(|rel| rel.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.to_string());
        self.apply_report_setting(idx, key, 0, Some(&value));
    }

    /// Key handling for [`Overlay::ReportSettingMenu`]. ↑/↓ (and `j`/`k`,
    /// Home/End) move; Enter applies; anything else cancels — the same shape as
    /// every other list overlay here.
    pub(crate) fn report_setting_menu_key_handler(
        &mut self,
        key: KeyEvent,
        mut menu: Box<SettingMenu>,
    ) {
        let last = menu.visible().len().saturating_sub(1);
        match key.code {
            KeyCode::Up => {
                menu.selected = menu.selected.saturating_sub(1);
                self.overlay = Some(Overlay::ReportSettingMenu(menu));
            }
            KeyCode::Down => {
                menu.selected = (menu.selected + 1).min(last);
                self.overlay = Some(Overlay::ReportSettingMenu(menu));
            }
            KeyCode::Home => {
                menu.selected = 0;
                self.overlay = Some(Overlay::ReportSettingMenu(menu));
            }
            KeyCode::End => {
                menu.selected = last;
                self.overlay = Some(Overlay::ReportSettingMenu(menu));
            }
            // Typing narrows the list. These menus can be as long as the set of
            // loaded environments, where scrolling to the one you already know
            // the name of is the slowest possible way to pick it. This is why
            // `j`/`k` no longer move the cursor here — a letter is a letter.
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                menu.filter.push(c);
                menu.clamp_selection();
                self.overlay = Some(Overlay::ReportSettingMenu(menu));
            }
            KeyCode::Backspace => {
                // Backspace on an empty filter closes the menu, so the key that
                // undoes typing keeps undoing right out of the overlay.
                if menu.filter.pop().is_some() {
                    menu.clamp_selection();
                    self.overlay = Some(Overlay::ReportSettingMenu(menu));
                }
            }
            // Enter on a filter that matches nothing keeps the menu up: closing
            // it would look like a pick was made.
            KeyCode::Enter if menu.choice().is_none() => {
                self.overlay = Some(Overlay::ReportSettingMenu(menu));
            }
            KeyCode::Enter => self.apply_setting_menu(*menu),
            // Esc / anything else: cancel (the overlay was already taken).
            _ => {}
        }
    }

    fn apply_setting_menu(&mut self, menu: SettingMenu) {
        let Some(idx) = self.report_index_by_id(menu.report_id) else {
            return;
        };
        // Nothing matches the filter: there is no choice to apply, and closing
        // the menu on Enter would look like a silent pick.
        let Some(choice) = menu.choice() else {
            return;
        };
        match &menu.step {
            SettingMenuStep::AddSetting => {
                // Seeded with the placeholder so the row appears at once; an
                // empty value would be read as "remove this directive" and the
                // menu would appear to do nothing.
                let s = Strings::for_language(&self.language);
                if choice == s.report_add_helper_collection {
                    self.add_helper_collection(idx);
                    return;
                }
                if choice == s.report_add_label_class {
                    self.add_label_class(idx);
                    return;
                }
                let key = choice.to_ascii_lowercase();
                let Some(spec) = header_specs().into_iter().find(|s| s.key == key) else {
                    return;
                };
                self.apply_report_setting(idx, spec.key, 0, Some(HEADER_PLACEHOLDER));
                // Put the cursor on the row that just appeared and open its
                // editor, so adding a setting and filling it in is one gesture.
                let rows = self.report_setting_rows(idx);
                if let Some(pos) = rows.iter().position(|r| r.key == spec.key) {
                    self.reports[idx].node_setting = Some(pos);
                    self.configure_selected_setting(idx, pos);
                }
            }
            SettingMenuStep::PickValue { key, occurrence } => {
                self.apply_report_setting(idx, key, *occurrence, Some(&choice))
            }
            SettingMenuStep::PickParam { name } => {
                let (id, name) = (menu.report_id, name.clone());
                self.set_report_param(id, &name, choice);
            }
        }
    }
}