autumn-cli 0.9.0

CLI tool for the Autumn web framework
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
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
//! Translatable view emission for `autumn generate scaffold --i18n` (issue #1349).
//!
//! Autumn already ships the whole Fluent stack — the [`t!`] macro with
//! compile-time key validation, `Locale::t()`, the `i18n/<tag>.ftl` convention,
//! fallback chains, and an `Accept-Language` `Locale` extractor. What the
//! scaffold generator lacked was the wiring: every generated view emitted
//! hardcoded English, so localizing a resource meant hand-ripping the English
//! out of four views and hand-authoring the matching `.ftl` keys.
//!
//! [`ViewLabels`] is the single seam that closes that gap. Every user-facing
//! string in the generated views goes through it, and it emits one of two
//! things:
//!
//! * **`--i18n` off** — the caller's `plain` expression, returned *verbatim*.
//!   Byte-for-byte identity with the pre-#1349 scaffold is therefore structural,
//!   not a property some test has to keep re-checking: with the flag off this
//!   type is a `str -> str` identity function.
//! * **`--i18n` on** — a `t!(locale, "key")` lookup, and the key/English pair is
//!   recorded so [`merge_en_ftl_keeping`] can back-fill `i18n/en.ftl` with exactly the
//!   keys the views reference. That matters beyond tidiness: `t!` validates key
//!   existence *at compile time*, so a key the generator references but does not
//!   define is a `compile_error!` in the user's app, not a runtime miss.
//!
//! Because the English value written to `en.ftl` and the English rendered by the
//! non-i18n scaffold come from the same call site, an `en` app renders
//! identically either way (AC4) — there is no second copy of the strings to
//! drift.
//!
//! [`t!`]: autumn_web::t

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use syn::spanned::Spanned as _;
use syn::visit::Visit as _;

/// The comment introducing the shared-chrome block in a generated `en.ftl`.
const COMMON_HEADER: &str = "# Shared chrome — reused by every scaffolded resource.";

/// Prefix of the comment introducing one resource's block in a generated
/// `en.ftl`. The resource's `PascalCase` name and a trailing marker follow, so
/// `autumn destroy scaffold` can find and remove exactly the block it added.
const RESOURCE_HEADER_PREFIX: &str = "# ";

/// Trailer stamped on a generated resource block's comment so the destroy path
/// can identify it without guessing.
const RESOURCE_HEADER_SUFFIX: &str = " — generated by `autumn generate scaffold --i18n`.";

/// Closes the shared-chrome block.
const COMMON_FOOTER: &str = "# — end shared chrome —";

/// Closes a resource's block. The `PascalCase` name goes between the two
/// halves, mirroring its header.
const RESOURCE_FOOTER_PREFIX: &str = "# — end ";
const RESOURCE_FOOTER_SUFFIX: &str = " —";

/// The comment closing the block `header` opens.
///
/// Blocks are explicitly CLOSED rather than run to the first blank line or
/// comment, because a `.ftl` is a file people edit: a translator who groups
/// keys with a blank line, or leaves a `# careful, this one is on a button`
/// note beside one, would otherwise move the boundary. `destroy` would then
/// take the header and the keys above the separator and strand the rest — with
/// no call sites left, so `autumn i18n check --strict` starts failing on keys
/// nobody can find the owner of. An explicit marker lets formatting and
/// comments live inside the block while everything outside it stays the
/// application's own.
fn block_footer(header: &str) -> String {
    if header == COMMON_HEADER {
        return COMMON_FOOTER.to_owned();
    }
    let pascal = header
        .strip_prefix(RESOURCE_HEADER_PREFIX)
        .and_then(|rest| rest.strip_suffix(RESOURCE_HEADER_SUFFIX))
        .unwrap_or_default();
    format!("{RESOURCE_FOOTER_PREFIX}{pascal}{RESOURCE_FOOTER_SUFFIX}")
}

/// Catalog key the framework looks up for the NUL field error (#2439). The same
/// key as `autumn_web::form::NUL_CHARACTER_MESSAGE_KEY`.
pub(super) const NUL_MESSAGE_KEY: &str = "common.error.nul_character";

/// English text of [`NUL_MESSAGE_KEY`]. The same text as
/// `autumn_web::form::NUL_CHARACTER_FIELD_ERROR`.
pub(super) const NUL_MESSAGE_ENGLISH: &str = "Cannot contain the NUL character (0x00)";

/// Emits every user-facing string in a generated view, either as the literal
/// English expression the plain scaffold uses or as a `t!(locale, "key")`
/// lookup.
///
/// See the [module docs](self) for why the `plain` expression is threaded
/// through rather than reconstructed.
#[derive(Debug)]
pub(super) struct ViewLabels {
    /// Whether `--i18n` is on. `false` makes every emitter method an identity
    /// function over its `plain` argument.
    enabled: bool,
    /// Keys actually referenced, mapped to the English value that must appear in
    /// `i18n/en.ftl`. Interior mutability so the emitters stay `&self` and can be
    /// threaded through the generator's `fn(&…) -> String` render helpers.
    used: RefCell<BTreeMap<String, String>>,
}

impl ViewLabels {
    /// A disabled emitter — every method returns its `plain` argument verbatim.
    pub(super) const fn disabled() -> Self {
        Self {
            enabled: false,
            used: RefCell::new(BTreeMap::new()),
        }
    }

    /// An emitter that translates. `enabled` is the `--i18n` flag, threaded
    /// rather than assumed so callers can build one emitter unconditionally.
    pub(super) const fn new(enabled: bool) -> Self {
        Self {
            enabled,
            used: RefCell::new(BTreeMap::new()),
        }
    }

    /// Whether this emitter translates.
    pub(super) const fn enabled(&self) -> bool {
        self.enabled
    }

    /// The key -> English map for every key the views actually referenced.
    ///
    /// Exactly this set is written to `en.ftl`: a key the generator never
    /// emitted would show up as "unused" under `autumn i18n check` (#1252), and
    /// a key it emitted but never defined would fail the user's build.
    pub(super) fn used_keys(&self) -> BTreeMap<String, String> {
        self.used.borrow().clone()
    }

    /// Add `key = ftl` to the catalog for a message that the framework looks up.
    /// No generated view uses this key. `autumn i18n check` does not report
    /// these keys as unused.
    pub(super) fn framework_key(&self, key: &str, ftl: &str) {
        if self.enabled {
            self.used
                .borrow_mut()
                .insert(key.to_owned(), ftl.to_owned());
        }
    }

    /// Record `key = ftl` and return the `t!` invocation for it.
    fn record(&self, key: &str, ftl: &str, args: &[(&str, &str)]) -> String {
        self.used
            .borrow_mut()
            .insert(key.to_owned(), ftl.to_owned());
        if args.is_empty() {
            format!("t!(locale, \"{key}\")")
        } else {
            let rendered: Vec<String> = args
                .iter()
                .map(|(name, expr)| format!("{name} = {expr}"))
                .collect();
            format!("t!(locale, \"{key}\", {})", rendered.join(", "))
        }
    }

    /// A string-valued site (`impl Into<String>` parameters such as
    /// `a11y::Link::new`/`Button::new`, `FormFor::override_label`, and Maud
    /// splice positions). `english` is the bare text; with `--i18n` off it is
    /// emitted as a quoted Rust literal, exactly as before.
    pub(super) fn lit(&self, key: &str, english: &str) -> String {
        if self.enabled {
            self.record(key, english, &[])
        } else {
            format!("\"{english}\"")
        }
    }

    /// [`Self::lit`] for a `&str` parameter (`layout(title)`,
    /// `widgets::Column::new`, `property_list` labels).
    pub(super) fn lit_ref(&self, key: &str, english: &str) -> String {
        if self.enabled {
            format!("&{}", self.record(key, english, &[]))
        } else {
            format!("\"{english}\"")
        }
    }

    /// [`Self::lit`] in Maud **body** position, where a bare literal renders as
    /// text but any expression must be parenthesised: `"Save"` becomes
    /// `(t!(locale, "common.save"))`.
    pub(super) fn markup(&self, key: &str, english: &str) -> String {
        if self.enabled {
            format!("({})", self.record(key, english, &[]))
        } else {
            format!("\"{english}\"")
        }
    }

    /// [`Self::expr`] in Maud body position.
    pub(super) fn markup_expr(
        &self,
        key: &str,
        ftl: &str,
        plain: &str,
        args: &[(&str, &str)],
    ) -> String {
        if self.enabled {
            format!("({})", self.record(key, ftl, args))
        } else {
            plain.to_owned()
        }
    }

    /// The general form: `plain` is the **complete** Rust expression the
    /// non-i18n scaffold emits (often a `format!(…)` call), `ftl` the Fluent
    /// value — which may carry `{ $arg }` placeholders fed by `args`, each a
    /// `(fluent name, Rust expression)` pair.
    pub(super) fn expr(&self, key: &str, ftl: &str, plain: &str, args: &[(&str, &str)]) -> String {
        if self.enabled {
            self.record(key, ftl, args)
        } else {
            plain.to_owned()
        }
    }

    /// [`Self::expr`] for a `&str` parameter.
    pub(super) fn expr_ref(
        &self,
        key: &str,
        ftl: &str,
        plain: &str,
        args: &[(&str, &str)],
    ) -> String {
        if self.enabled {
            format!("&{}", self.record(key, ftl, args))
        } else {
            plain.to_owned()
        }
    }
}

/// Split a `.ftl` source into its defined keys.
///
/// Mirrors the minimal parser in `autumn-macros`' `t!` validation and
/// `autumn-web`'s `Bundle` loader: a top-level `key = value` line, with `#`
/// comments and indented continuation lines skipped.
pub(super) fn defined_keys(src: &str) -> BTreeMap<String, String> {
    src.lines()
        .filter(|line| {
            !line.trim_start().starts_with('#')
                && !line.trim().is_empty()
                && !line.starts_with(' ')
                && !line.starts_with('\t')
        })
        .filter_map(|line| line.split_once('='))
        .map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))
        .collect()
}

/// Merge the keys a `--i18n` scaffold referenced into `existing` (the project's
/// `i18n/en.ftl`, or `""` when there is none yet).
///
/// Semantics, in order of importance:
///
/// 1. **A key that already exists is never rewritten.** Re-running the
///    generator over a file whose English has been edited — or whose keys a
///    translator has already worked from — must not clobber it.
/// 2. **Shared chrome is written once.** `common.*` keys land in one block that
///    later resources add to rather than duplicate (AC5).
/// 3. **The resource's own keys are grouped** under a marked comment, so a
///    translator reads the file by resource and `autumn destroy scaffold` can
///    remove exactly what this generator added.
///
/// Returns `existing` unchanged when every key is already defined, so the
/// generator can skip the write and leave the file out of the plan.
/// Back-fill a bundle with the keys a render referenced, reconciling the
/// resource's block against them.
///
/// Takes the set of keys a live call site still names, ALWAYS. Reconciliation
/// prunes, and pruning a key some surviving code still looks up breaks the
/// build at COMPILE time; a convenience entry point that quietly passed no
/// such set is exactly how one of the two merge sites came to be missing it.
///
/// Regeneration reconciles the resource block against the keys the NEW render
/// emits, which is how a dropped field or flag stops leaving orphans behind.
/// But "this render no longer emits it" is not "nothing uses it": hand-written
/// code outside the generated module can call `t!(locale, "post.field.subtitle")`,
/// and `t!` validates key existence at COMPILE time, so pruning it breaks the
/// build — the same failure `destroy` already scans the project to avoid.
/// Passing the same set through both paths is what keeps them agreeing.
pub(super) fn merge_en_ftl_keeping(
    existing: &str,
    pascal_name: &str,
    resource: &str,
    keys: &BTreeMap<String, String>,
    still_referenced: &std::collections::HashSet<String>,
) -> String {
    use std::fmt::Write as _;

    let already = defined_keys(existing);
    let resource_prefix = format!("{resource}.");
    let resource_header = format!("{RESOURCE_HEADER_PREFIX}{pascal_name}{RESOURCE_HEADER_SUFFIX}");
    // A resource literally named `Common` would share its prefix with the chrome
    // block. `plan_scaffold_with_options_impl` refuses that name under `--i18n`;
    // classifying chrome FIRST and taking the resource's keys from what is left
    // is the belt-and-braces half, so no key can ever be written to both blocks
    // even from a hand-built plan.
    let missing_common: Vec<(&String, &String)> = keys
        .iter()
        .filter(|(k, _)| k.starts_with("common.") && !already.contains_key(*k))
        .collect();
    let missing_resource: Vec<(&String, &String)> = keys
        .iter()
        .filter(|(k, _)| {
            k.starts_with(&resource_prefix)
                && !k.starts_with("common.")
                && !already.contains_key(*k)
        })
        .collect();
    // Reconciled before the nothing-to-do check below: a regeneration that dropped a field
    // or a flag has every remaining key already present, so the "missing" sets are empty
    // while the block still carries keys the rewritten routes no longer reference — exactly
    // what `autumn i18n check --strict` fails on. Values, comments, and blank lines for
    // surviving keys carry over.
    //
    // The shared chrome is never pruned here: every resource writes those keys, so dropping
    // one from this resource's render would delete a key a sibling still uses. Chrome is
    // additive, and `destroy` is what eventually takes it. Keys a surviving call site still
    // names are held back from the prune — but only ones the bundle already defines, since
    // a reference to a key no `.ftl` carries was already failing `t!` before this ran, and
    // reconciliation must not invent an empty message for it.
    let mut wanted = keys.clone();
    for key in still_referenced {
        if key.starts_with(&resource_prefix)
            && !key.starts_with("common.")
            && already.contains_key(key)
        {
            wanted.entry(key.clone()).or_default();
        }
    }
    if let Some(reconciled) = reconcile_block(existing, &resource_header, &resource_prefix, &wanted)
    {
        return merge_en_ftl_keeping(&reconciled, pascal_name, resource, keys, still_referenced);
    }
    if missing_common.is_empty() && missing_resource.is_empty() {
        return existing.to_owned();
    }

    // Re-running the generator — after adding a column, or with a flag that
    // brings new chrome — must extend the block that already exists rather than
    // strand the new key at EOF under no header at all. The file's whole promise
    // to a translator is that it reads by section.
    if !missing_common.is_empty()
        && let Some(insert_at) = block_end(existing, COMMON_HEADER)
    {
        let mut out = String::with_capacity(existing.len() + missing_common.len() * 48);
        out.push_str(&existing[..insert_at]);
        for (key, value) in &missing_common {
            let _ = writeln!(out, "{key} = {value}");
        }
        out.push_str(&existing[insert_at..]);
        // Whatever the resource block still needs lands on the next pass, which
        // terminates: the chrome keys are now all present.
        return merge_en_ftl_keeping(&out, pascal_name, resource, keys, still_referenced);
    }

    let mut out = String::with_capacity(existing.len() + (keys.len() + 4) * 48);
    if existing.is_empty() {
        out.push_str(
            "# Generated by `autumn generate scaffold --i18n`.\n\
             #\n\
             # This is the DEFAULT locale — leave these values in their own language.\n\
             # To add a locale, copy this file to `i18n/<tag>.ftl` and translate THERE.\n\
             # Keys are grouped by resource; `common.*` is shared chrome every\n\
             # scaffolded resource reuses.\n\n",
        );
    } else {
        out.push_str(existing);
        if !out.ends_with('\n') {
            out.push('\n');
        }
        out.push('\n');
    }

    if !missing_common.is_empty() {
        out.push_str(COMMON_HEADER);
        out.push('\n');
        for (key, value) in missing_common {
            let _ = writeln!(out, "{key} = {value}");
        }
        out.push_str(COMMON_FOOTER);
        out.push('\n');
        if !missing_resource.is_empty() {
            out.push('\n');
        }
    }
    if !missing_resource.is_empty() {
        if !existing.contains(&resource_header) {
            out.push_str(&resource_header);
            out.push('\n');
        }
        for (key, value) in missing_resource {
            let _ = writeln!(out, "{key} = {value}");
        }
        out.push_str(&block_footer(&resource_header));
        out.push('\n');
    }
    out
}

/// Rewrite the block `header` opens so its keys are exactly `keys`' entries
/// under `prefix`, or `None` when there is no such block or it already matches.
///
/// Existing VALUES win — a translated `post.new = Nouvel article` stays put —
/// and non-key lines (a translator's comment, a blank line grouping fields) are
/// carried through in place. Only keys the current render no longer references
/// are dropped, which is the whole point: they have no call sites left, so
/// `autumn i18n check --strict` would fail on them.
fn reconcile_block(
    existing: &str,
    header: &str,
    prefix: &str,
    keys: &BTreeMap<String, String>,
) -> Option<String> {
    use std::fmt::Write as _;
    let end = block_end(existing, header)?;
    let start = existing.find(header)?;
    let body_start = start + existing[start..].find('\n').map_or(0, |i| i + 1);
    // The `common.` exclusion applies only when reconciling a RESOURCE block —
    // a resource named `Common` is refused, but a hand-built plan could still
    // reach here. Pruning the chrome block passes `prefix == "common."`, where
    // the exclusion must not fire.
    let wanted: BTreeMap<&str, &str> = keys
        .iter()
        .filter(|(k, _)| {
            k.starts_with(prefix) && (prefix == "common." || !k.starts_with("common."))
        })
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();

    let mut body = String::new();
    let mut keeping_continuations = false;
    for line in existing[body_start..end].lines() {
        // INDENTATION decides first, before any `=` split. A Fluent
        // continuation is just indented text and usually contains no `=` at
        // all (`    and a second line`), so testing for `=` first would file it
        // as a comment and keep it even when its key is being dropped —
        // producing exactly the orphan this reconciliation exists to avoid:
        // the loader either rejects it or silently glues it onto the message
        // above.
        if line.starts_with(' ') || line.starts_with('\t') {
            if keeping_continuations {
                body.push_str(line);
                body.push('\n');
            }
            continue;
        }
        // COMMENTS are tested before the `=` split, and do not end a value.
        // Both halves matter, and both mirror `parse_ftl` (`autumn/src/i18n.rs`)
        // rather than guessing:
        //
        //   * A comment carrying an `=` (`# use post.x = y here`) would
        //     otherwise be read as a key line, found absent from `wanted`, and
        //     deleted — taking a translator's note with it.
        //   * `parse_ftl` `continue`s past a comment WITHOUT flushing the
        //     current key, so an indented line after a mid-value comment is
        //     still part of that value at runtime. Ending the value here would
        //     drop the continuation and silently truncate the translation.
        //
        // A BLANK line does flush there, so it still ends the value here.
        if line.trim_start().starts_with('#') {
            body.push_str(line);
            body.push('\n');
            continue;
        }
        let Some((raw_key, _)) = line.split_once('=') else {
            // A blank line at the block's own indentation — keep it where the
            // translator put it. It ends the previous key's value.
            keeping_continuations = false;
            body.push_str(line);
            body.push('\n');
            continue;
        };
        if wanted.contains_key(raw_key.trim()) {
            keeping_continuations = true;
            body.push_str(line);
            body.push('\n');
        } else {
            // Dropped: its continuation lines go with it.
            keeping_continuations = false;
        }
    }
    // Scanned over the WHOLE file, not just this block. A key can be defined
    // outside the block a translator never touched — hand-authored above it, or
    // left behind by an older layout — and appending a second definition here
    // would not merely duplicate it: `parse_ftl` inserts each entry into a map
    // in file order (`autumn/src/i18n.rs`), so the LAST definition wins. The
    // generated English would silently replace the translation above it, which
    // is the one thing this merge promises never to do. Reconciliation itself
    // still reads only the block: keys outside it are not the generator's to
    // keep or drop, just its to leave alone.
    let defined_anywhere = defined_keys(existing);
    for (key, value) in &wanted {
        if !defined_anywhere.contains_key(*key) {
            let _ = writeln!(body, "{key} = {value}");
        }
    }

    if body == existing[body_start..end] {
        return None;
    }
    let mut out = String::with_capacity(existing.len());
    out.push_str(&existing[..body_start]);
    out.push_str(&body);
    out.push_str(&existing[end..]);
    Some(out)
}

/// Byte offset just past the last key line of the block `header` introduces, or
/// `None` when `existing` carries no such block. Used for both the shared
/// chrome block and a resource's own.
///
/// The block runs from its header to the first blank line or foreign comment —
/// the same shape [`merge_en_ftl_keeping`] writes.
fn block_end(existing: &str, header: &str) -> Option<usize> {
    let start = existing.find(header)?;
    let mut cursor = start + header.len();
    // Step past the header's own newline.
    cursor += existing[cursor..].find('\n').map_or(0, |i| i + 1);
    let footer = block_footer(header);
    let mut end = cursor;
    for line in existing[cursor..].split_inclusive('\n') {
        if line.trim_end() == footer {
            return Some(end);
        }
        end += line.len();
    }
    // No footer: a bundle written before blocks were explicitly closed. Fall
    // back to the old boundary — the first blank line or foreign comment — so
    // an existing project still merges and destroys correctly.
    let mut end = cursor;
    for line in existing[cursor..].split_inclusive('\n') {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            break;
        }
        end += line.len();
    }
    Some(end)
}

/// Inverse of [`merge_en_ftl_keeping`] for `autumn destroy scaffold` — remove one
/// resource's block (its marked comment plus every `<resource>.` key) from
/// `existing`.
///
/// The shared `common.*` block is deliberately left alone: other scaffolded
/// resources reuse it, and it is what keeps the file non-empty. That matters —
/// the generated app calls `.i18n_auto()`, which panics at startup if the
/// default locale's file is missing, so destroy must never empty or delete it.
pub(super) fn remove_en_ftl_keys(
    existing: &str,
    pascal_name: &str,
    resource: &str,
    // Every key surviving project source still looks up — the resource's own as
    // much as the shared chrome. The caller scans the project for these,
    // because the bundle itself cannot answer it: a resource whose keys were
    // all hand-authored before it was scaffolded leaves no marker comment
    // behind, so "no other marker" does NOT mean "no other user".
    surviving: &std::collections::HashSet<String>,
) -> String {
    let stripped = prune_resource_block(existing, pascal_name, resource, surviving);
    // Chrome exists to be shared. Once nothing references it, every `common.*`
    // key is dead weight — which is exactly what `autumn i18n check --strict`
    // fails on, so destroying the only `--i18n` resource would otherwise leave
    // the project's own lint red. But the asymmetry matters: an orphan key is a
    // lint warning, while removing one a surviving resource still calls is a
    // COMPILE error (`t!` validates key existence at compile time). So this errs
    // toward keeping.
    //
    // Never the FILE, either way: `.i18n_auto()` panics at startup when the
    // default locale's bundle is missing, and a comment-only bundle still loads.
    prune_chrome_block(&stripped, surviving)
}

/// Narrow the shared chrome block to the keys `surviving` still names, dropping
/// the block entirely when nothing is left.
///
/// Per KEY, not all-or-nothing. Chrome is per-surface: `common.trash`,
/// `common.restore` and `common.purge` come from `--soft-delete`, `common.next`
/// from the pager, `common.export.csv` from the CSV link. Destroying the only
/// resource that had a Trash view leaves those three referenced by nothing —
/// which `autumn i18n check --strict` fails on — while `common.create`,
/// `common.save` and the rest are still in use by every sibling and must stay.
///
/// Marker-bounded like [`remove_marked_block`], so a hand-authored `common.*`
/// key outside the block is never touched.
fn prune_chrome_block(existing: &str, surviving: &std::collections::HashSet<String>) -> String {
    // No source names the framework key (#2439), so the scan never reports it.
    // It stays while any chrome key stays, because then a sibling scaffold
    // still has a form.
    let mut surviving = surviving.clone();
    if surviving.iter().any(|key| key.starts_with("common.")) {
        surviving.insert(NUL_MESSAGE_KEY.to_owned());
    }
    prune_block(existing, COMMON_HEADER, "common.", &surviving)
}

/// Narrow one resource's block to the keys `surviving` still names, dropping
/// the block entirely when nothing is left.
///
/// Per KEY for the same reason the chrome block is, and it is the same failure:
/// hand-written code outside the generated module can reference a generated
/// key — `t!(locale, "post.index.title")` on a dashboard card or a nav link is
/// an ordinary thing for an app to do — and taking the whole `post.*` block out
/// from under it breaks the build, because `t!` validates key existence at
/// COMPILE time. Restricting preservation to `common.*` drew the line in the
/// wrong place: nothing about a `post.` prefix makes a live call site less
/// live. Keys nothing references still go, so `autumn i18n check --strict` does
/// not go red on the leftovers.
fn prune_resource_block(
    existing: &str,
    pascal_name: &str,
    resource: &str,
    surviving: &std::collections::HashSet<String>,
) -> String {
    let header = format!("{RESOURCE_HEADER_PREFIX}{pascal_name}{RESOURCE_HEADER_SUFFIX}");
    prune_block(existing, &header, &format!("{resource}."), surviving)
}

/// Shared body of [`prune_chrome_block`] and [`prune_resource_block`]: keep the
/// block's keys that `surviving` names under `prefix`, drop the rest, and take
/// the whole marked block out when that leaves nothing.
///
/// Marker-bounded like [`remove_marked_block`], so a hand-authored key outside
/// the block is never touched.
fn prune_block(
    existing: &str,
    header: &str,
    prefix: &str,
    surviving: &std::collections::HashSet<String>,
) -> String {
    // Only keys the bundle actually DEFINES. `surviving` is a scan of source,
    // so it can name a key no `.ftl` carries — a call site that was already
    // failing `t!` before any of this ran — and `reconcile_block` appends keys
    // it does not find defined. Destroy inventing an empty message for one is
    // strictly worse than leaving the pre-existing breakage alone.
    let defined = defined_keys(existing);
    let kept: BTreeMap<String, String> = surviving
        .iter()
        .filter(|key| key.starts_with(prefix) && defined.contains_key(*key))
        .map(|key| (key.clone(), String::new()))
        .collect();
    if kept.is_empty() {
        return remove_marked_block(existing, header);
    }
    // `reconcile_block` keeps each surviving key's own value and drops the
    // rest — the empty values above are never written, since every key it keeps
    // is already defined.
    reconcile_block(existing, header, prefix, &kept).unwrap_or_else(|| existing.to_owned())
}

/// Remove the marked comment `header` and the run of key lines it introduces.
///
/// Bounded by the MARKER, not by key prefix. A prefix sweep would also delete a
/// hand-authored `post.email.subject` — a translation the application owns,
/// which this generator never wrote and has no business removing — purely
/// because it happens to start with the resource's name. The merge path goes to
/// some trouble never to overwrite a value somebody else authored; destroy has
/// to be equally careful about what it takes away. So removal covers exactly
/// the block `merge_en_ftl` writes: the header line, then every following line
/// up to the first blank line or foreign comment.
///
/// That run includes any INDENTED continuation lines. Leaving those behind is
/// how a destroy corrupts a bundle: the loader either rejects the orphan
/// outright — and `.i18n_auto()` turns that into a startup panic — or silently
/// glues it onto whichever key precedes it, rewriting an unrelated translation.
fn remove_marked_block(existing: &str, header: &str) -> String {
    let Some(end) = block_end(existing, header) else {
        return existing.to_owned();
    };
    let start = existing.find(header).expect("block_end found the header");
    // `block_end` stops just BEFORE the closing marker; take that line too.
    let footer = block_footer(header);
    let end = existing[end..]
        .strip_prefix(footer.as_str())
        .map_or(end, |rest| {
            end + footer.len() + usize::from(rest.starts_with('\n'))
        });
    let mut out = String::with_capacity(existing.len());
    out.push_str(&existing[..start]);
    out.push_str(&existing[end..]);
    let lines: Vec<&str> = out.lines().collect();
    collapse_blank_runs(&lines)
}

/// Re-join `lines`, collapsing the blank runs a removed block leaves behind and
/// restoring the file's single trailing newline.
fn collapse_blank_runs(lines: &[&str]) -> String {
    let mut joined = String::with_capacity(lines.iter().map(|l| l.len() + 1).sum());
    let mut prev_blank = false;
    for line in lines {
        let blank = line.trim().is_empty();
        if blank && prev_blank {
            continue;
        }
        prev_blank = blank;
        joined.push_str(line);
        joined.push('\n');
    }
    while joined.ends_with("\n\n") {
        joined.pop();
    }
    joined
}

/// The name of the TOML table `line` opens, if it opens one.
///
/// Tolerates the spacing and trailing comments TOML allows — `[ i18n ]` and
/// `[i18n] # locale settings` are both the i18n table. Getting this wrong is not
/// cosmetic: missing an existing table makes the generator append a SECOND
/// `[i18n]`, and a duplicate table makes the whole file unparseable, taking the
/// application's entire configuration down with it.
fn toml_table_name(line: &str) -> Option<&str> {
    let trimmed = line.trim();
    let rest = trimmed.strip_prefix('[')?;
    let close = rest.find(']')?;
    // Anything after the closing bracket must be blank or a comment — otherwise
    // this is not a table header at all.
    let tail = rest[close + 1..].trim();
    if !tail.is_empty() && !tail.starts_with('#') {
        return None;
    }
    // `["i18n"]` names the same table as `[i18n]` — TOML lets any key be
    // quoted. Left quoted, the name never matches, so the caller concludes
    // there is no `[i18n]` table and appends one: a SECOND definition of the
    // same table, which makes `autumn.toml` unparseable for the app that has
    // to read it.
    let name = rest[..close].trim();
    Some(
        name.strip_prefix('"')
            .and_then(|n| n.strip_suffix('"'))
            .or_else(|| name.strip_prefix('\'').and_then(|n| n.strip_suffix('\'')))
            .unwrap_or(name),
    )
}

/// A TOML key with any quoting removed.
///
/// `"default_locale" = "fr"` is the same key as `default_locale = "fr"` — TOML
/// lets any key be quoted, and serde's loader reads both. Compared with its
/// quotes still on, the key never matches and the generator falls back to `en`,
/// writing its output where the runtime does not look.
fn toml_key_name(raw: &str) -> &str {
    let key = raw.trim();
    key.strip_prefix('"')
        .and_then(|k| k.strip_suffix('"'))
        .or_else(|| key.strip_prefix('\'').and_then(|k| k.strip_suffix('\'')))
        .unwrap_or(key)
}

/// The scalar on the right of a TOML `key = value`, unquoted, with any trailing
/// comment removed.
///
/// The comment has to be stripped with the quoting in mind, not before it: `#`
/// is an ordinary character inside a string, so cutting at the first `#` would
/// mangle `dir = "i18n#v2"`, while ignoring comments entirely turns
/// `default_locale = "fr" # our default` into the locale tag
/// `fr" # our default` — and the generator would then cheerfully create a file
/// named after it. Returns `None` for an empty or unparseable value.
fn toml_scalar_value(raw: &str) -> Option<String> {
    let trimmed = raw.trim_start();
    let quote = trimmed.chars().next()?;
    let value = if quote == '"' || quote == '\'' {
        let rest = &trimmed[quote.len_utf8()..];
        // A BASIC string (double quotes) processes escapes; a LITERAL string
        // (single quotes) does not, by TOML's definition. Both of these values
        // become filesystem paths, so the raw source text is the wrong thing to
        // build them from: the app's loader reads the DECODED value, and
        // `dir = "i18n\\bundles"` on Windows would otherwise have the generator
        // writing to a directory with a literal double backslash in its name
        // while the runtime reads the single-backslash one.
        //
        // The terminator has to respect escapes for the same reason: a `\"` is
        // part of the value, so stopping at it would truncate the path.
        if quote == '"' {
            let mut end = None;
            let mut escaped = false;
            for (i, c) in rest.char_indices() {
                if escaped {
                    escaped = false;
                } else if c == '\\' {
                    escaped = true;
                } else if c == '"' {
                    end = Some(i);
                    break;
                }
            }
            decode_toml_escapes(&rest[..end?])
        } else {
            rest[..rest.find(quote)?].to_owned()
        }
    } else {
        // A bare value runs to the first comment marker or end of line.
        trimmed
            .split_once('#')
            .map_or(trimmed, |(before, _)| before)
            .trim_end()
            .to_owned()
    };
    (!value.is_empty()).then_some(value)
}

/// Split an inline table's body on the commas that separate its members.
///
/// Quote-aware: a comma inside a value belongs to the value. `dir =
/// "translations,v2"` is a legal directory name, and splitting through it
/// leaves `toml_scalar_value` with an unterminated string, which it discards —
/// so the generator would silently fall back to `i18n/` and write its keys
/// where the runtime never looks.
///
/// Escapes are honoured while scanning so a `\"` inside a basic string does not
/// end it. Literal (single-quoted) strings process no escapes, per TOML.
fn split_inline_members(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut current = String::new();
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for c in body.chars() {
        match quote {
            Some(q) => {
                current.push(c);
                if escaped {
                    escaped = false;
                } else if c == '\\' && q == '"' {
                    escaped = true;
                } else if c == q {
                    quote = None;
                }
            }
            None if c == '"' || c == '\'' => {
                quote = Some(c);
                current.push(c);
            }
            None if c == ',' => out.push(std::mem::take(&mut current)),
            None => current.push(c),
        }
    }
    out.push(current);
    out
}

/// Render `value` as the contents of a Rust double-quoted string literal.
///
/// A configured `dir` is interpolated into generated Rust (`embed_locales!`),
/// and TOML happily carries characters that Rust's lexer reads as escapes: the
/// Windows-shaped `dir = 'translations\bundles'` would emit `\b`, which is not
/// a Rust escape at all, so the generated `main.rs` stops parsing — before any
/// embed build, and for a project that merely configured a directory.
fn rust_string_escape(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Decode the escape sequences TOML defines for a basic string.
///
/// An unknown or malformed escape is passed through verbatim rather than
/// rejected: this is a best-effort read of a file the app's own loader
/// validates properly, and a generator that refused to run over a `dir` it
/// could not decode would be worse than one that used the text as written.
fn decode_toml_escapes(src: &str) -> String {
    let mut out = String::with_capacity(src.len());
    let mut chars = src.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        let Some(esc) = chars.next() else {
            out.push('\\');
            break;
        };
        match esc {
            'b' => out.push('\u{8}'),
            't' => out.push('\t'),
            'n' => out.push('\n'),
            'f' => out.push('\u{c}'),
            'r' => out.push('\r'),
            '"' => out.push('"'),
            '\\' => out.push('\\'),
            'u' | 'U' => {
                let width = if esc == 'u' { 4 } else { 8 };
                let digits: String = chars.clone().take(width).collect();
                if let Some(decoded) = u32::from_str_radix(&digits, 16)
                    .ok()
                    .filter(|_| digits.len() == width)
                    .and_then(char::from_u32)
                {
                    out.push(decoded);
                    for _ in 0..width {
                        chars.next();
                    }
                } else {
                    out.push('\\');
                    out.push(esc);
                }
            }
            other => {
                out.push('\\');
                out.push(other);
            }
        }
    }
    out
}

/// Whether `autumn.toml` already defines i18n configuration **in any of TOML's
/// spellings**, so a second definition must not be appended.
///
/// TOML expresses the same table three ways, and all three collide with an
/// appended `[i18n]`:
///
/// ```toml
/// [i18n]                                       # a table header
/// i18n = { default_locale = "fr" }             # an inline table
/// i18n.default_locale = "fr"                   # a dotted key
/// ```
///
/// Missing any of them is not cosmetic: the generator appends `[i18n]`, TOML
/// rejects the duplicate definition, and the application can no longer load its
/// configuration at all. A dotted `i18n.x` under some other table
/// (`[server]\ni18n.x = …`) is a different key entirely, so only top-level ones
/// count.
/// Whether `autumn.toml` defines i18n configuration.
///
/// Parsed with the real TOML parser, which is already a direct dependency of
/// this crate. The line scan below has been extended once per round for
/// another spelling TOML allows — `[i18n]`, `["i18n"]`, `i18n = { … }`,
/// `"i18n" = { … }`, `i18n.default_locale`, `"i18n".default_locale`, quoted
/// member keys, escaped values, commas inside quoted values — and each miss
/// had the generator append a SECOND `[i18n]` table, which makes the file
/// unparseable for the app that has to read it. Enumerating token classes by
/// hand does not converge; `toml::Table` knows them all.
///
/// The scan survives as the fallback for a file that does not parse. That is
/// deliberate and predates this: a malformed `autumn.toml` should not fail
/// generation here, because the app's own loader reports it far better.
fn defines_i18n(autumn_toml: &str) -> bool {
    autumn_toml.parse::<toml::Table>().map_or_else(
        |_| defines_i18n_by_scan(autumn_toml),
        |table| table.contains_key("i18n"),
    )
}

/// What an existing `autumn.toml` configures for i18n, as
/// `(default_locale, dir)`.
///
/// Structural for the same reason as [`defines_i18n`], and with the same
/// fallback. Reading these from the source text rather than the parsed value
/// is what sent generated keys to `i18n/en.ftl` while the runtime loaded
/// `translations/fr.ftl`.
pub(super) fn configured_i18n(autumn_toml: &str) -> (Option<String>, Option<String>) {
    let Ok(table) = autumn_toml.parse::<toml::Table>() else {
        return configured_i18n_by_scan(autumn_toml);
    };
    let i18n = table.get("i18n");
    let member = |key: &str| {
        i18n.and_then(|v| v.get(key))
            .and_then(toml::Value::as_str)
            .map(str::to_owned)
    };
    (member("default_locale"), member("dir"))
}

fn defines_i18n_by_scan(autumn_toml: &str) -> bool {
    let mut at_top_level = true;
    for line in autumn_toml.lines() {
        if let Some(name) = toml_table_name(line) {
            if name == "i18n" {
                return true;
            }
            at_top_level = false;
            continue;
        }
        if !at_top_level {
            continue;
        }
        let trimmed = line.trim();
        if let Some((key, _)) = trimmed.split_once('=') {
            let key = key.trim();
            if key == "i18n" || key.starts_with("i18n.") {
                return true;
            }
        }
    }
    false
}

/// What an existing `autumn.toml` configures for i18n: the default locale, and
/// the directory its bundles live in.
///
/// Both matter for where the generated keys go. The runtime resolves lookups
/// through `<dir>/<default_locale>.ftl`, so writing to a hardcoded
/// `i18n/en.ftl` in a project configured otherwise leaves the app's real bundle
/// without a single generated key: every label renders as a visible `{$key}`
/// placeholder, and `autumn i18n check` reports them all missing — while `t!`'s
/// compile-time validation (which looks under `i18n/` for `en` by default)
/// passes, so nothing catches it until runtime.
///
/// Deliberately a line scan rather than a TOML parse: this needs two keys, the
/// file may carry profile overlays the generator has no business interpreting,
/// and a malformed `autumn.toml` should not fail generation here — the app's own
/// loader reports that far better. `[profile.<env>.i18n]` overlays are ignored:
/// the generator writes the base bundle, which every profile inherits.
fn configured_i18n_by_scan(autumn_toml: &str) -> (Option<String>, Option<String>) {
    let mut in_i18n = false;
    let mut at_top_level = true;
    let (mut locale, mut dir) = (None, None);
    for line in autumn_toml.lines() {
        if let Some(name) = toml_table_name(line) {
            in_i18n = name == "i18n";
            at_top_level = false;
            continue;
        }
        let trimmed = line.trim();
        let Some((raw_key, value)) = trimmed.split_once('=') else {
            continue;
        };
        // Dotted keys (`i18n.default_locale = "fr"`) carry the table in the key
        // itself, so they are read at top level rather than inside `[i18n]`.
        let (key, value) = if in_i18n {
            (raw_key, value)
        } else if at_top_level {
            match raw_key.trim().strip_prefix("i18n.") {
                Some(rest) => (rest, value),
                // An inline `i18n = { default_locale = "fr", … }`: read the
                // members out of the braces.
                None if raw_key.trim() == "i18n" => {
                    for member in
                        split_inline_members(value.trim().trim_matches(|c| c == '{' || c == '}'))
                    {
                        let member = member.as_str();
                        let Some((k, v)) = member.split_once('=') else {
                            continue;
                        };
                        let Some(v) = toml_scalar_value(v) else {
                            continue;
                        };
                        match toml_key_name(k) {
                            "default_locale" => locale = Some(v.clone()),
                            "dir" => dir = Some(v.clone()),
                            _ => {}
                        }
                    }
                    continue;
                }
                None => continue,
            }
        } else {
            continue;
        };
        let Some(value) = toml_scalar_value(value) else {
            continue;
        };
        match toml_key_name(key) {
            "default_locale" => locale = Some(value.clone()),
            "dir" => dir = Some(value.clone()),
            _ => {}
        }
    }
    (locale, dir)
}

/// The two environment variables `t!`'s compile-time key check reads, as the
/// COMPILER will see them.
///
/// `t!` does not read `autumn.toml`. It resolves its validation bundle from
/// `AUTUMN_I18N_FILE`, else `$CARGO_MANIFEST_DIR/i18n/$AUTUMN_I18N_DEFAULT_LOCALE.ftl`
/// with the locale defaulting to `en` (`autumn-macros/src/i18n.rs`), and
/// degrades to a runtime lookup when neither exists. A generator that assumes
/// `i18n/en.ftl` keeps the wrong file in step: with the locale set to `fr` the
/// validator reads `i18n/fr.ftl`, which then lacks every key just generated,
/// and `cargo check` fails with a `compile_error!` per lookup.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct MacroEnv {
    pub(super) file: Option<String>,
    pub(super) default_locale: Option<String>,
}

impl MacroEnv {
    /// The process environment, with the project's own `.cargo/config.toml`
    /// `[env]` table layered underneath — which is where a setting the macro
    /// needs on EVERY build realistically lives, and which this process does
    /// not otherwise inherit.
    ///
    /// The WHOLE hierarchy cargo reads, not just the project's own file: an app
    /// generated inside a workspace usually inherits its build settings from
    /// the workspace root, and reading only `<project>/.cargo` there takes a
    /// locale cargo never applies and keeps the wrong bundle in step.
    pub(super) fn resolve(project_root: &Path) -> Self {
        let mut configured: BTreeMap<String, (String, bool)> = BTreeMap::new();
        for (base, path) in cargo_config_files(project_root) {
            let Ok(text) = std::fs::read_to_string(&path) else {
                continue;
            };
            // NEAREST FIRST, so an entry already seen keeps its value: cargo
            // merges the chain with the closer file winning.
            for (name, entry) in cargo_config_env(&text, &base) {
                configured.entry(name).or_insert(entry);
            }
        }
        let read = |name: &str| layer_cargo_env(configured.get(name), std::env::var(name).ok());
        Self {
            file: read("AUTUMN_I18N_FILE"),
            default_locale: read("AUTUMN_I18N_DEFAULT_LOCALE"),
        }
    }
}

/// The cargo config files that apply to a build run in `project_root`, nearest
/// first, as `(base directory for `relative` entries, file)`.
///
/// Cargo's hierarchical structure: `.cargo/config[.toml]` in the directory and
/// each ancestor, then `$CARGO_HOME`'s own. Walking it is the point — a
/// generated app nested in a workspace typically carries no `.cargo` of its
/// own and inherits the root's.
fn cargo_config_files(project_root: &Path) -> Vec<(PathBuf, PathBuf)> {
    let mut out: Vec<(PathBuf, PathBuf)> = project_root
        .ancestors()
        .filter_map(|dir| {
            cargo_config_in(&dir.join(".cargo")).map(|path| (dir.to_path_buf(), path))
        })
        .collect();
    // `$CARGO_HOME/config[.toml]` is consulted last, so it loses to every file
    // above. Its own `relative` entries resolve against the directory holding
    // it, the same rule the rest of the chain follows.
    if let Some(home) = cargo_home()
        && let Some(path) = cargo_config_in(&home)
    {
        let base = home.parent().unwrap_or(&home).to_path_buf();
        if !out.iter().any(|(_, existing)| *existing == path) {
            out.push((base, path));
        }
    }
    out
}

/// The config file in one `.cargo` directory, if any.
///
/// EXTENSIONLESS FIRST. With both present cargo warns "both `…/config` and
/// `…/config.toml` exist. Using `…/config`" and applies the extensionless one
/// for backwards compatibility.
fn cargo_config_in(dir: &Path) -> Option<PathBuf> {
    ["config", "config.toml"]
        .into_iter()
        .map(|name| dir.join(name))
        .find(|path| path.is_file())
}

/// `$CARGO_HOME`, or the conventional `~/.cargo` when it is unset.
fn cargo_home() -> Option<PathBuf> {
    if let Some(home) = std::env::var_os("CARGO_HOME") {
        return Some(PathBuf::from(home));
    }
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(|home| PathBuf::from(home).join(".cargo"))
}

/// One variable's value as cargo would set it: a config entry applies only when
/// the process does not already carry the variable, unless the entry asks to
/// `force`.
fn layer_cargo_env(
    configured: Option<&(String, bool)>,
    from_process: Option<String>,
) -> Option<String> {
    match configured {
        Some((value, force)) if *force || from_process.is_none() => Some(value.clone()),
        _ => from_process,
    }
}

/// The `[env]` table of one cargo config file, as `name -> (value, force)`.
///
/// An entry is either a bare string or a table carrying `value` plus the
/// optional `force` and `relative` flags; `relative` makes the value a path
/// resolved against `base` — the directory holding this file's `.cargo`, which
/// is the rule cargo itself follows, and which differs per file once the whole
/// ancestor chain is read.
fn cargo_config_env(config: &str, base: &Path) -> BTreeMap<String, (String, bool)> {
    let Ok(table) = config.parse::<toml::Table>() else {
        return BTreeMap::new();
    };
    let Some(env) = table.get("env").and_then(toml::Value::as_table) else {
        return BTreeMap::new();
    };
    env.iter()
        .filter_map(|(name, entry)| {
            let (value, force, relative) = match entry {
                toml::Value::String(value) => (value.clone(), false, false),
                toml::Value::Table(fields) => (
                    fields.get("value")?.as_str()?.to_owned(),
                    fields.get("force").and_then(toml::Value::as_bool) == Some(true),
                    fields.get("relative").and_then(toml::Value::as_bool) == Some(true),
                ),
                _ => return None,
            };
            let value = if relative {
                base.join(value).to_string_lossy().into_owned()
            } else {
                value
            };
            Some((name.clone(), (value, force)))
        })
        .collect()
}

/// The bundle `t!` will validate against, or `None` when the macro would find
/// none and fall back to a runtime lookup.
///
/// Mirrors `locate_default_bundle` in `autumn-macros/src/i18n.rs`, including
/// its requirement that the file EXIST: an absent bundle means there is no
/// compile-time check to keep in step, and writing one would invent a locale
/// the project deliberately does not have.
pub(super) fn validator_bundle_path(project_root: &Path, env: &MacroEnv) -> Option<PathBuf> {
    if let Some(file) = &env.file {
        // A relative `AUTUMN_I18N_FILE` is resolved by the compiler against its
        // own working directory, which for a cargo build is the workspace root.
        // The project root is that directory for a generated app.
        let path = project_root.join(file);
        if path.is_file() {
            return Some(path);
        }
        // FALLS THROUGH when that file is missing, exactly as the macro does:
        // `locate_default_bundle` guards the explicit path with `is_file()` and
        // then goes on to the locale candidate. Returning `None` here would
        // read a stale or mistyped `AUTUMN_I18N_FILE` as "validation is off"
        // while the macro quietly validates against `i18n/<locale>.ftl`, which
        // then never receives the generated keys — a `compile_error!` per
        // lookup.
    }
    let locale = env.default_locale.as_deref().unwrap_or("en");
    let path = project_root.join("i18n").join(format!("{locale}.ftl"));
    path.is_file().then_some(path)
}

/// Every `.ftl` bundle in the configured locale directory.
///
/// The generator writes only the DEFAULT locale — filling another with English
/// would report as translated and ship English, which is worse than a warning.
/// But destroy has to reach all of them: a translator starts a locale by
/// copying the default bundle and translating in place, so those files carry
/// this resource's marked block too, and leaving it behind fails `autumn i18n
/// check --strict` as unused.
///
/// Sorted, so a plan's reverts and warnings come out in a stable order.
pub(super) fn locale_bundles(project_root: &Path, dir: &str) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(project_root.join(dir)) else {
        return Vec::new();
    };
    let mut out: Vec<PathBuf> = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "ftl"))
        .collect();
    out.sort();
    out
}

/// Ship the `i18n/` sidecar into a generated `Dockerfile`, in both stages.
///
/// `.i18n_auto()` reads `i18n/<default>.ftl` from the working directory at
/// startup and **panics** when it is missing (`autumn/src/app.rs`'s
/// `resolve_i18n_bundle`). `autumn new --with-i18n` handles this by resolving
/// the Dockerfile's i18n anchors; a plain `autumn new` strips them, so a project
/// that adopts `--i18n` later builds an image with no bundle in it and
/// crash-loops on deploy — after a build that looked completely clean, because
/// `t!`'s compile-time key check silently degrades to a runtime lookup when the
/// file is absent from the build context.
///
/// The two `COPY` lines are inserted next to the ones for `migrations/`, which
/// both stages already carry and which sit at exactly the same layer. Returns
/// `None` when the file has no such anchor (a hand-edited or absent Dockerfile),
/// so the caller can warn instead of guessing where to write.
pub(super) fn ensure_dockerfile_i18n_copy(dockerfile: &str, dir: &str) -> Option<String> {
    let builder_anchor = "COPY migrations ./migrations";
    let runtime_anchor = "COPY --from=builder /app/migrations /app/migrations";
    // A `dir` carrying whitespace is a legal path, and the shell form splits on
    // it: `COPY translations v2 ./translations v2` reads as three sources and a
    // destination, so the build either fails or copies the wrong thing. The
    // JSON form is exactly what Docker documents for paths with spaces. Used
    // only when needed, so the ordinary Dockerfile keeps its conventional
    // shell-form lines.
    let (builder_line, runtime_line) = if dir.contains(char::is_whitespace) {
        (
            format!(
                "COPY [{}, {}]",
                json_str(dir),
                json_str(&format!("./{dir}"))
            ),
            format!(
                "COPY --from=builder [{}, {}]",
                json_str(&format!("/app/{dir}")),
                json_str(&format!("/app/{dir}"))
            ),
        )
    } else {
        (
            format!("COPY {dir} ./{dir}"),
            format!("COPY --from=builder /app/{dir} /app/{dir}"),
        )
    };
    // ACTIVE lines, not substrings. Docker strips comments before executing, so
    // a `# COPY i18n ./i18n` left behind as an example installs nothing — and
    // reading it as installed returns the file untouched, after which the
    // container panics in `.i18n_auto()` with no bundle to load. The same rule
    // governs the anchors: inserting after a commented `# COPY migrations …`
    // would put the new line in a stage that never runs it.
    if has_active_line(dockerfile, &builder_line) && has_active_line(dockerfile, &runtime_line) {
        return Some(dockerfile.to_owned());
    }
    let out = insert_after_active_line(dockerfile, runtime_anchor, &runtime_line)?;
    insert_after_active_line(&out, builder_anchor, &builder_line)
}

/// Whether `dockerfile` carries `instruction` as an instruction Docker will
/// run, rather than as a comment or a fragment of a longer line.
fn has_active_line(dockerfile: &str, instruction: &str) -> bool {
    dockerfile.lines().any(|line| line.trim() == instruction)
}

/// `dockerfile` with `new_line` inserted after the first ACTIVE `anchor` line,
/// or `None` when no such line exists.
///
/// Line-oriented rather than a substring `replacen`, so a commented copy of the
/// anchor cannot capture the insertion — and, since each call rebuilds the
/// whole file, the two stages no longer have to be edited in a particular
/// order to keep offsets valid.
fn insert_after_active_line(dockerfile: &str, anchor: &str, new_line: &str) -> Option<String> {
    let mut out = String::with_capacity(dockerfile.len() + new_line.len() + 1);
    let mut inserted = false;
    for line in dockerfile.split_inclusive('\n') {
        out.push_str(line);
        if !inserted && line.trim() == anchor {
            if !line.ends_with('\n') {
                out.push('\n');
            }
            out.push_str(new_line);
            out.push('\n');
            inserted = true;
        }
    }
    inserted.then_some(out)
}

/// The directory an earlier `--i18n` run pointed the Dockerfile's locale
/// `COPY` lines at, when that is no longer the configured `dir`.
///
/// A project that changes `[i18n] dir` after its first `--i18n` scaffold keeps
/// the old pair, and `ensure_dockerfile_i18n_copy` adds a second one for the
/// new directory. That is worth saying out loud: `COPY` fails the build when
/// its source is missing from the context, so a rename that MOVED the old
/// directory stops the image building at all, and one that merely copied it
/// ships a bundle the app never reads.
///
/// Reported rather than rewritten. These lines carry no marker, so "the
/// generator wrote this" can only ever be inferred — and the inference is a
/// shape (`COPY <x> ./<x>`) that an ordinary hand-written `COPY static
/// ./static` matches exactly. A warning that occasionally names the wrong
/// directory costs the reader a second; an edit that silently rewrites
/// someone's asset `COPY` into a locale one costs them their image. So the
/// position is used as corroboration (this generator inserts immediately after
/// the `migrations` anchors) and the result is still only ever advice.
pub(super) fn stale_dockerfile_i18n_dir(dockerfile: &str, dir: &str) -> Option<String> {
    /// The `[src, dest]` of a `COPY`, in EITHER form.
    ///
    /// The JSON form is not optional to support: this generator emits it itself
    /// for a `dir` containing whitespace, so a detector that only splits on
    /// spaces cannot see the very lines it wrote — leaving the stale pair
    /// unreported for exactly the paths that most need quoting.
    fn copy_operands(line: &str, from_builder: bool) -> Option<(String, String)> {
        let rest = line.trim().strip_prefix("COPY ")?.trim_start();
        let rest = if from_builder {
            rest.strip_prefix("--from=builder")?.trim_start()
        } else {
            if rest.starts_with("--") {
                return None;
            }
            rest
        };
        if let Some(inner) = rest.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
            let mut parts = inner.split(',').map(|p| {
                p.trim()
                    .trim_matches('"')
                    .replace("\\\"", "\"")
                    .replace("\\\\", "\\")
            });
            return Some((parts.next()?, parts.next()?));
        }
        let parts: Vec<&str> = rest.split_whitespace().collect();
        match parts.as_slice() {
            [src, dest] => Some(((*src).to_owned(), (*dest).to_owned())),
            _ => None,
        }
    }
    /// The directory in `COPY <x> ./<x>`, in either form.
    fn builder_copy_dir(line: &str) -> Option<String> {
        let (src, dest) = copy_operands(line, false)?;
        (dest.strip_prefix("./") == Some(src.as_str())).then_some(src)
    }
    /// The same for `COPY --from=builder /app/<x> /app/<x>`.
    ///
    /// A NESTED `<x>` counts. `dir = "locales/v1"` is a legal configuration and
    /// this generator writes the pair for it itself, so refusing any path with a
    /// separator held the runtime side to a stricter shape than the builder
    /// side and the two never agreed: moving to `locales/v2` added the new pair
    /// with no warning, and the old `COPY locales/v1 …` stayed behind to fail
    /// the image build once that directory went away.
    fn runtime_copy_dir(line: &str) -> Option<String> {
        let (src, dest) = copy_operands(line, true)?;
        if src != dest {
            return None;
        }
        src.strip_prefix("/app/")
            .filter(|d| !d.is_empty())
            .map(str::to_owned)
    }

    let after = |anchor: &str, extract: fn(&str) -> Option<String>| -> Option<String> {
        let mut lines = dockerfile.lines().skip_while(|l| l.trim() != anchor);
        lines.next()?;
        extract(lines.next()?)
    };

    let builder = after("COPY migrations ./migrations", builder_copy_dir)?;
    let runtime = after(
        "COPY --from=builder /app/migrations /app/migrations",
        runtime_copy_dir,
    )?;
    // Both stages naming the same non-configured directory is what makes this a
    // moved bundle rather than a coincidence.
    (builder == runtime && builder != dir).then_some(builder)
}

/// Profile overlays that point i18n somewhere other than the base config.
///
/// `[profile.prod.i18n]` (and the sibling `autumn-<env>.toml` files) can
/// override `dir` and `default_locale`, and the runtime resolves the FULLY
/// LAYERED config — so a base of `i18n/en.ftl` with a production override of
/// `dir = "translations"` means the image ships `i18n/` while the app boots
/// looking for `translations/`, and `.i18n_auto()` panics.
///
/// The generator deliberately writes the BASE bundle only. Writing English into
/// a profile that exists precisely because it serves a different locale would
/// be its own bug, and there is no way to know which profile a given deploy
/// uses — so this reports the overlays instead, and the caller warns. Returns
/// the `(profile, dir/locale summary)` pairs that differ from the base.
/// The same report for a STANDALONE `autumn-<profile>.toml`, whose `[i18n]`
/// sits at top level rather than under `[profile.<env>.i18n]`.
///
/// These are a separate layer, not a spelling variant: the runtime merges
/// `autumn-{profile}.toml` LAST, after both `autumn.toml` and its inline
/// `[profile.…]` sections (`autumn/src/config.rs`). A project keeping its
/// production config in one of these gets no `[profile.prod.i18n]` for
/// [`profile_i18n_overrides`] to find, so scanning only the base file reports
/// nothing at all — and the deploy that matters is exactly the one pointed
/// somewhere this scaffold never wrote.
///
/// `files` is `(profile name, file contents)`; returns `(profile, path)` for
/// those whose i18n differs from the base.
pub(super) fn profile_file_i18n_overrides(
    files: &[(String, String)],
    base_dir: &str,
    base_locale: &str,
) -> Vec<(String, String)> {
    let mut out = Vec::new();
    for (profile, contents) in files {
        let (locale, dir) = configured_i18n(contents);
        let differs = dir.as_deref().is_some_and(|d| d != base_dir)
            || locale.as_deref().is_some_and(|l| l != base_locale);
        if !differs {
            continue;
        }
        out.push((
            profile.clone(),
            format!(
                "{}/{}.ftl",
                dir.as_deref().unwrap_or(base_dir),
                locale.as_deref().unwrap_or(base_locale)
            ),
        ));
    }
    out
}

pub(super) fn profile_i18n_overrides(
    autumn_toml: &str,
    base_dir: &str,
    base_locale: &str,
) -> Vec<(String, String)> {
    // Structural when the file parses, for the same reason `configured_i18n` is
    // — and this is the half of that change I left undone last round, which
    // produced a finding immediately. `[profile.prod.i18n]` is only ONE of the
    // spellings the runtime merges: `[profile.prod]` with `i18n = { … }`, a
    // dotted `profile.prod.i18n.dir`, and any of them quoted all reach the same
    // table, and a scan keyed on a header ending in `.i18n` sees none of them.
    // Missing one means no warning for a production deploy pointed at a bundle
    // this scaffold never wrote — which is a startup panic, not a cosmetic gap.
    if let Ok(table) = autumn_toml.parse::<toml::Table>() {
        let mut out = Vec::new();
        let profiles = table.get("profile").and_then(toml::Value::as_table);
        for (profile, value) in profiles.into_iter().flatten() {
            let Some(i18n) = value.get("i18n") else {
                continue;
            };
            let member = |key: &str| i18n.get(key).and_then(toml::Value::as_str);
            let (dir, locale) = (member("dir"), member("default_locale"));
            let differs =
                dir.is_some_and(|d| d != base_dir) || locale.is_some_and(|l| l != base_locale);
            if !differs {
                continue;
            }
            out.push((
                profile.clone(),
                format!(
                    "{}/{}.ftl",
                    dir.unwrap_or(base_dir),
                    locale.unwrap_or(base_locale)
                ),
            ));
        }
        out.sort();
        return out;
    }
    profile_i18n_overrides_by_scan(autumn_toml, base_dir, base_locale)
}

fn profile_i18n_overrides_by_scan(
    autumn_toml: &str,
    base_dir: &str,
    base_locale: &str,
) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut current: Option<String> = None;
    let (mut dir, mut locale) = (None, None);
    let mut flush = |profile: Option<String>, dir: Option<String>, locale: Option<String>| {
        let Some(profile) = profile else { return };
        let differs = dir.as_deref().is_some_and(|d| d != base_dir)
            || locale.as_deref().is_some_and(|l| l != base_locale);
        if !differs {
            return;
        }
        let path = format!(
            "{}/{}.ftl",
            dir.as_deref().unwrap_or(base_dir),
            locale.as_deref().unwrap_or(base_locale)
        );
        out.push((profile, path));
    };
    for line in autumn_toml.lines() {
        if let Some(name) = toml_table_name(line) {
            flush(current.take(), dir.take(), locale.take());
            // `[profile.<env>.i18n]`
            current = name
                .strip_prefix("profile.")
                .and_then(|rest| rest.strip_suffix(".i18n"))
                .map(str::to_owned);
            continue;
        }
        if current.is_none() {
            continue;
        }
        let trimmed = line.trim();
        let Some((key, value)) = trimmed.split_once('=') else {
            continue;
        };
        let Some(value) = toml_scalar_value(value) else {
            continue;
        };
        match toml_key_name(key) {
            "default_locale" => locale = Some(value.clone()),
            "dir" => dir = Some(value.clone()),
            _ => {}
        }
    }
    flush(current, dir, locale);
    out
}

/// Add an `[i18n]` block to `autumn.toml` if it has none.
///
/// `default_locale = "en"` matches the `en.ftl` the generator writes; the
/// supported list starts as `["en"]` so an app that adds `fr.ftl` only has to
/// extend one line. A project that already configures `[i18n]` is left alone —
/// its `default_locale` may not be `en`, and rewriting it would silently
/// repoint the bundle the app loads.
pub(super) fn ensure_i18n_config_block(existing: &str) -> String {
    // Match the CONFIGURATION, not the literal text — see `defines_i18n`.
    if defines_i18n(existing) {
        return existing.to_owned();
    }
    let mut out = existing.to_owned();
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    if !out.is_empty() {
        out.push('\n');
    }
    out.push_str("[i18n]\ndefault_locale = \"en\"\nsupported_locales = [\"en\"]\n");
    out
}

/// `value` as a JSON string literal, for Dockerfile's exec/JSON `COPY` form.
fn json_str(value: &str) -> String {
    format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
}

/// Byte offset of a `proc_macro2` source position.
///
/// `proc_macro2` counts a `LineColumn`'s `column` in UTF-8 CHARACTERS, not
/// bytes, so this walks each line's own chars to find the byte offset —
/// the same conversion `proc_macro2` does internally, done here because
/// `main.rs` needs a BYTE range to slice and splice.
struct SourceIndex<'a> {
    src: &'a str,
    /// Byte offset where each 1-indexed source line starts.
    line_starts: Vec<usize>,
}

impl<'a> SourceIndex<'a> {
    fn new(src: &'a str) -> Self {
        let mut line_starts = vec![0];
        line_starts.extend(src.match_indices('\n').map(|(i, _)| i + 1));
        Self { src, line_starts }
    }

    fn byte_offset(&self, at: proc_macro2::LineColumn) -> usize {
        let line_start = self.line_starts[at.line - 1];
        let line_end = self
            .line_starts
            .get(at.line)
            .copied()
            .unwrap_or(self.src.len());
        let mut offset = line_start;
        for ch in self.src[line_start..line_end].chars().take(at.column) {
            offset += ch.len_utf8();
        }
        offset
    }

    /// The byte range a span covers.
    fn range(&self, span: proc_macro2::Span) -> std::ops::Range<usize> {
        self.byte_offset(span.start())..self.byte_offset(span.end())
    }
}

/// Whether `attrs` carries `#[cfg(test)]` exactly — the one attribute this
/// generator excludes production code on.
fn has_cfg_test(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        attr.path().is_ident("cfg")
            && attr
                .parse_args::<syn::Ident>()
                .is_ok_and(|ident| ident == "test")
    })
}

/// The attributes on an item, across every kind `main.rs` can hold at file
/// or module scope.
///
/// `syn::Item` has no shared accessor for attributes. This match covers
/// every kind that carries them. A kind with none — or a future `syn`
/// variant — returns an empty slice. That is still correct: there is no
/// `#[cfg(test)]` to find on it.
fn item_attrs(item: &syn::Item) -> &[syn::Attribute] {
    use syn::Item;
    match item {
        Item::Const(i) => &i.attrs,
        Item::Enum(i) => &i.attrs,
        Item::ExternCrate(i) => &i.attrs,
        Item::Fn(i) => &i.attrs,
        Item::ForeignMod(i) => &i.attrs,
        Item::Impl(i) => &i.attrs,
        Item::Macro(i) => &i.attrs,
        Item::Mod(i) => &i.attrs,
        Item::Static(i) => &i.attrs,
        Item::Struct(i) => &i.attrs,
        Item::Trait(i) => &i.attrs,
        Item::TraitAlias(i) => &i.attrs,
        Item::Type(i) => &i.attrs,
        Item::Union(i) => &i.attrs,
        Item::Use(i) => &i.attrs,
        _ => &[],
    }
}

/// One nesting level: the statements of `block` BEFORE index `before` are
/// what a value at this point can still see. An enclosing statement is
/// visible; a sibling branch is not.
#[derive(Clone, Copy)]
struct Frame<'ast> {
    block: &'ast syn::Block,
    before: usize,
}

/// A tracked method call (`.routes`, `.embedded_static`, or
/// `.embedded_locales`), with enough context to answer "is this
/// production" and "what did its value already flow through".
struct CallSite<'ast> {
    /// The whole method-call expression, so its receiver chain can be
    /// walked from here.
    call: &'ast syn::Expr,
    /// Where `.method(` starts — the anchor for a text splice.
    dot_span: proc_macro2::Span,
    is_cfg_test: bool,
    /// Every enclosing `fn`, innermost last. A nested `fn` inside `main`'s
    /// body is unlikely in generated code. Still, walking the whole stack
    /// answers the same question as before: is this call inside `main`'s
    /// body?
    enclosing_fns: Vec<*const syn::ItemFn>,
    /// The block nesting nearest this call, innermost last. This answers
    /// one question: is a call already in the SAME block, one branch at a
    /// time?
    frames: Vec<Frame<'ast>>,
}

/// One pass over `main.rs`'s AST.
///
/// It collects everything [`ensure_i18n_auto`] and [`ensure_embedded_locales`]
/// need: which `fn main`s are production, and where the interesting method
/// calls and `static` items sit.
#[derive(Default)]
struct Collector<'ast> {
    cfg_test_depth: u32,
    fn_stack: Vec<*const syn::ItemFn>,
    frames: Vec<Frame<'ast>>,

    main_fns: Vec<(&'ast syn::ItemFn, bool)>,
    routes_calls: Vec<CallSite<'ast>>,
    embedded_static_calls: Vec<CallSite<'ast>>,
    embedded_locales_calls: Vec<CallSite<'ast>>,
    statics: Vec<(&'ast syn::ItemStatic, bool)>,
    /// Whether each occurrence of the plain identifier `EMBEDDED_LOCALES`
    /// sits under `#[cfg(test)]` — a declaration, or a use site. This
    /// answers one question: does the name appear anywhere in production
    /// code?
    embedded_locales_idents: Vec<bool>,
}

impl<'ast> Collector<'ast> {
    /// Walk `file` and collect everything both entry points need.
    fn collect(file: &'ast syn::File) -> Self {
        let mut collector = Self::default();
        collector.visit_file(file);
        collector
    }
}

impl<'ast> syn::visit::Visit<'ast> for Collector<'ast> {
    fn visit_item(&mut self, item: &'ast syn::Item) {
        let is_test = has_cfg_test(item_attrs(item));
        if is_test {
            self.cfg_test_depth += 1;
        }
        syn::visit::visit_item(self, item);
        if is_test {
            self.cfg_test_depth -= 1;
        }
    }

    fn visit_item_fn(&mut self, item: &'ast syn::ItemFn) {
        if item.sig.ident == "main" {
            self.main_fns.push((item, self.cfg_test_depth > 0));
        }
        self.fn_stack.push(std::ptr::from_ref(item));
        syn::visit::visit_item_fn(self, item);
        self.fn_stack.pop();
    }

    fn visit_item_static(&mut self, item: &'ast syn::ItemStatic) {
        self.statics.push((item, self.cfg_test_depth > 0));
        syn::visit::visit_item_static(self, item);
    }

    fn visit_ident(&mut self, ident: &'ast syn::Ident) {
        if ident == "EMBEDDED_LOCALES" {
            self.embedded_locales_idents.push(self.cfg_test_depth > 0);
        }
    }

    fn visit_block(&mut self, block: &'ast syn::Block) {
        let base = self.frames.len();
        for (i, stmt) in block.stmts.iter().enumerate() {
            self.frames.push(Frame { block, before: i });
            self.visit_stmt(stmt);
            self.frames.pop();
        }
        self.frames.truncate(base);
    }

    fn visit_expr(&mut self, expr: &'ast syn::Expr) {
        if let syn::Expr::MethodCall(mc) = expr {
            // Compared as an `Ident`, not a `String` — every method call in
            // `main.rs` reaches this, and only three names need a match.
            let bucket = if mc.method == "routes" {
                Some(&mut self.routes_calls)
            } else if mc.method == "embedded_static" {
                Some(&mut self.embedded_static_calls)
            } else if mc.method == "embedded_locales" {
                Some(&mut self.embedded_locales_calls)
            } else {
                None
            };
            if let Some(bucket) = bucket {
                bucket.push(CallSite {
                    call: expr,
                    dot_span: mc.dot_token.span(),
                    is_cfg_test: self.cfg_test_depth > 0,
                    enclosing_fns: self.fn_stack.clone(),
                    frames: self.frames.clone(),
                });
            }
        }
        syn::visit::visit_expr(self, expr);
    }
}

/// The `.routes(` calls belonging to builders the BINARY runs, or empty
/// when that cannot be told apart from a helper's.
///
/// A builder inside `fn main`'s body is unambiguous — EVERY non-test `fn
/// main` counts, so `#[cfg(unix)] fn main()` beside `#[cfg(windows)] fn
/// main()` both get wired.
///
/// Otherwise `main` delegates, for example `fn main() { build_app().serve() }`.
/// The only safe case is when the file has exactly one non-test builder.
/// More than one builder cannot be told apart, and the choice cannot be
/// undone once wired. So the generator refuses instead of guessing.
fn production_anchors<'a, 'ast>(collector: &'a Collector<'ast>) -> Vec<&'a CallSite<'ast>> {
    let main_fns: Vec<*const syn::ItemFn> = collector
        .main_fns
        .iter()
        .filter(|(_, is_test)| !is_test)
        .map(|(item, _)| std::ptr::from_ref(*item))
        .collect();
    if !main_fns.is_empty() {
        let inside: Vec<&CallSite<'ast>> = collector
            .routes_calls
            .iter()
            .filter(|call| call.enclosing_fns.iter().any(|f| main_fns.contains(f)))
            .collect();
        if !inside.is_empty() {
            return inside;
        }
    }
    let candidates: Vec<&CallSite<'ast>> = collector
        .routes_calls
        .iter()
        .filter(|c| !c.is_cfg_test)
        .collect();
    match candidates.as_slice() {
        [only] => vec![*only],
        _ => Vec::new(),
    }
}

/// The innermost `fn` each of `anchors` sits in — the function bodies the
/// binary runs, used to scope "is this call production" for a call site
/// that has nothing to do with `.routes(` itself.
fn production_fn_ptrs(anchors: &[&CallSite<'_>]) -> Vec<*const syn::ItemFn> {
    let mut out: Vec<*const syn::ItemFn> = anchors
        .iter()
        .filter_map(|c| c.enclosing_fns.last().copied())
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

/// Whether `call` sits in one of `scopes` — or, when no production builder
/// could be identified at all, merely outside `#[cfg(test)]`. The fallback
/// is deliberate: with nothing to scope to, "anything non-test" is a
/// better read than "nothing counts".
fn in_production(call: &CallSite<'_>, scopes: &[*const syn::ItemFn]) -> bool {
    if scopes.is_empty() {
        !call.is_cfg_test
    } else {
        call.enclosing_fns.iter().any(|f| scopes.contains(f))
    }
}

/// The value a receiver expression starts from: a call in the SAME chain
/// (`.receiver`), a plain name to resolve through a binding, or a fresh
/// value (`App::new()`, a literal, …) with no binding behind it.
enum ChainOutcome<'ast> {
    Found,
    Root(&'ast syn::Ident),
    Dead,
}

/// Walk `expr`'s receiver chain, looking for a call to `method`.
///
/// Only look at this chain's own depth — never inside a nested call's
/// arguments, such as a closure passed to `.layer(...)`. This function
/// follows receiver links only.
fn chain_walk<'ast>(mut expr: &'ast syn::Expr, method: &str) -> ChainOutcome<'ast> {
    loop {
        match expr {
            syn::Expr::MethodCall(mc) => {
                if mc.method == method {
                    return ChainOutcome::Found;
                }
                expr = &mc.receiver;
            }
            syn::Expr::Path(p) => {
                return p
                    .path
                    .get_ident()
                    .map_or(ChainOutcome::Dead, ChainOutcome::Root);
            }
            _ => return ChainOutcome::Dead,
        }
    }
}

/// The trailing expression of `block` — what it evaluates to — or `None`
/// when the last statement ends in `;` and the block yields `()`.
fn block_tail(block: &syn::Block) -> Option<&syn::Expr> {
    match block.stmts.last()? {
        syn::Stmt::Expr(expr, None) => Some(expr),
        _ => None,
    }
}

/// The leaf expressions a value can actually come from: the branches of a
/// conditional or a bare block, expanded recursively. Which branch runs is
/// a choice made at runtime, so every one of them has to be checked.
fn branch_candidates(expr: &syn::Expr) -> Vec<&syn::Expr> {
    match expr {
        syn::Expr::If(e) => {
            let mut out = block_tail(&e.then_branch)
                .map(branch_candidates)
                .unwrap_or_default();
            if let Some((_, else_expr)) = &e.else_branch {
                out.extend(branch_candidates(else_expr));
            }
            out
        }
        syn::Expr::Match(e) => e
            .arms
            .iter()
            .flat_map(|arm| branch_candidates(&arm.body))
            .collect(),
        syn::Expr::Block(e) => block_tail(&e.block)
            .map(branch_candidates)
            .unwrap_or_default(),
        _ => vec![expr],
    }
}

/// The value a statement gives a name, in either form Rust spells it: a
/// `let`, or a plain reassignment.
///
/// Both forms carry a builder forward the same way. `let mut app =
/// build(); app = app.i18n(b);` rebinds `app`. A second `let app = …;`
/// does the same thing.
fn stmt_binds<'ast>(stmt: &'ast syn::Stmt, name: &str) -> Option<&'ast syn::Expr> {
    match stmt {
        syn::Stmt::Local(local) => {
            let pat = match &local.pat {
                syn::Pat::Ident(pat) => pat,
                // A type annotation may sit between the name and `=`
                // (`let app: App = …;`); the pattern is nested one level.
                syn::Pat::Type(pat_type) => match &*pat_type.pat {
                    syn::Pat::Ident(pat) => pat,
                    _ => return None,
                },
                _ => return None,
            };
            if pat.ident != name {
                return None;
            }
            local.init.as_ref().map(|init| &*init.expr)
        }
        syn::Stmt::Expr(syn::Expr::Assign(assign), _) => match &*assign.left {
            syn::Expr::Path(path) if path.path.get_ident().is_some_and(|id| id == name) => {
                Some(&*assign.right)
            }
            _ => None,
        },
        _ => None,
    }
}

/// Every reassignment of `name` reachable from a bare `if`/`match`/block
/// STATEMENT — one that is not itself a value, so a path through it that
/// skips the reassignment leaves `name` holding whatever it held before.
///
/// `if flag { app = app.i18n(bundle()); }` with no `else` is the case this
/// exists for: the assignment runs on ONE path only, so it is a candidate
/// alongside — never instead of — whatever `name` held going in. Missing
/// it would read a conditionally-installed bundle as never installed at
/// all, and clear it.
fn reachable_reassignments<'ast>(
    expr: &'ast syn::Expr,
    name: &str,
    out: &mut Vec<&'ast syn::Expr>,
) {
    match expr {
        syn::Expr::If(e) => {
            reachable_reassignments_in_block(&e.then_branch, name, out);
            if let Some((_, else_expr)) = &e.else_branch {
                reachable_reassignments(else_expr, name, out);
            }
        }
        syn::Expr::Block(e) => reachable_reassignments_in_block(&e.block, name, out),
        syn::Expr::Match(e) => {
            for arm in &e.arms {
                reachable_reassignments(&arm.body, name, out);
            }
        }
        _ => {}
    }
}

/// [`reachable_reassignments`]'s scan over one block's own statements.
fn reachable_reassignments_in_block<'ast>(
    block: &'ast syn::Block,
    name: &str,
    out: &mut Vec<&'ast syn::Expr>,
) {
    for stmt in &block.stmts {
        if let Some(rhs) = stmt_binds(stmt, name) {
            out.push(rhs);
        }
        if let syn::Stmt::Expr(expr, _) = stmt {
            reachable_reassignments(expr, name, out);
        }
    }
}

/// Every place `name` could be bound reaching `frames`, searching this
/// nesting level and then outward.
///
/// Each comes with the frame stack a caller must use to resolve THAT
/// binding's own free names — narrowed to the statements before it.
///
/// A plain `let`/reassignment fully replaces `name`, so it is the only
/// candidate returned once found: nothing earlier can still be reached
/// through this name. A bare conditional STATEMENT reassigning `name` does
/// not — the path that skips it leaves `name` unchanged — so its
/// reassignment is returned ALONGSIDE the search continuing past it,
/// exactly like a plain binding would once it is found.
fn resolve_bindings<'ast>(
    frames: &[Frame<'ast>],
    name: &str,
) -> Vec<(&'ast syn::Expr, Vec<Frame<'ast>>)> {
    let mut out = Vec::new();
    for depth in (0..frames.len()).rev() {
        let frame = frames[depth];
        for (i, stmt) in frame.block.stmts[..frame.before].iter().enumerate().rev() {
            let mut narrowed = frames[..=depth].to_vec();
            narrowed[depth] = Frame {
                block: frame.block,
                before: i,
            };
            if let Some(rhs) = stmt_binds(stmt, name) {
                out.push((rhs, narrowed));
                return out;
            }
            if let syn::Stmt::Expr(expr, _) = stmt {
                let mut conditional = Vec::new();
                reachable_reassignments(expr, name, &mut conditional);
                out.extend(conditional.into_iter().map(|rhs| (rhs, narrowed.clone())));
            }
        }
    }
    out
}

/// Whether the value reaching `expr` has already flowed through `method`.
///
/// It may flow through the call's own chain, or through earlier rebindings
/// and conditional branches that lead back to where the chain started.
///
/// A bundle on ANY reachable branch counts. Which branch runs is a runtime
/// choice. Inserting `.i18n_auto()` based on a branch that might not run
/// could clear a bundle the flag would still select.
///
/// `depth` bounds the walk against a pathological, deeply-rebound input;
/// valid Rust cannot cycle through its own bindings.
fn value_already_called<'ast>(
    expr: &'ast syn::Expr,
    frames: &[Frame<'ast>],
    method: &str,
    depth: u32,
) -> bool {
    if depth > 256 {
        return false;
    }
    branch_candidates(expr)
        .into_iter()
        .any(|candidate| match chain_walk(candidate, method) {
            ChainOutcome::Found => true,
            ChainOutcome::Dead => false,
            ChainOutcome::Root(name) => resolve_bindings(frames, &name.to_string())
                .into_iter()
                .any(|(rhs, next)| value_already_called(rhs, &next, method, depth + 1)),
        })
}

/// Whether the app value reaching `call` has already been passed through
/// `method` (`"i18n"` or `"i18n_auto"`).
fn method_called_before(call: &CallSite<'_>, method: &str) -> bool {
    value_already_called(call.call, &call.frames, method, 0)
}

/// The outcome of trying to wire `.i18n_auto()` into `main.rs`.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum I18nAutoWiring {
    /// The builder chain now calls `.i18n_auto()` (or already did).
    Wired(String),
    /// The app installs its own `Bundle` with `.i18n(...)` — from embedded
    /// files, a translation-management service, memory.
    ///
    /// That bundle takes precedence over any filesystem load. So the keys
    /// this generator wrote to disk never reach it. Every generated label
    /// then renders as a placeholder, even though generation and `t!`'s
    /// compile-time check both succeeded. `main.rs` is left alone —
    /// swapping someone's bundle for a filesystem load would be worse —
    /// and the caller warns.
    CustomBundle,
    /// No real `.routes(` call was found, so there is nowhere safe to
    /// insert.
    ///
    /// This also covers a `main.rs` that fails to parse as Rust — a
    /// stricter check than this generator needs, but it is treated the
    /// same way. Leave the file alone, and let the caller warn instead of
    /// guessing at code it cannot fully read.
    NoAnchor,
}

/// The leading whitespace of the line containing byte offset `at`.
fn line_indent(src: &str, at: usize) -> &str {
    let line_start = src[..at].rfind('\n').map_or(0, |i| i + 1);
    let line = &src[line_start..];
    let indent_len = line.len() - line.trim_start().len();
    &line[..indent_len]
}

/// Insert `.i18n_auto()` into the `AppBuilder` chain in `main.rs` so the
/// generated `t!` lookups actually resolve (AC4's "zero further config").
///
/// Inserted immediately before the first REAL `.routes(` call — the same
/// anchor `autumn new --with-i18n` uses.
///
/// A `main.rs` that already installs a bundle — through `.i18n_auto()` or
/// an explicit `.i18n(...)` — is left untouched. An app that builds its
/// own `Bundle`, from embedded files or a translation-management service,
/// keeps that bundle. The generator must not swap it for a filesystem
/// load.
pub(super) fn ensure_i18n_auto(main_rs: &str) -> I18nAutoWiring {
    let Ok(file) = syn::parse_file(main_rs) else {
        return I18nAutoWiring::NoAnchor;
    };
    let collector = Collector::collect(&file);

    // WHICH builders are production is decided first, and everything else
    // is asked about those builders rather than about the file. A
    // `main.rs` can hold several `main` functions — a preview helper, a
    // `#[cfg(test)]` fixture. File-wide questions gave wrong answers on
    // ordinary layouts. A `.i18n(test_bundle())` in a fixture reported the
    // whole app as custom-bundled and left production unwired. An
    // `.i18n_auto()` on the fixture reported the app as already wired.
    let anchors = production_anchors(&collector);
    if anchors.is_empty() {
        return I18nAutoWiring::NoAnchor;
    }

    // EVERY production branch, not just the first, and each judged ON ITS OWN.
    // `main` may build the app conditionally — one `.routes(` per configuration
    // branch — and one branch carrying `.i18n_auto()` says nothing about its
    // sibling.
    //
    // A chain with its own bundle is LEFT ALONE rather than blocking the rest.
    // `.i18n_auto()` clears a preloaded bundle and switches to filesystem
    // loading. Wiring it into that chain would replace the app's embedded or
    // translation-management-service bundle, and it can panic when nothing is
    // on disk. That is a reason to skip that one chain, not to leave its
    // siblings with raw keys.
    let mut custom = false;
    let mut pending = Vec::new();
    for anchor in anchors {
        if method_called_before(anchor, "i18n") {
            custom = true;
        } else if !method_called_before(anchor, "i18n_auto") {
            pending.push(anchor);
        }
    }
    if pending.is_empty() {
        return if custom {
            I18nAutoWiring::CustomBundle
        } else {
            I18nAutoWiring::Wired(main_rs.to_owned())
        };
    }

    let index = SourceIndex::new(main_rs);
    let mut sites: Vec<usize> = pending
        .iter()
        .map(|anchor| index.byte_offset(anchor.dot_span.start()))
        .collect();
    sites.sort_unstable();

    // Applied back-to-front so each insertion leaves the earlier offsets valid.
    let mut out = main_rs.to_owned();
    for at in sites.into_iter().rev() {
        let line_start = out[..at].rfind('\n').map_or(0, |i| i + 1);
        let indent = line_indent(&out, at);
        if line_start + indent.len() == at {
            // `.routes(` is the first token on its line: reuse the line's own
            // indentation so the inserted call sits in the builder chain
            // rather than at some arbitrary column.
            let indent = indent.to_owned();
            out = format!(
                "{}{indent}.i18n_auto()\n{}",
                &out[..line_start],
                &out[line_start..]
            );
        } else {
            // A single-line builder chain — inserted inline, still valid Rust.
            out = format!("{}.i18n_auto(){}", &out[..at], &out[at..]);
        }
    }
    I18nAutoWiring::Wired(out)
}

/// Whether `expr` is `autumn_web::embed_locales!(...)`, the macro this
/// generator wires up — as opposed to a hand-rolled or otherwise-built
/// `EMBEDDED_LOCALES`, which is left alone.
fn is_embed_locales_macro(expr: &syn::Expr) -> bool {
    let syn::Expr::Macro(mac) = expr else {
        return false;
    };
    let segments: Vec<&syn::Ident> = mac.mac.path.segments.iter().map(|s| &s.ident).collect();
    matches!(segments.as_slice(), [a, b] if *a == "autumn_web" && *b == "embed_locales")
}

/// Embed the locale bundle into the binary for `autumn build --embed`,
/// matching what `autumn new --with-i18n` wires into a fresh app.
///
/// `.i18n_auto()` alone loads from DISK.
///
/// An `--embed` build is supposed to be self-contained. Without this call,
/// the binary still reads the locale directory at startup. Run it from an
/// empty deployment directory, or from the release image (whose
/// embedded-build path ships no sidecar on purpose), and it panics on a
/// missing default bundle — after a build that looked entirely clean.
///
/// Both edits sit behind the `embed-assets` feature that already gates the
/// template's static assets. They are anchored beside the PRODUCTION
/// `EMBEDDED_STATIC` declaration and its `.embedded_static(&EMBEDDED_STATIC)`
/// install. This returns `None` when neither is present — an `--api` app, a
/// hand-rolled `main.rs`, or a file that fails to parse — so the caller can
/// warn instead of guessing. It returns the input unchanged when the locales
/// are already embedded.
pub(super) fn ensure_embedded_locales(main_rs: &str, dir: &str) -> Option<String> {
    // `embed_locales!()` defaults to `i18n/`; a configured directory is passed
    // through as the macro's literal argument — escaped, because this is the one
    // place a `dir` read out of `autumn.toml` becomes Rust source.
    let macro_call = if dir == "i18n" {
        "autumn_web::embed_locales!()".to_owned()
    } else {
        format!(
            "autumn_web::embed_locales!(\"{}\")",
            rust_string_escape(dir)
        )
    };

    let file = syn::parse_file(main_rs).ok()?;
    let collector = Collector::collect(&file);
    let index = SourceIndex::new(main_rs);

    // PRODUCTION occurrences only. A `#[cfg(test)]` fixture that happens to
    // mention `EMBEDDED_LOCALES` is not the binary's embedding, and treating it
    // as one returns "already wired" while `autumn build --embed` ships a
    // release binary with no bundle in it.
    let embedded_in_production = collector
        .embedded_locales_idents
        .iter()
        .any(|is_test| !is_test);

    if embedded_in_production {
        // Already embedded — but not necessarily from the right place. A
        // project that changed `[i18n] dir` after its first `--i18n` scaffold
        // keeps embedding the OLD directory, so this repoints the PRODUCTION
        // static's own macro call — never a differently-named neighbour, such
        // as an `ADMIN_EMBEDDED_LOCALES` beside it — and only when that
        // initialiser is this macro at all; a hand-rolled or macro-generated
        // static is left alone, and only the install below is checked.
        let production_decl = collector
            .statics
            .iter()
            .find(|(item, is_test)| !is_test && item.ident == "EMBEDDED_LOCALES");
        let out = match production_decl {
            Some((item, _)) if is_embed_locales_macro(&item.expr) => {
                let range = index.range(item.expr.span());
                format!(
                    "{}{macro_call}{}",
                    &main_rs[..range.start],
                    &main_rs[range.end..]
                )
            }
            _ => main_rs.to_owned(),
        };
        // Unconditionally: the insertion is per-anchor and skips the ones
        // already served, so "some branch has it" can no longer stand in for
        // "every branch has it".
        return insert_locale_install(&out);
    }

    // Beside the PRODUCTION static, on the same production test the install
    // below uses. A `#[cfg(test)]` module can declare its own fixture with the
    // very same declaration, and treating the FIRST occurrence in the file as
    // "the" static would declare `EMBEDDED_LOCALES` inside that module while
    // the install went — correctly — into the production builder.
    let (production_static, _) = collector
        .statics
        .iter()
        .find(|(item, is_test)| !is_test && item.ident == "EMBEDDED_STATIC")?;
    let at = index.range(production_static.span()).end;
    let with_static = format!(
        "{}\n#[cfg(feature = \"embed-assets\")]\nstatic EMBEDDED_LOCALES: autumn_web::include_dir::Dir = {macro_call};{}",
        &main_rs[..at],
        &main_rs[at..]
    );
    insert_locale_install(&with_static)
}

/// Whether `anchor`'s block already carries an `.embedded_locales(` call —
/// per BLOCK, because that is what a conditional branch is: one branch
/// already carrying the call says nothing about its sibling.
fn locales_installed_beside(
    anchor: &CallSite<'_>,
    embedded_locales_calls: &[CallSite<'_>],
) -> bool {
    let Some(&block) = anchor.frames.last().map(|f| &f.block) else {
        return false;
    };
    embedded_locales_calls.iter().any(|c| {
        c.frames
            .last()
            .is_some_and(|f| std::ptr::eq(f.block, block))
    })
}

/// Byte offset right after the statement whose method call ends at `end` —
/// its terminating `;`, plus the following newline when there is one. The
/// calls this anchors on (`app.embedded_static(&EMBEDDED_STATIC)`) are
/// always a bare statement of their own, so the next `;` is that
/// statement's.
fn statement_end(src: &str, end: usize) -> usize {
    let mut at = src[end..].find(';').map_or(src.len(), |i| end + i + 1);
    if src[at..].starts_with('\n') {
        at += 1;
    }
    at
}

/// Splice `.embedded_locales(&EMBEDDED_LOCALES)` in after every PRODUCTION
/// `embedded_static` install that does not already have one beside it, or
/// `None` when there is no such install at all (and none of the locales
/// calls the file already carries are production either).
///
/// EVERY production anchor, each judged on its own — the same per-branch
/// shape [`ensure_i18n_auto`] uses, and for the same reason. A `main` that
/// builds the app conditionally has one `embedded_static` install per
/// branch, every one of them production; serving only the first leaves the
/// others loading locales from disk, so an `--embed` deployment panics
/// whenever it takes one of those branches, with the bundle sitting unused
/// in the binary.
fn insert_locale_install(src: &str) -> Option<String> {
    let file = syn::parse_file(src).ok()?;
    let collector = Collector::collect(&file);
    let index = SourceIndex::new(src);

    let routes_anchors = production_anchors(&collector);
    let scopes = production_fn_ptrs(&routes_anchors);

    let anchors: Vec<&CallSite<'_>> = collector
        .embedded_static_calls
        .iter()
        .filter(|c| in_production(c, &scopes))
        .collect();
    let pending: Vec<&CallSite<'_>> = anchors
        .iter()
        .filter(|c| !locales_installed_beside(c, &collector.embedded_locales_calls))
        .copied()
        .collect();

    if pending.is_empty() {
        // Nothing to add — but say whether that is because everything is
        // served or because there was nowhere to write. A file with no
        // production anchor at all is only "done" when the call is already
        // there; otherwise the caller has to warn.
        let served = !anchors.is_empty()
            || collector
                .embedded_locales_calls
                .iter()
                .any(|c| in_production(c, &scopes));
        return served.then(|| src.to_owned());
    }

    let mut sites: Vec<usize> = pending
        .iter()
        .map(|c| index.range(c.call.span()).end)
        .collect();
    sites.sort_unstable();

    // Back-to-front, so each insertion leaves the earlier offsets valid.
    let mut out = src.to_owned();
    for call_end in sites.into_iter().rev() {
        let indent = line_indent(&out, call_end).to_owned();
        let at = statement_end(&out, call_end);
        out = format!(
            "{}{indent}#[cfg(feature = \"embed-assets\")]\n{indent}let app = app.embedded_locales(&EMBEDDED_LOCALES);\n{}",
            &out[..at],
            &out[at..]
        );
    }
    Some(out)
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;

    /// [`merge_en_ftl_keeping`] with nothing held back — the shape most of
    /// these tests want, where no surviving source is in play.
    fn merge_en_ftl(
        existing: &str,
        pascal_name: &str,
        resource: &str,
        keys: &BTreeMap<String, String>,
    ) -> String {
        merge_en_ftl_keeping(existing, pascal_name, resource, keys, &HashSet::new())
    }

    fn chrome(keys: &[&str]) -> HashSet<String> {
        keys.iter().map(|k| (*k).to_owned()).collect()
    }

    fn keys(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
            .collect()
    }

    #[test]
    fn disabled_emitter_is_an_identity_over_the_plain_expression() {
        let labels = ViewLabels::disabled();
        assert_eq!(labels.lit("common.create", "Create"), "\"Create\"");
        assert_eq!(
            labels.lit_ref("post.index.title", "Post index"),
            "\"Post index\""
        );
        assert_eq!(
            labels.expr(
                "post.show.title",
                "Post #{ $id }",
                "&format!(\"Post #{}\", id)",
                &[]
            ),
            "&format!(\"Post #{}\", id)"
        );
        assert!(labels.used_keys().is_empty());
    }

    #[test]
    fn enabled_emitter_records_keys_and_emits_lookups() {
        let labels = ViewLabels::new(true);
        assert_eq!(
            labels.lit("common.create", "Create"),
            "t!(locale, \"common.create\")"
        );
        assert_eq!(
            labels.lit_ref("post.index.title", "Post index"),
            "&t!(locale, \"post.index.title\")"
        );
        assert_eq!(
            labels.expr(
                "common.new",
                "New { $resource }",
                "\"New Post\"",
                &[("resource", "&l_resource")]
            ),
            "t!(locale, \"common.new\", resource = &l_resource)"
        );
        let used = labels.used_keys();
        assert_eq!(used.get("common.create").unwrap(), "Create");
        assert_eq!(used.get("common.new").unwrap(), "New { $resource }");
    }

    #[test]
    fn merge_writes_a_header_and_both_blocks_into_an_empty_file() {
        let out = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("common.create", "Create"), ("post.name", "Post")]),
        );
        assert!(out.contains(COMMON_HEADER), "{out}");
        assert!(out.contains("common.create = Create"), "{out}");
        assert!(out.contains("post.name = Post"), "{out}");
        assert!(out.contains("Post — generated by"), "{out}");
    }

    #[test]
    fn merge_never_rewrites_an_existing_value() {
        let existing = "common.create = Add\n";
        let out = merge_en_ftl(
            existing,
            "Post",
            "post",
            &keys(&[("common.create", "Create"), ("post.name", "Post")]),
        );
        assert!(out.contains("common.create = Add"), "{out}");
        assert!(!out.contains("common.create = Create"), "{out}");
        assert!(out.contains("post.name = Post"), "{out}");
    }

    #[test]
    fn merge_is_idempotent() {
        let pairs = keys(&[("common.create", "Create"), ("post.name", "Post")]);
        let once = merge_en_ftl("", "Post", "post", &pairs);
        let twice = merge_en_ftl(&once, "Post", "post", &pairs);
        assert_eq!(once, twice);
    }

    #[test]
    fn merge_shares_the_common_block_across_resources() {
        let first = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("common.create", "Create"), ("post.name", "Post")]),
        );
        let second = merge_en_ftl(
            &first,
            "Comment",
            "comment",
            &keys(&[("common.create", "Create"), ("comment.name", "Comment")]),
        );
        assert_eq!(second.matches("common.create =").count(), 1, "{second}");
        assert_eq!(second.matches(COMMON_HEADER).count(), 1, "{second}");
        assert!(second.contains("comment.name = Comment"), "{second}");
        assert!(second.contains("post.name = Post"), "{second}");
    }

    #[test]
    fn remove_takes_only_the_resource_block() {
        // A sibling resource keeps the shared chrome in use, so only `Post`'s
        // own block comes out. (Destroying the LAST resource takes the chrome
        // too — see `removing_the_last_resource_takes_the_now_unreferenced_chrome_with_it`.)
        let ftl = merge_en_ftl(
            &merge_en_ftl(
                "",
                "Post",
                "post",
                &keys(&[("common.create", "Create"), ("post.name", "Post")]),
            ),
            "Comment",
            "comment",
            &keys(&[("common.create", "Create"), ("comment.name", "Comment")]),
        );
        // `true`: the surviving `Comment` routes still look chrome keys up.
        let out = remove_en_ftl_keys(&ftl, "Post", "post", &chrome(&["common.create"]));
        assert!(out.contains("common.create = Create"), "{out}");
        assert!(!out.contains("post.name"), "{out}");
        assert!(!out.contains("Post — generated by"), "{out}");
        assert!(out.contains("comment.name = Comment"), "{out}");
        // Idempotent: destroying twice is a no-op.
        assert_eq!(
            remove_en_ftl_keys(&out, "Post", "post", &chrome(&["common.create"])),
            out
        );
    }

    /// #2439: no source names the framework key, so the scan never reports it.
    /// A sibling that still uses the chrome keeps it too.
    #[test]
    fn remove_keeps_the_framework_key_while_a_sibling_survives() {
        let nul = (
            "common.error.nul_character",
            "Cannot contain the NUL character (0x00)",
        );
        let ftl = merge_en_ftl(
            &merge_en_ftl(
                "",
                "Post",
                "post",
                &keys(&[("common.create", "Create"), nul, ("post.name", "Post")]),
            ),
            "Comment",
            "comment",
            &keys(&[
                ("common.create", "Create"),
                nul,
                ("comment.name", "Comment"),
            ]),
        );
        let out = remove_en_ftl_keys(&ftl, "Post", "post", &chrome(&["common.create"]));
        assert!(out.contains("common.error.nul_character = "), "{out}");
        assert!(out.contains("comment.name = Comment"), "{out}");
    }

    /// The last scaffold takes the shared block, framework key included.
    #[test]
    fn removing_the_last_resource_takes_the_framework_key_too() {
        let nul = (
            "common.error.nul_character",
            "Cannot contain the NUL character (0x00)",
        );
        let ftl = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("common.create", "Create"), nul, ("post.name", "Post")]),
        );
        let out = remove_en_ftl_keys(&ftl, "Post", "post", &HashSet::new());
        assert!(!out.contains("common.error.nul_character"), "{out}");
    }

    #[test]
    fn remove_leaves_a_sibling_resource_intact() {
        let ftl = merge_en_ftl(
            &merge_en_ftl("", "Post", "post", &keys(&[("post.name", "Post")])),
            "Comment",
            "comment",
            &keys(&[("comment.name", "Comment")]),
        );
        let out = remove_en_ftl_keys(&ftl, "Post", "post", &HashSet::new());
        assert!(out.contains("comment.name = Comment"), "{out}");
        assert!(!out.contains("post.name"), "{out}");
    }

    #[test]
    fn config_block_is_added_once() {
        let once = ensure_i18n_config_block("[server]\nport = 3000\n");
        assert!(once.contains("[i18n]"), "{once}");
        assert!(once.contains("default_locale = \"en\""), "{once}");
        assert_eq!(ensure_i18n_config_block(&once), once);
    }

    #[test]
    fn config_block_respects_an_existing_i18n_section() {
        let existing = "[i18n]\ndefault_locale = \"fr\"\n";
        assert_eq!(ensure_i18n_config_block(existing), existing);
    }

    #[test]
    fn i18n_auto_is_inserted_before_the_routes_call() {
        let main_rs = "fn main() {\n    autumn_web::app()\n        .routes(routes![index])\n        .run();\n}\n";
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected an anchor");
        };
        assert!(
            out.contains("        .i18n_auto()\n        .routes(routes![index])"),
            "{out}"
        );
        assert_eq!(
            ensure_i18n_auto(&out),
            I18nAutoWiring::Wired(out.clone()),
            "must be idempotent"
        );
    }

    /// An app that builds its own `Bundle` keeps it — but the caller has to be
    /// told, because the keys written to disk will never reach it.
    #[test]
    fn i18n_auto_reports_a_hand_installed_bundle_rather_than_claiming_success() {
        let main_rs = "fn main() {\n    autumn_web::app()\n        .i18n(my_bundle())\n        .routes(routes![index]);\n}\n";
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// `autumn new`'s own template mentions `.routes(routes![...])` in a comment
    /// above `fn main`. Anchoring there would write `.i18n_auto()` INTO that
    /// comment: the app compiles, starts, and renders raw keys forever, and the
    /// idempotency guard makes every later run a no-op.
    #[test]
    fn i18n_auto_ignores_a_routes_call_inside_a_comment() {
        let main_rs = concat!(
            "// Register new endpoints by adding them to the .routes(routes![...]) list.\n",
            "fn main() {\n",
            "    autumn_web::app()\n",
            "        .routes(routes![index])\n",
            "        .run();\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected the real anchor to be found");
        };
        assert!(
            out.contains("        .i18n_auto()\n        .routes(routes![index])"),
            "must anchor on the real builder call:\n{out}"
        );
        assert!(
            out.lines().next().unwrap().ends_with("list."),
            "the comment must be left alone:\n{out}"
        );
    }

    /// A `.i18n_auto()` that appears only in a doc comment must not be mistaken
    /// for a bundle the app already installs.
    #[test]
    fn i18n_auto_ignores_a_mention_inside_a_doc_comment() {
        let main_rs = concat!(
            "/// Call `.i18n_auto()` to load translations.\n",
            "fn main() {\n",
            "    autumn_web::app()\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected an anchor");
        };
        assert!(
            out.contains("        .i18n_auto()\n        .routes(routes![index])"),
            "{out}"
        );
    }

    /// A `main.rs` can hold more than one builder. Wiring the wrong one is
    /// silent — the production app gets no bundle and renders raw keys, and the
    /// idempotency guard stops any later run from correcting it.
    #[test]
    fn i18n_auto_targets_the_builder_the_binary_runs() {
        let main_rs = concat!(
            "fn preview_app() -> App {\n",
            "    autumn_web::app()\n",
            "        .routes(routes![preview])\n",
            "}\n",
            "\n",
            "#[autumn_web::main]\n",
            "async fn main() {\n",
            "    autumn_web::app()\n",
            "        .routes(routes![index])\n",
            "        .run()\n",
            "        .await;\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected an anchor");
        };
        assert!(
            out.contains(".i18n_auto()\n        .routes(routes![index])"),
            "must wire the builder `main` runs:\n{out}"
        );
        assert!(
            !out.contains(".i18n_auto()\n        .routes(routes![preview])"),
            "must not wire the preview builder:\n{out}"
        );
    }

    /// The common `fn main` -> `build_app()` shape has its builder BEFORE
    /// `fn main`; with only one candidate there is nothing to disambiguate.
    #[test]
    fn i18n_auto_falls_back_to_the_only_builder_when_it_precedes_main() {
        let main_rs = concat!(
            "fn build_app() -> App {\n",
            "    autumn_web::app()\n",
            "        .routes(routes![index])\n",
            "}\n",
            "\n",
            "#[autumn_web::main]\n",
            "async fn main() {\n",
            "    build_app().run().await;\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected an anchor");
        };
        assert!(out.contains(".i18n_auto()"), "{out}");
    }

    #[test]
    fn locales_are_embedded_for_embed_builds() {
        // `.i18n_auto()` loads from DISK; an `--embed` build is meant to be
        // self-contained, and the release image ships no sidecar for it.
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert!(out.contains("static EMBEDDED_LOCALES"), "{out}");
        assert!(out.contains("autumn_web::embed_locales!()"), "{out}");
        assert!(
            out.contains("app.embedded_locales(&EMBEDDED_LOCALES)"),
            "{out}"
        );
        assert_eq!(
            out.matches("#[cfg(feature = \"embed-assets\")]").count(),
            2,
            "both edits stay behind the feature the template already gates on:\n{out}"
        );
        // Idempotent, and a configured directory reaches the macro.
        assert_eq!(
            ensure_embedded_locales(&out, "i18n").as_deref(),
            Some(out.as_str())
        );
        let custom = ensure_embedded_locales(main_rs, "translations").unwrap();
        assert!(
            custom.contains("embed_locales!(\"translations\")"),
            "{custom}"
        );
        // An `--api` or hand-rolled `main.rs` has no anchors: reported, not guessed at.
        assert_eq!(ensure_embedded_locales("fn main() {}\n", "i18n"), None);
    }

    #[test]
    fn i18n_auto_reports_no_anchor_rather_than_guessing() {
        let main_rs = "fn main() {\n    println!(\"no builder here\");\n}\n";
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::NoAnchor);
    }

    /// A `main.rs` this crate cannot parse as Rust at all — a hand edit left
    /// broken, a syntax this `syn` version does not cover — must not be
    /// guessed at. Leaving it alone and reporting no anchor is what a caller
    /// already does for an ambiguous file; it is strictly better than a
    /// hand-rolled scanner that reads broken code as something it is not.
    #[test]
    fn a_file_that_fails_to_parse_is_left_alone() {
        let broken = "fn main( {\n    app.routes(routes![index]);\n";
        assert_eq!(ensure_i18n_auto(broken), I18nAutoWiring::NoAnchor);
        assert_eq!(ensure_embedded_locales(broken, "i18n"), None);
    }

    #[test]
    fn config_block_detects_a_spaced_section_header() {
        // `[ i18n ]` is legal TOML; appending a second `[i18n]` beside it makes
        // the whole file unparseable and takes the app's config down with it.
        let existing = "[ i18n ]\ndefault_locale = \"fr\"\n";
        assert_eq!(ensure_i18n_config_block(existing), existing);
    }

    #[test]
    fn the_configured_locale_and_directory_are_read_from_the_config() {
        let (locale, dir) = configured_i18n("[i18n]\ndefault_locale = \"fr\"\n");
        assert_eq!(locale.as_deref(), Some("fr"));
        assert_eq!(dir, None);
        // Spacing and trailing comments are both legal TOML.
        let (locale, dir) = configured_i18n(
            "[ i18n ] # locale settings\ndefault_locale = 'pt-BR' # ours\ndir = \"translations\"\n",
        );
        assert_eq!(locale.as_deref(), Some("pt-BR"));
        assert_eq!(dir.as_deref(), Some("translations"));
        // `#` is an ordinary character inside a quoted value.
        let (_, dir) = configured_i18n("[i18n]\ndir = \"i18n#v2\"\n");
        assert_eq!(dir.as_deref(), Some("i18n#v2"));
        // Keys under some OTHER section are not ours.
        assert_eq!(
            configured_i18n("[server]\ndefault_locale = \"fr\"\ndir = \"x\"\n"),
            (None, None)
        );
        assert_eq!(configured_i18n("[server]\nport = 3000\n"), (None, None));
    }

    #[test]
    fn profile_overlays_that_repoint_i18n_are_reported() {
        let toml = concat!(
            "[i18n]\ndefault_locale = \"en\"\n\n",
            // Same paths as the base — nothing to say about this one.
            "[profile.staging.i18n]\ndefault_locale = \"en\"\n\n",
            "[profile.prod.i18n]\ndir = \"translations\"\ndefault_locale = \"fr\"\n",
        );
        let out = profile_i18n_overrides(toml, "i18n", "en");
        assert_eq!(
            out,
            vec![("prod".to_owned(), "translations/fr.ftl".to_owned())]
        );
        // An overlay of something else entirely is not an i18n overlay.
        assert!(
            profile_i18n_overrides("[profile.prod.server]\nport = 80\n", "i18n", "en").is_empty()
        );
    }

    #[test]
    fn config_block_detects_the_inline_and_dotted_spellings() {
        // TOML expresses one table three ways, and appending `[i18n]` beside any
        // of them is a duplicate definition that makes the file unparseable —
        // taking the whole application config down with it.
        for existing in [
            "i18n = { default_locale = \"fr\", supported_locales = [\"fr\"] }\n",
            "i18n.default_locale = \"fr\"\n",
            "[i18n]\ndefault_locale = \"fr\"\n",
        ] {
            assert_eq!(
                ensure_i18n_config_block(existing),
                existing,
                "must not append a second definition to: {existing}"
            );
        }
        // A dotted key under some OTHER table is a different key entirely.
        let scoped = "[server]\ni18n.enabled = true\n";
        assert!(ensure_i18n_config_block(scoped).contains("[i18n]"));
    }

    #[test]
    fn the_configured_values_are_read_from_the_inline_and_dotted_spellings() {
        let (locale, dir) =
            configured_i18n("i18n = { default_locale = \"fr\", dir = \"translations\" }\n");
        assert_eq!(locale.as_deref(), Some("fr"));
        assert_eq!(dir.as_deref(), Some("translations"));
        let (locale, dir) = configured_i18n("i18n.default_locale = \"pt-BR\"\ni18n.dir = 'tr'\n");
        assert_eq!(locale.as_deref(), Some("pt-BR"));
        assert_eq!(dir.as_deref(), Some("tr"));
    }

    #[test]
    fn config_block_detects_a_header_with_a_trailing_comment() {
        // `[i18n] # locale settings` is one table, not none — appending a second
        // `[i18n]` beside it makes the file unparseable and takes the whole
        // application config down with it.
        let existing = "[i18n] # locale settings\ndefault_locale = \"fr\"\n";
        assert_eq!(ensure_i18n_config_block(existing), existing);
    }

    #[test]
    fn removal_leaves_hand_authored_keys_on_the_same_prefix_alone() {
        // A `post.email.subject` the application owns is not this generator's
        // to delete just because it starts with the resource's name.
        let generated = merge_en_ftl("", "Post", "post", &keys(&[("post.new", "New Post")]));
        let with_hand_authored = format!("{generated}\n# App copy\npost.email.subject = Welcome\n");
        let out = remove_en_ftl_keys(&with_hand_authored, "Post", "post", &HashSet::new());
        assert!(
            out.contains("post.email.subject = Welcome"),
            "a hand-authored key must survive destroy:\n{out}"
        );
        assert!(!out.contains("post.new"), "{out}");
    }

    /// A key defined ABOVE the generated block must not be redefined inside it.
    ///
    /// `parse_ftl` (`autumn/src/i18n.rs`) inserts each entry into a map in file
    /// order, so the last definition wins outright — a second, generated
    /// definition below a hand-authored one does not merely duplicate it, it
    /// silently replaces the translation with English. Reconciliation reads
    /// only the block, so before this it saw the key as absent and appended it.
    #[test]
    fn regeneration_does_not_redefine_a_key_authored_above_the_block() {
        // Establish a block, then hand-author one of the NEXT run's keys above
        // it — the shape you get when someone translates a string before the
        // generator ever emits it, or hoists it out of the block by hand.
        let generated = merge_en_ftl("", "Post", "post", &keys(&[("post.new", "New Post")]));
        let with_hand_authored = format!("post.field.body = Corps du texte\n\n{generated}");

        let out = merge_en_ftl(
            &with_hand_authored,
            "Post",
            "post",
            &keys(&[("post.new", "New Post"), ("post.field.body", "Body")]),
        );

        assert_eq!(
            out.matches("post.field.body =").count(),
            1,
            "the key must be defined exactly once — a second, later definition \
             wins in `parse_ftl` and would replace the translation:\n{out}"
        );
        assert!(
            out.contains("post.field.body = Corps du texte"),
            "the hand-authored value must survive:\n{out}"
        );
        assert!(
            !out.contains("post.field.body = Body"),
            "the generated English must not be written at all:\n{out}"
        );
    }

    /// `parse_ftl` does not flush the current key on a comment line, so an
    /// indented line after a translator's mid-value note is still part of that
    /// value at runtime. Reconciliation has to agree, or regeneration silently
    /// truncates a translation it was told to keep.
    #[test]
    fn a_comment_inside_a_value_does_not_truncate_it_on_regeneration() {
        // Built from a real generated block so the markers `block_end` looks
        // for are exactly the ones the generator writes.
        let wanted = keys(&[("post.help", "First"), ("post.new", "New Post")]);
        let generated = merge_en_ftl("", "Post", "post", &wanted);
        let with_note = generated.replace(
            "post.help = First\n",
            "post.help = First\n# translator note\n    second\n",
        );
        assert!(with_note.contains("second"), "fixture: {with_note}");

        let out = merge_en_ftl(&with_note, "Post", "post", &wanted);
        assert!(
            out.contains("second"),
            "the continuation belongs to `post.help` and must survive:\n{out}"
        );
        assert!(out.contains("# translator note"), "{out}");
    }

    /// A comment carrying an `=` is still a comment, not a key line — read as
    /// one it is absent from `wanted` and gets deleted.
    #[test]
    fn a_comment_containing_an_equals_sign_is_not_pruned_as_a_key() {
        let note = "# careful: post.legacy = Old Post is served elsewhere";
        // Two keys so the block reconciles rather than short-circuiting.
        let wanted = keys(&[("post.new", "New Post"), ("post.help", "First")]);
        let generated = merge_en_ftl("", "Post", "post", &wanted);
        let with_note = generated.replace(
            "post.new = New Post\n",
            &format!("post.new = New Post\n{note}\n"),
        );
        assert!(with_note.contains(note), "fixture: {with_note}");

        let out = merge_en_ftl(&with_note, "Post", "post", &wanted);
        assert!(
            out.contains(note),
            "a translator's note must survive regeneration:\n{out}"
        );
    }

    /// `fn main_preview()` is a different function that happens to share a
    /// prefix; anchoring on it wires the wrong builder, silently and (thanks to
    /// the idempotency guard) unrepairably.
    /// "First `.routes(` after `fn main`" is not the same as "inside `main`".
    /// The layout that separates them is ordinary: a builder helper above
    /// `main`, and a `#[cfg(test)]` builder below it.
    #[test]
    fn the_anchor_stays_inside_mains_body() {
        let main_rs = concat!(
            "fn build_app() -> App {\n",
            "    App::new()\n",
            "        .routes(routes![index])\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    build_app().serve();\n",
            "}\n",
            "\n",
            "#[cfg(test)]\n",
            "fn test_app() -> App {\n",
            "    App::new()\n",
            "        .routes(routes![fixture])\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        let real_at = out.find("routes![index]").unwrap();
        let test_at = out.find("routes![fixture]").unwrap();
        let call_at = out.find(".i18n_auto()").expect("inserted");
        assert!(
            call_at < real_at,
            "`main` has no builder of its own, so the only real one wins — \
             never the `#[cfg(test)]` one:\n{out}"
        );
        assert!(call_at < test_at, "{out}");
    }

    /// A char literal is not syntax. `let open = '{';` inside `main` would
    /// otherwise leave `brace_block` unable to find where `main` ends, and the
    /// anchor would fall back to an earlier helper's builder.
    #[test]
    fn a_char_literal_does_not_break_the_body_bounds() {
        let main_rs = concat!(
            "fn preview() -> App {\n",
            "    App::new()\n",
            "        .routes(routes![preview])\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    let open = '{';\n",
            "    let quote = '\"';\n",
            "    let tick = '\\'';\n",
            "    let app = App::new()\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        let preview_at = out.find("routes![preview]").unwrap();
        let call_at = out.find(".i18n_auto()").expect("inserted");
        assert!(
            call_at > preview_at,
            "the builder in `main` is still the one that runs:\n{out}"
        );
    }

    /// The runtime merges `[profile.<env>]`'s `i18n` however it is spelled, so
    /// a warning keyed on a header ending in `.i18n` misses most of them —
    /// and a missed profile override is a production startup panic.
    #[test]
    fn every_spelling_of_a_profile_override_is_reported() {
        for src in [
            "[profile.prod.i18n]\ndir = \"translations\"\ndefault_locale = \"fr\"\n",
            "[profile.prod]\ni18n = { dir = \"translations\", default_locale = \"fr\" }\n",
            "[profile.prod]\ni18n.dir = \"translations\"\ni18n.default_locale = \"fr\"\n",
            "profile.prod.i18n.dir = \"translations\"\nprofile.prod.i18n.default_locale = \"fr\"\n",
            "[\"profile\".\"prod\".\"i18n\"]\ndir = \"translations\"\ndefault_locale = \"fr\"\n",
        ] {
            assert_eq!(
                profile_i18n_overrides(src, "i18n", "en"),
                vec![("prod".to_owned(), "translations/fr.ftl".to_owned())],
                "for {src:?}"
            );
        }
        // A profile that agrees with the base is not an override.
        assert!(
            profile_i18n_overrides("[profile.prod.i18n]\ndir = \"i18n\"\n", "i18n", "en")
                .is_empty()
        );
    }

    /// The generator emits the JSON `COPY` form itself for a `dir` with
    /// whitespace, so a stale-pair detector that only splits on spaces cannot
    /// see the lines it wrote — the paths that most need quoting would be the
    /// ones that never get warned about.
    #[test]
    fn a_stale_json_form_copy_is_still_recognised() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "COPY migrations ./migrations\n",
            "COPY [\"translations v2\", \"./translations v2\"]\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
            "COPY --from=builder [\"/app/translations v2\", \"/app/translations v2\"]\n",
        );
        assert_eq!(
            stale_dockerfile_i18n_dir(dockerfile, "i18n").as_deref(),
            Some("translations v2")
        );
        // The same directory, configured, is not stale.
        assert_eq!(
            stale_dockerfile_i18n_dir(dockerfile, "translations v2"),
            None
        );
    }

    /// `main` may build the app conditionally. Wiring only the first branch
    /// leaves the other rendering raw keys, and unrepairably: a later run sees
    /// the call inserted into the first and stops.
    #[test]
    fn every_production_branch_inside_main_is_wired() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = if cfg!(feature = \"admin\") {\n",
            "        App::new()\n",
            "            .routes(routes![admin]);\n",
            "    } else {\n",
            "        App::new()\n",
            "            .routes(routes![index]);\n",
            "    };\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        assert_eq!(
            out.matches(".i18n_auto()").count(),
            2,
            "both branches must be wired:\n{out}"
        );

        // And a re-run is a no-op rather than a second insertion.
        assert_eq!(ensure_i18n_auto(&out), I18nAutoWiring::Wired(out.clone()));
    }

    /// One branch installing its own bundle says nothing about its sibling.
    /// Blocking on it left the other branch rendering raw keys.
    #[test]
    fn a_custom_bundle_in_one_branch_does_not_block_the_other() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = if flag {\n",
            "        App::new()\n",
            "            .i18n(tms_bundle())\n",
            "            .routes(routes![admin]);\n",
            "    } else {\n",
            "        App::new()\n",
            "            .routes(routes![index]);\n",
            "    };\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("the plain branch must still be wired");
        };
        assert_eq!(
            out.matches(".i18n_auto()").count(),
            1,
            "exactly the unconfigured chain gets it:\n{out}"
        );
        // The hand-installed bundle is untouched, and `.i18n_auto()` did not
        // land in its chain — that would clear it.
        assert!(out.contains(".i18n(tms_bundle())"), "{out}");
        let custom_at = out.find(".i18n(tms_bundle())").unwrap();
        let auto_at = out.find(".i18n_auto()").unwrap();
        assert!(auto_at > custom_at, "wired the wrong chain:\n{out}");
    }

    /// When the ONLY production chain carries its own bundle, that is still
    /// reported rather than silently called wired.
    #[test]
    fn a_sole_custom_bundled_chain_is_still_reported() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .i18n(my_bundle())\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// A partly-wired file gets completed, not skipped: one branch already
    /// carrying the call says nothing about its sibling.
    #[test]
    fn a_partly_wired_main_is_completed() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = if flag {\n",
            "        App::new()\n",
            "            .i18n_auto()\n",
            "            .routes(routes![admin]);\n",
            "    } else {\n",
            "        App::new()\n",
            "            .routes(routes![index]);\n",
            "    };\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        assert_eq!(
            out.matches(".i18n_auto()").count(),
            2,
            "the unwired branch must be completed:\n{out}"
        );
    }

    /// `EMBEDDED_LOCALES` in a `#[cfg(test)]` fixture is not the binary's
    /// embedding — treating it as one ships a release `--embed` binary with no
    /// bundle, which panics without the sidecar directory.
    #[test]
    fn a_cfg_test_mention_does_not_count_as_embedded_locales() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    static EMBEDDED_LOCALES: Dir = autumn_web::embed_locales!(\"fixtures\");\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert!(
            out.contains("#[cfg(feature = \"embed-assets\")]"),
            "production embedding must still be added:\n{out}"
        );
        assert!(
            out.contains(".embedded_locales(&EMBEDDED_LOCALES)"),
            "{out}"
        );
    }

    /// Two ordinary builders and no builder in `main` is a coin flip. Wiring
    /// the wrong one leaves production rendering raw keys, and the inserted
    /// call makes every later run a no-op, so the flip cannot be retried — a
    /// refusal the caller warns about is worth more.
    #[test]
    fn an_ambiguous_delegating_main_is_refused_rather_than_guessed() {
        let main_rs = concat!(
            "fn preview() -> App {\n",
            "    App::new().routes(routes![preview])\n",
            "}\n",
            "\n",
            "fn build_app() -> App {\n",
            "    App::new().routes(routes![index])\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    build_app().serve();\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::NoAnchor);
    }

    /// A `#[cfg(test)]` builder is not a candidate — it cannot be the one the
    /// binary runs — so the very common `build_app()` + fixture shape stays
    /// unambiguous rather than being refused.
    #[test]
    fn a_cfg_test_builder_is_not_a_candidate() {
        let main_rs = concat!(
            "fn build_app() -> App {\n",
            "    App::new().routes(routes![index])\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    build_app().serve();\n",
            "}\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    fn test_app() -> App {\n",
            "        App::new().routes(routes![fixture])\n",
            "    }\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        let real_at = out.find("routes![index]").unwrap();
        let fixture_at = out.find("routes![fixture]").unwrap();
        let call_at = out.find(".i18n_auto()").expect("inserted");
        assert!(call_at < real_at && call_at < fixture_at, "{out}");
    }

    /// A custom bundle installed on a TEST builder says nothing about the
    /// production one — reporting it file-wide left production unwired.
    #[test]
    fn a_custom_bundle_on_a_test_builder_does_not_block_production() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .routes(routes![index]);\n",
            "}\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    fn test_app() -> App {\n",
            "        App::new().i18n(test_bundle()).routes(routes![fixture])\n",
            "    }\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected production to be wired, not reported as custom-bundled");
        };
        assert!(out.contains(".i18n_auto()"), "{out}");
    }

    /// `.i18n_auto()` CLEARS a preloaded bundle and switches to filesystem
    /// loading, so failing to spot a hand-installed `.i18n(…)` does not merely
    /// add a call — it replaces the app's own bundle.
    #[test]
    fn a_custom_bundle_is_seen_through_whitespace_and_comments() {
        for call in [
            ".i18n(my_bundle())",
            ".i18n (my_bundle())",
            ".i18n\n        (my_bundle())",
            ".i18n /* keep ours */ (my_bundle())",
        ] {
            let main_rs = format!(
                "fn main() {{\n    let app = App::new()\n        {call}\n        .routes(routes![index]);\n}}\n"
            );
            assert_eq!(
                ensure_i18n_auto(&main_rs),
                I18nAutoWiring::CustomBundle,
                "for {call:?}"
            );
        }
        // `.i18n_auto()` is a different method that starts with the same name,
        // and must still read as already-wired rather than as a custom bundle.
        let wired = "fn main() {\n    let app = App::new()\n        .i18n_auto()\n        .routes(routes![index]);\n}\n";
        assert!(matches!(ensure_i18n_auto(wired), I18nAutoWiring::Wired(_)));
    }

    /// A `#[cfg(test)] static …;` ends with a semicolon, not a brace. Reading
    /// the next brace instead skipped past it onto an unrelated later item —
    /// missing the test-only static AND pulling that later item into the
    /// cfg(test) region.
    #[test]
    fn a_cfg_test_static_is_scoped_to_its_own_semicolon() {
        // The semicolon-terminated static is test-only, and the following
        // item must not be dragged into `cfg(test)` with it: a test-only
        // static must not suppress production wiring, and must not have its
        // install spliced into production either.
        let main_rs = concat!(
            "#[cfg(test)]\n",
            "static EMBEDDED_LOCALES: Dir = autumn_web::embed_locales!(\"fixtures\");\n",
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert!(
            out.contains("#[cfg(feature = \"embed-assets\")]"),
            "production embedding must be added:\n{out}"
        );
    }

    /// Whitespace and comments between a method and its paren are valid Rust,
    /// and every method detection in this module has to tolerate them — not
    /// just the one a review happened to name. Missing the `.routes` anchor is
    /// the worst of them: the scaffold emits translated views and never
    /// installs the bundle that resolves them.
    #[test]
    fn method_detections_all_tolerate_spacing() {
        for call in [".routes(routes![index])", ".routes (routes![index])"] {
            let main_rs = format!("fn main() {{\n    let app = App::new()\n        {call};\n}}\n");
            assert!(
                matches!(ensure_i18n_auto(&main_rs), I18nAutoWiring::Wired(out) if out.contains(".i18n_auto()")),
                "no anchor found for {call:?}"
            );
        }

        // An already-wired chain is recognised through spacing too, so a
        // re-run does not insert a second call.
        let spaced = concat!(
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .i18n_auto ()\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(
            ensure_i18n_auto(spaced),
            I18nAutoWiring::Wired(spaced.to_owned()),
            "a spaced `.i18n_auto ()` must count as wired"
        );

        // And so is a spaced embed install.
        let embedded = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "#[cfg(feature = \"embed-assets\")]\n",
            "static EMBEDDED_LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "    let app = app.embedded_locales (&EMBEDDED_LOCALES);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(embedded, "i18n").expect("anchors present");
        assert_eq!(
            out.matches("embedded_locales").count(),
            embedded.matches("embedded_locales").count(),
            "a spaced install must not be duplicated:\n{out}"
        );
    }

    /// A preview helper is ordinary non-test code, so "outside `cfg(test)`" is
    /// not the same question as "production". One of those installing the
    /// locales says nothing about the chain the binary runs.
    #[test]
    fn an_install_in_a_helper_does_not_count_as_production() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "#[cfg(feature = \"embed-assets\")]\n",
            "static EMBEDDED_LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();\n",
            "\n",
            "fn preview() -> App {\n",
            "    let app = App::new().routes(routes![preview]);\n",
            "    let app = app.embedded_locales(&EMBEDDED_LOCALES);\n",
            "    app\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new().routes(routes![index]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert!(
            out.matches(".embedded_locales(&EMBEDDED_LOCALES)").count() >= 2,
            "production must get its own install, not inherit the helper's:\n{out}"
        );
    }

    /// `t!` resolves its validation bundle from `AUTUMN_I18N_FILE`, else
    /// `i18n/$AUTUMN_I18N_DEFAULT_LOCALE.ftl`. Keeping a hardcoded
    /// `i18n/en.ftl` in step syncs the wrong file whenever a build configures
    /// either one, and every generated lookup then expands to a
    /// `compile_error!` against a bundle that never received the keys.
    #[test]
    fn the_validator_bundle_follows_the_macros_own_environment() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("i18n")).unwrap();

        // Nothing configured, nothing on disk: no compile-time check to satisfy.
        assert_eq!(validator_bundle_path(root, &MacroEnv::default()), None);

        std::fs::write(root.join("i18n").join("en.ftl"), "a = A\n").unwrap();
        assert_eq!(
            validator_bundle_path(root, &MacroEnv::default()),
            Some(root.join("i18n").join("en.ftl"))
        );

        // A configured locale moves the validator off `en` entirely.
        let fr = MacroEnv {
            file: None,
            default_locale: Some("fr".to_owned()),
        };
        assert_eq!(
            validator_bundle_path(root, &fr),
            None,
            "the macro degrades to a runtime lookup when its bundle is absent"
        );
        std::fs::write(root.join("i18n").join("fr.ftl"), "a = A\n").unwrap();
        assert_eq!(
            validator_bundle_path(root, &fr),
            Some(root.join("i18n").join("fr.ftl")),
            "not `en.ftl`, which the macro would never read here"
        );

        // An explicit file wins over the directory convention.
        std::fs::write(root.join("custom.ftl"), "a = A\n").unwrap();
        let explicit = MacroEnv {
            file: Some("custom.ftl".to_owned()),
            default_locale: Some("fr".to_owned()),
        };
        assert_eq!(
            validator_bundle_path(root, &explicit),
            Some(root.join("custom.ftl"))
        );
    }

    /// A missing `AUTUMN_I18N_FILE` does not turn validation OFF — the macro
    /// guards that path with `is_file()` and goes on to the locale candidate.
    /// Stopping at the explicit path leaves the bundle it actually opens
    /// without the generated keys.
    #[test]
    fn an_absent_explicit_bundle_falls_through_to_the_locale_candidate() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("i18n")).unwrap();
        std::fs::write(root.join("i18n").join("fr.ftl"), "a = A\n").unwrap();
        let env = MacroEnv {
            file: Some("gone.ftl".to_owned()),
            default_locale: Some("fr".to_owned()),
        };
        assert_eq!(
            validator_bundle_path(root, &env),
            Some(root.join("i18n").join("fr.ftl"))
        );
        // And with neither present there is genuinely nothing to keep in step.
        let nothing = MacroEnv {
            file: Some("gone.ftl".to_owned()),
            default_locale: Some("de".to_owned()),
        };
        assert_eq!(validator_bundle_path(root, &nothing), None);
    }

    /// A setting the macro needs on every build lives in `.cargo/config.toml`,
    /// which this process does not inherit.
    #[test]
    fn cargo_config_env_reads_both_entry_forms() {
        let root = Path::new("/project");
        let config = concat!(
            "[env]\n",
            "AUTUMN_I18N_DEFAULT_LOCALE = \"fr\"\n",
            "AUTUMN_I18N_FILE = { value = \"bundles/app.ftl\", relative = true }\n",
            "FORCED = { value = \"yes\", force = true }\n",
        );
        let env = cargo_config_env(config, root);
        assert_eq!(
            env.get("AUTUMN_I18N_DEFAULT_LOCALE"),
            Some(&("fr".to_owned(), false))
        );
        assert_eq!(
            env.get("AUTUMN_I18N_FILE"),
            Some(&(
                root.join("bundles/app.ftl").to_string_lossy().into_owned(),
                false
            )),
            "`relative` resolves against the directory holding `.cargo`"
        );
        assert_eq!(env.get("FORCED"), Some(&("yes".to_owned(), true)));
        // An unparseable or table-less config is simply nothing to layer.
        assert!(cargo_config_env("not = [toml", root).is_empty());
        assert!(cargo_config_env("[build]\njobs = 2\n", root).is_empty());
    }

    /// Cargo reads `.cargo/config[.toml]` from the directory and every
    /// ancestor, merging with the nearer file winning. A generated app nested
    /// in a workspace usually has no `.cargo` of its own and inherits the
    /// root's, so reading only its own directory takes a locale cargo never
    /// applies.
    #[test]
    fn the_cargo_config_chain_is_walked_nearest_first() {
        let tmp = tempfile::TempDir::new().unwrap();
        let workspace = tmp.path();
        let app = workspace.join("apps").join("web");
        std::fs::create_dir_all(app.join(".cargo")).unwrap();
        std::fs::create_dir_all(workspace.join(".cargo")).unwrap();
        std::fs::write(
            workspace.join(".cargo").join("config.toml"),
            "[env]\nAUTUMN_I18N_DEFAULT_LOCALE = \"de\"\n\
             AUTUMN_I18N_FILE = { value = \"root.ftl\", relative = true }\n",
        )
        .unwrap();

        // Inherited from the workspace root when the app carries nothing.
        let files = cargo_config_files(&app);
        assert!(
            files.iter().any(|(base, path)| base == workspace
                && path == &workspace.join(".cargo").join("config.toml")),
            "the workspace config applies to the app: {files:?}"
        );

        // And the nearer file wins where both name the same variable.
        std::fs::write(
            app.join(".cargo").join("config.toml"),
            "[env]\nAUTUMN_I18N_DEFAULT_LOCALE = \"es\"\n",
        )
        .unwrap();
        let mut merged: BTreeMap<String, (String, bool)> = BTreeMap::new();
        for (base, path) in cargo_config_files(&app) {
            let Ok(text) = std::fs::read_to_string(&path) else {
                continue;
            };
            for (name, entry) in cargo_config_env(&text, &base) {
                merged.entry(name).or_insert(entry);
            }
        }
        assert_eq!(
            merged.get("AUTUMN_I18N_DEFAULT_LOCALE"),
            Some(&("es".to_owned(), false)),
            "nearest wins"
        );
        assert_eq!(
            merged.get("AUTUMN_I18N_FILE"),
            Some(&(
                workspace.join("root.ftl").to_string_lossy().into_owned(),
                false
            )),
            "an unshadowed entry still comes through, and a `relative` one \
             resolves against ITS OWN base — the workspace, not the app"
        );
    }

    /// Cargo's precedence: the process wins unless the entry says `force`.
    #[test]
    fn a_cargo_config_entry_yields_to_the_process_unless_forced() {
        let plain = ("config".to_owned(), false);
        let forced = ("config".to_owned(), true);
        assert_eq!(
            layer_cargo_env(Some(&plain), None),
            Some("config".to_owned())
        );
        assert_eq!(
            layer_cargo_env(Some(&plain), Some("process".to_owned())),
            Some("process".to_owned())
        );
        assert_eq!(
            layer_cargo_env(Some(&forced), Some("process".to_owned())),
            Some("config".to_owned())
        );
        assert_eq!(
            layer_cargo_env(None, Some("process".to_owned())),
            Some("process".to_owned())
        );
        assert_eq!(layer_cargo_env(None, None), None);
    }

    /// `ADMIN_EMBEDDED_LOCALES` is not this static. Reading it as one reports
    /// the file as already embedded and then installs `&EMBEDDED_LOCALES` — a
    /// symbol nothing declares, so the `--embed` build stops compiling.
    #[test]
    fn a_longer_identifier_is_not_this_static() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "#[cfg(feature = \"embed-assets\")]\n",
            "static ADMIN_EMBEDDED_LOCALES: autumn_web::include_dir::Dir =\n",
            "    autumn_web::embed_locales!(\"admin\");\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new().routes(routes![index]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert!(
            out.contains("static EMBEDDED_LOCALES:"),
            "this static must be declared, not assumed:\n{out}"
        );
        assert!(
            out.contains("autumn_web::embed_locales!(\"admin\")"),
            "the unrelated bundle must keep its own directory:\n{out}"
        );
    }

    /// And when both statics exist, repointing follows the DECLARATION rather
    /// than the file's first `embed_locales!`: rewriting the neighbour ships
    /// the admin app this resource's translations and leaves the static this
    /// call is about still pointing at its stale directory.
    #[test]
    fn only_this_statics_own_macro_is_repointed() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "#[cfg(feature = \"embed-assets\")]\n",
            "static ADMIN_EMBEDDED_LOCALES: autumn_web::include_dir::Dir =\n",
            "    autumn_web::embed_locales!(\"admin\");\n",
            "#[cfg(feature = \"embed-assets\")]\n",
            "static EMBEDDED_LOCALES: autumn_web::include_dir::Dir =\n",
            "    autumn_web::embed_locales!(\"old\");\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new().routes(routes![index]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "    let app = app.embedded_locales(&EMBEDDED_LOCALES);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "translations").expect("already embedded");
        assert!(
            out.contains("autumn_web::embed_locales!(\"admin\")"),
            "the neighbour is not this static's to rewrite:\n{out}"
        );
        assert!(
            out.contains("autumn_web::embed_locales!(\"translations\")"),
            "this static must follow the configured directory:\n{out}"
        );
        assert!(
            !out.contains("\"old\""),
            "the stale directory must go:\n{out}"
        );
    }

    /// Block comments NEST, and a comment sitting between a method name and
    /// its call must not hide a bundle it wraps.
    #[test]
    fn a_nested_block_comment_does_not_hide_a_bundle() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .i18n /* outer /* nested */ tail */ (tms_bundle())\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(
            ensure_i18n_auto(main_rs),
            I18nAutoWiring::CustomBundle,
            "the commented-through `.i18n(...)` is still a call"
        );
    }

    /// Detection and insertion have to be asked about the SAME code. Scoping
    /// only the detection left the insertion taking the file's FIRST
    /// `embedded_static` line, which with a preview helper above `main` is the
    /// helper's: the tool then reported the embed as configured while the
    /// production binary still fell through to a disk load — and panicked on a
    /// deployment with no sidecar locale directory.
    #[test]
    fn the_install_is_written_into_the_production_builder() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "\n",
            "fn preview() -> App {\n",
            "    let app = App::new().routes(routes![preview]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "    app\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new().routes(routes![index]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        let main_at = out.find("fn main").expect("`fn main` survives");
        let install_at = out
            .find(".embedded_locales(&EMBEDDED_LOCALES)")
            .expect("the install is written");
        assert!(
            install_at > main_at,
            "the install belongs to the production builder, not the helper:\n{out}"
        );
        assert_eq!(
            out.matches(".embedded_locales(&EMBEDDED_LOCALES)").count(),
            1,
            "exactly one install:\n{out}"
        );
    }

    /// `embed_locales!` bakes the files in; `.embedded_locales(&…)` is what
    /// makes the app read them. With the static present and the install
    /// missing, an `--embed` build carries the bundle and never loads it — and
    /// then panics on a host with no sidecar directory, having reported the
    /// setup as complete.
    #[test]
    fn a_static_without_its_install_is_not_complete() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "#[cfg(feature = \"embed-assets\")]\n",
            "static EMBEDDED_LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert!(
            out.contains(".embedded_locales(&EMBEDDED_LOCALES)"),
            "the missing install must be added:\n{out}"
        );
        // And a complete setup is left exactly as it is.
        assert_eq!(
            ensure_embedded_locales(&out, "i18n").as_deref(),
            Some(out.as_str()),
            "must be idempotent"
        );
    }

    /// A nested block between `.i18n(...)` and `.routes(...)` is ordinary
    /// middleware. Reading its closing brace as the statement boundary hid the
    /// custom bundle, and `.i18n_auto()` was then inserted into that chain —
    /// which CLEARS the bundle it was hiding.
    #[test]
    fn a_nested_block_does_not_truncate_the_chain() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .i18n(tms_bundle())\n",
            "        .layer(from_fn(|req, next| async move { next.run(req).await }))\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(
            ensure_i18n_auto(main_rs),
            I18nAutoWiring::CustomBundle,
            "the earlier `.i18n(...)` must still be visible past the closure"
        );
    }

    /// `let app = app.i18n(bundle);` followed by `let app = app.routes(…);` is
    /// the ordinary builder rebinding — one app, two statements. Scoping the
    /// custom-bundle question to the CHAIN saw only the second and called the
    /// app unbundled, so `.i18n_auto()` went in and CLEARED the bundle.
    #[test]
    fn a_bundle_installed_by_an_earlier_rebinding_is_still_found() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new();\n",
            "    let app = app.i18n(tms_bundle());\n",
            "    let app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
        );
        assert_eq!(
            ensure_i18n_auto(main_rs),
            I18nAutoWiring::CustomBundle,
            "rebinding the same `app` is one builder, not two unrelated chains"
        );
    }

    /// A bundle installed BEFORE an `if` is inherited by every branch. A
    /// block-scoped search starts at the branch's own brace and cannot see it,
    /// so `.i18n_auto()` went into each branch and CLEARED it.
    #[test]
    fn a_bundle_inherited_from_an_enclosing_statement_is_still_found() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new().i18n(tms_bundle());\n",
            "    let app = if flag {\n",
            "        app.routes(routes![admin])\n",
            "    } else {\n",
            "        app.routes(routes![index])\n",
            "    };\n",
            "    app.serve();\n",
            "}\n",
        );
        assert_eq!(
            ensure_i18n_auto(main_rs),
            I18nAutoWiring::CustomBundle,
            "every branch continues the app the bundle was installed on"
        );
    }

    /// The mirror of it, and the reason the search cannot simply widen to the
    /// enclosing function: a bundle installed only in a SIBLING branch is not
    /// this branch's, and reading it as one leaves this branch rendering raw
    /// keys.
    #[test]
    fn a_sibling_branchs_bundle_is_still_not_this_branchs() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = if flag {\n",
            "        App::new().i18n(tms_bundle()).routes(routes![admin])\n",
            "    } else {\n",
            "        App::new().routes(routes![index])\n",
            "    };\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("the plain branch must still be wired");
        };
        assert_eq!(
            out.matches(".i18n_auto()").count(),
            1,
            "exactly the unconfigured branch gets it:\n{out}"
        );
        let custom_at = out.find(".i18n(tms_bundle())").unwrap();
        let auto_at = out.find(".i18n_auto()").unwrap();
        assert!(auto_at > custom_at, "wired the wrong branch:\n{out}");
    }

    /// The already-wired question is asked the same way, so an inherited
    /// `.i18n_auto()` is not wired a second time.
    #[test]
    fn an_inherited_auto_wiring_is_not_repeated() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new().i18n_auto();\n",
            "    let app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
        );
        assert_eq!(
            ensure_i18n_auto(main_rs),
            I18nAutoWiring::Wired(main_rs.to_owned()),
            "the app already loads its bundle; nothing to add"
        );
    }

    /// A call on an UNRELATED value is not this app's. A lexical-depth scan
    /// counted every earlier call at the same level, so a preview builder
    /// beside the production one spoke for it — and for `.i18n_auto` that is
    /// the silent failure: nothing warns, and production renders raw keys.
    #[test]
    fn a_call_on_another_binding_does_not_speak_for_this_app() {
        let wired = concat!(
            "fn main() {\n",
            "    let preview = App::new();\n",
            "    let preview = preview.i18n_auto();\n",
            "    let app = App::new();\n",
            "    let app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(wired) else {
            panic!("production is not wired by the preview builder");
        };
        assert_eq!(
            out.matches(".i18n_auto()").count(),
            2,
            "production needs its own:\n{out}"
        );

        let bundled = wired.replace(".i18n_auto()", ".i18n(tms_bundle())");
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(&bundled) else {
            panic!("the preview's bundle is not production's either");
        };
        assert!(out.contains(".i18n_auto()"), "{out}");
    }

    /// `let mut app = …; app = app.i18n(b); app = app.routes(…);` is the
    /// mutable spelling of the same builder. Reading only `let` skipped the
    /// assignment that installs the bundle, and `.i18n_auto()` went in and
    /// CLEARED it.
    #[test]
    fn a_bundle_installed_by_a_mutable_reassignment_is_still_found() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let mut app = build_app();\n",
            "    app = app.i18n(tms_bundle());\n",
            "    app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// A bundle installed on ONE branch of a conditional initialiser still
    /// reaches the joined value. Skipping it wires `.i18n_auto()` after the
    /// join, which CLEARS the bundle whenever the flag selects that branch.
    #[test]
    fn a_bundle_installed_in_one_branch_of_an_initialiser_is_still_found() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new();\n",
            "    let app = if use_tms { app.i18n(tms_bundle()) } else { app };\n",
            "    let app = app.routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// A bundle installed by a reassignment nested inside a bare `if`
    /// STATEMENT (no `let`, no `else`) still reaches the value after it: the
    /// `if` is not a value, so skipping it must not read the reassignment as
    /// never having happened. The dangerous read is the false negative —
    /// treating this app as unbundled clears a bundle installed on every run
    /// where the flag is set.
    #[test]
    fn a_bundle_installed_by_a_bare_conditional_reassignment_is_still_found() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let mut app = App::new();\n",
            "    if use_tms {\n",
            "        app = app.i18n(tms_bundle());\n",
            "    }\n",
            "    app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// And when the branches only CHOOSE between builders, each one's own
    /// binding is followed — the bundle can be a hop further back.
    #[test]
    fn every_branch_of_an_initialiser_is_followed_back() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let plain = App::new();\n",
            "    let tms = App::new().i18n(tms_bundle());\n",
            "    let app = if use_tms { tms } else { plain };\n",
            "    let app = app.routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// A closure body is not a branch. `.i18n(…)` inside middleware belongs to
    /// whatever that closure builds, and counting it would report an app as
    /// bundled because of something buried in a `.layer(…)` argument.
    #[test]
    fn a_call_inside_middleware_is_not_the_apps_own_bundle() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .layer(from_fn(|req, next| async move { other.i18n(b); next.run(req).await }))\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("middleware internals are not this app's bundle");
        };
        assert!(out.contains(".i18n_auto()"), "{out}");
    }

    /// Every production branch gets its own locale install. A `main` that
    /// builds the app conditionally has one `embedded_static` install per
    /// branch; serving only the first leaves the others loading from disk, so
    /// an `--embed` deployment panics whenever it takes one of them.
    #[test]
    fn every_production_branch_gets_the_locale_install() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "\n",
            "fn main() {\n",
            "    if flag {\n",
            "        let app = App::new().routes(routes![admin]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "    } else {\n",
            "        let app = App::new().routes(routes![index]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "    }\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        assert_eq!(
            out.matches(".embedded_locales(&EMBEDDED_LOCALES)").count(),
            2,
            "both branches must install them:\n{out}"
        );
        assert_eq!(
            ensure_embedded_locales(&out, "i18n").as_deref(),
            Some(out.as_str()),
            "and a re-run adds nothing"
        );
    }

    /// And an assignment to a DIFFERENT name still says nothing about this
    /// app — following assignments must not cost the receiver check.
    #[test]
    fn an_assignment_to_another_name_does_not_speak_for_this_app() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let mut preview = build_app();\n",
            "    preview = preview.i18n(tms_bundle());\n",
            "    let mut app = build_app();\n",
            "    app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("the preview's bundle is not production's");
        };
        assert!(out.contains(".i18n_auto()"), "{out}");
    }

    /// And a bundle two rebindings back is still this app's — giving up after
    /// one hop would clear it.
    #[test]
    fn a_bundle_reached_through_several_rebindings_is_still_found() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let base = App::new().i18n(tms_bundle());\n",
            "    let configured = base;\n",
            "    let app = configured;\n",
            "    let app = app.routes(routes![index]);\n",
            "}\n",
        );
        assert_eq!(ensure_i18n_auto(main_rs), I18nAutoWiring::CustomBundle);
    }

    /// A `#[cfg(test)]` fixture can declare the very same `EMBEDDED_STATIC`
    /// line. Writing the locale static beside the FIRST one puts it in the test
    /// module while the install goes into production — an `--embed` release
    /// that stops compiling on a symbol out of scope.
    #[test]
    fn the_locale_static_is_declared_beside_the_production_one() {
        let main_rs = concat!(
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "}\n",
            "\n",
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new().routes(routes![index]);\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        let mod_end = out
            .find("}\n\nstatic EMBEDDED_STATIC")
            .expect("test module");
        let locales_at = out
            .find("static EMBEDDED_LOCALES")
            .expect("the static is declared");
        assert!(
            locales_at > mod_end,
            "the locale static must sit outside `#[cfg(test)]`:\n{out}"
        );
    }

    /// And the widening stops at the function: a `#[cfg(test)]` fixture's own
    /// bundle is not production's, and reading it as one leaves the real app
    /// rendering raw keys.
    #[test]
    fn a_test_fixtures_bundle_does_not_speak_for_production() {
        let main_rs = concat!(
            "fn main() {\n",
            "    let app = App::new();\n",
            "    let app = app.routes(routes![index]);\n",
            "    app.serve();\n",
            "}\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    fn test_app() -> App {\n",
            "        App::new().i18n(fixture_bundle()).routes(routes![index])\n",
            "    }\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("production must still be wired");
        };
        assert!(out.contains(".i18n_auto()"), "{out}");
    }

    /// A `dir` with whitespace is a legal path, and the shell `COPY` form
    /// splits on it — three sources and a destination, not one of each.
    #[test]
    fn a_locale_dir_with_spaces_uses_dockers_json_copy_form() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "COPY migrations ./migrations\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
        );
        let out = ensure_dockerfile_i18n_copy(dockerfile, "translations v2").expect("anchors");
        assert!(
            out.contains(r#"COPY ["translations v2", "./translations v2"]"#),
            "{out}"
        );
        assert!(
            out.contains(r#"COPY --from=builder ["/app/translations v2", "/app/translations v2"]"#),
            "{out}"
        );
        // An ordinary directory keeps the conventional shell form.
        let plain = ensure_dockerfile_i18n_copy(dockerfile, "i18n").expect("anchors");
        assert!(plain.contains("COPY i18n ./i18n"), "{plain}");
    }

    /// Every spelling TOML allows for the same configuration reads the same.
    ///
    /// This is the table the hand-rolled scanner was extended for one row at a
    /// time, each miss shipping as a bug: a wrong bundle path, or a second
    /// `[i18n]` table appended over an existing one. Parsed properly, they are
    /// all just the same value.
    #[test]
    fn every_toml_spelling_of_the_i18n_table_reads_alike() {
        let expected = (Some("fr".to_owned()), Some("translations".to_owned()));
        for src in [
            "[i18n]\ndefault_locale = \"fr\"\ndir = \"translations\"\n",
            "[\"i18n\"]\ndefault_locale = \"fr\"\ndir = \"translations\"\n",
            "[i18n]\n\"default_locale\" = \"fr\"\n'dir' = \"translations\"\n",
            "i18n = { default_locale = \"fr\", dir = \"translations\" }\n",
            "\"i18n\" = { default_locale = \"fr\", dir = \"translations\" }\n",
            "i18n.default_locale = \"fr\"\ni18n.dir = \"translations\"\n",
            "\"i18n\".default_locale = \"fr\"\n\"i18n\".dir = \"translations\"\n",
            // Escapes are decoded, not passed through as source text.
            "[i18n]\ndefault_locale = \"\\u0066r\"\ndir = \"translations\"\n",
            // A comma inside a quoted value is part of the value, and a
            // trailing comment is not.
            "[i18n]\ndefault_locale = \"fr\" # the default\ndir = \"translations\"\n",
        ] {
            assert_eq!(configured_i18n(src), expected, "for {src:?}");
            assert!(defines_i18n(src), "for {src:?}");
        }

        // A comma really inside a value survives as one.
        assert_eq!(
            configured_i18n("i18n = { dir = \"translations,v2\", default_locale = \"fr\" }\n").1,
            Some("translations,v2".to_owned())
        );
        // Absent is still absent, and a malformed file still falls back rather
        // than failing generation.
        assert!(!defines_i18n("[server]\nport = 3000\n"));
        assert!(defines_i18n("[i18n]\nthis is not valid toml\n"));
    }

    /// A builder INSIDE `main` still wins over one that merely precedes it.
    #[test]
    fn a_builder_inside_main_is_preferred_to_an_earlier_one() {
        let main_rs = concat!(
            "fn preview() -> App {\n",
            "    App::new()\n",
            "        .routes(routes![preview])\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        let preview_at = out.find("routes![preview]").unwrap();
        let call_at = out.find(".i18n_auto()").expect("inserted");
        assert!(
            call_at > preview_at,
            "the builder in `main` is the one that runs:\n{out}"
        );
    }

    #[test]
    fn the_main_anchor_matches_on_an_identifier_boundary() {
        let main_rs = concat!(
            "fn main_preview() {\n",
            "    let app = App::new()\n",
            "        .routes(routes![preview]);\n",
            "}\n",
            "\n",
            "fn main() {\n",
            "    let app = App::new()\n",
            "        .routes(routes![index]);\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("expected a wiring");
        };
        let preview_at = out.find("routes![preview]").unwrap();
        let real_at = out.find("routes![index]").unwrap();
        let call_at = out.find(".i18n_auto()").expect("inserted");
        assert!(
            call_at > preview_at && call_at < real_at,
            "`.i18n_auto()` must land in `fn main`'s builder, not the preview \
             helper's:\n{out}"
        );
    }

    #[test]
    fn removal_takes_a_multi_line_value_with_its_key() {
        // A translator may wrap a value over indented continuation lines. Left
        // behind, they either fail the loader outright — and `.i18n_auto()`
        // turns that into a startup panic — or silently glue onto whichever key
        // precedes them, corrupting an unrelated translation.
        let ftl = concat!(
            "common.show = Show\n",
            "\n",
            "# Comment — generated by `autumn generate scaffold --i18n`.\n",
            "comment.new = New Comment\n",
            "\n",
            "# Post — generated by `autumn generate scaffold --i18n`.\n",
            "post.index.title = Post index\n",
            "    continued here\n",
            "post.new = New Post\n",
        );
        let out = remove_en_ftl_keys(ftl, "Post", "post", &chrome(&["common.show"]));
        assert!(
            !out.contains("continued here"),
            "an orphaned continuation either fails the loader — and `.i18n_auto()` \
             turns that into a startup panic — or silently glues onto the key above \
             it:\n{out}"
        );
        assert!(!out.contains("post."), "{out}");
        // The sibling resource keeps the chrome alive.
        assert!(out.contains("common.show = Show"), "{out}");
        assert!(out.contains("comment.new = New Comment"), "{out}");
    }

    /// Chrome is per-surface, so destroying the only resource that had a Trash
    /// view must take `common.trash`/`restore`/`purge` — and nothing else.
    #[test]
    fn chrome_is_pruned_per_key_not_all_or_nothing() {
        let ftl = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[
                ("common.create", "Create"),
                ("common.save", "Save"),
                ("common.trash", "Trash"),
                ("common.restore", "Restore"),
                ("post.new", "New Post"),
            ]),
        );
        // A plain sibling survives: it uses the CRUD chrome but no trash chrome.
        let out = remove_en_ftl_keys(
            &ftl,
            "Post",
            "post",
            &chrome(&["common.create", "common.save"]),
        );
        assert!(out.contains("common.create = Create"), "{out}");
        assert!(out.contains("common.save = Save"), "{out}");
        assert!(
            !out.contains("common.trash") && !out.contains("common.restore"),
            "chrome nothing references any more fails `--strict`:\n{out}"
        );
        assert!(!out.contains("post.new"), "{out}");
    }

    /// The resource's own block is pruned per key for the same reason the
    /// chrome block is. Hand-written code outside the generated module can
    /// render a generated key — a dashboard card or a nav link labelled
    /// `t!(locale, "post.index.title")` — and `t!` validates key existence at
    /// COMPILE time, so removing the whole block out from under it breaks the
    /// build. Keeping preservation to `common.*` drew the line in the wrong
    /// place.
    #[test]
    fn a_resource_key_something_still_references_survives_its_block() {
        let ftl = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[
                ("common.create", "Create"),
                ("post.index.title", "Posts"),
                ("post.new.title", "New Post"),
            ]),
        );
        let out = remove_en_ftl_keys(
            &ftl,
            "Post",
            "post",
            &chrome(&["common.create", "post.index.title"]),
        );
        assert!(
            out.contains("post.index.title = Posts"),
            "a live call site keeps its key:\n{out}"
        );
        assert!(
            !out.contains("post.new.title"),
            "keys nothing references still go — `--strict` fails on them:\n{out}"
        );
        assert!(out.contains("common.create = Create"), "{out}");
    }

    /// The other half: preservation follows what is DEFINED, so a scan that
    /// names a key the bundle never carried — a call site already failing `t!`
    /// before destroy ran — must not have an empty message invented for it.
    #[test]
    fn a_referenced_key_the_bundle_never_defined_is_not_invented() {
        let ftl = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("common.create", "Create"), ("post.index.title", "Posts")]),
        );
        let out = remove_en_ftl_keys(
            &ftl,
            "Post",
            "post",
            &chrome(&["common.create", "post.index.title", "post.never.defined"]),
        );
        assert!(!out.contains("post.never.defined"), "{out}");
    }

    #[test]
    fn removing_the_last_resource_takes_the_now_unreferenced_chrome_with_it() {
        let ftl = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("common.create", "Create"), ("post.new", "New Post")]),
        );
        let out = remove_en_ftl_keys(&ftl, "Post", "post", &HashSet::new());
        assert!(
            !out.contains("common.create"),
            "chrome nothing references any more fails `i18n check --strict`:\n{out}"
        );
        // …but a SIBLING resource keeps it alive.
        let two = merge_en_ftl(
            &ftl,
            "Comment",
            "comment",
            &keys(&[("common.create", "Create"), ("comment.new", "New Comment")]),
        );
        let still = remove_en_ftl_keys(&two, "Post", "post", &chrome(&["common.create"]));
        assert!(still.contains("common.create = Create"), "{still}");
        assert!(still.contains("comment.new = New Comment"), "{still}");
    }

    #[test]
    fn a_regenerated_key_lands_inside_its_own_block() {
        let first = merge_en_ftl("", "Post", "post", &keys(&[("post.new", "New Post")]));
        let second = merge_en_ftl(
            &first,
            "Post",
            "post",
            &keys(&[("post.new", "New Post"), ("post.field.body", "Body")]),
        );
        let header_at = second.find("Post — generated by").expect("header");
        let key_at = second.find("post.field.body").expect("new key");
        assert!(
            key_at > header_at,
            "the new key must sit under the header:\n{second}"
        );
        // …and above the block's closing marker, not stranded past it at EOF.
        let footer_at = second.find("# — end Post —").expect("footer");
        assert!(
            key_at < footer_at,
            "the new key must sit INSIDE the block:\n{second}"
        );
    }

    /// A `.ftl` is a file people edit. A translator who groups keys with a
    /// blank line, or leaves a note beside one, must not move the boundary of
    /// what `destroy` owns — otherwise it strands the keys below the separator
    /// with no call sites, and `autumn i18n check --strict` starts failing on
    /// keys whose owner nobody can find.
    /// A `--force` regeneration that dropped a field or a flag must not leave
    /// the keys for those surfaces behind: nothing references them any more, so
    /// `autumn i18n check --strict` fails on them.
    #[test]
    fn regeneration_prunes_keys_whose_surfaces_are_gone() {
        let before = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[
                ("common.create", "Create"),
                ("post.new", "New Post"),
                ("post.field.body", "Body"),
                ("post.search.title", "Search Posts"),
            ]),
        );
        // A translated value, and a note beside a key that survives.
        let edited = before
            .replace("post.new = New Post", "post.new = Nouvel article")
            .replace(
                "post.field.body = Body\n",
                "# on the edit form\npost.field.body = Body\n",
            );
        let after = merge_en_ftl(
            &edited,
            "Post",
            "post",
            &keys(&[("common.create", "Create"), ("post.new", "New Post")]),
        );
        assert!(!after.contains("post.field.body"), "{after}");
        assert!(!after.contains("post.search.title"), "{after}");
        assert!(
            after.contains("post.new = Nouvel article"),
            "a translated value must survive:\n{after}"
        );
        assert!(
            after.contains("# on the edit form"),
            "a translator's note must survive:\n{after}"
        );
        // Chrome is never pruned from here — a sibling resource writes it too.
        assert!(after.contains("common.create = Create"), "{after}");
        // And it settles: regenerating again changes nothing.
        assert_eq!(
            merge_en_ftl(
                &after,
                "Post",
                "post",
                &keys(&[("common.create", "Create"), ("post.new", "New Post")])
            ),
            after
        );
    }

    /// A Fluent continuation is just indented text and usually carries no `=`.
    /// Keeping one whose key was pruned orphans it — the loader either rejects
    /// the bundle (a startup panic, via `.i18n_auto()`) or glues the text onto
    /// the message above, rewriting an unrelated translation.
    #[test]
    fn regeneration_drops_continuation_lines_with_their_pruned_key() {
        let before = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("post.new", "New Post"), ("post.field.body", "Body")]),
        );
        // A wrapped value with NO `=` in the continuation, and a kept key that
        // also wraps — the first must go, the second must stay whole.
        let edited = before
            .replace(
                "post.field.body = Body\n",
                "post.field.body = Body\n    spilling over onto a second line\n",
            )
            .replace(
                "post.new = New Post\n",
                "post.new = New Post\n    also wrapped\n",
            );
        let after = merge_en_ftl(&edited, "Post", "post", &keys(&[("post.new", "New Post")]));
        assert!(!after.contains("post.field.body"), "{after}");
        assert!(
            !after.contains("spilling over"),
            "the pruned key's continuation must go with it:\n{after}"
        );
        assert!(
            after.contains("also wrapped"),
            "a surviving key keeps its own continuation:\n{after}"
        );
    }

    #[test]
    fn an_existing_embed_is_repointed_when_the_bundle_directory_changes() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let embedded = ensure_embedded_locales(main_rs, "i18n").expect("anchors present");
        // The project later moves its bundles; the embed has to follow, or an
        // `--embed` build ships a directory the app no longer reads.
        let moved = ensure_embedded_locales(&embedded, "translations").expect("already embedded");
        assert!(
            moved.contains("embed_locales!(\"translations\")"),
            "{moved}"
        );
        assert!(!moved.contains("embed_locales!()"), "{moved}");
        assert_eq!(
            moved.matches("EMBEDDED_LOCALES").count(),
            2,
            "repointing must not duplicate the wiring:\n{moved}"
        );
        // …and moving back works too, without stacking arguments.
        let back = ensure_embedded_locales(&moved, "i18n").expect("already embedded");
        assert!(back.contains("embed_locales!()"), "{back}");
        assert!(!back.contains("translations"), "{back}");
    }

    #[test]
    fn a_comment_or_blank_line_inside_a_block_does_not_truncate_it() {
        let ftl = merge_en_ftl(
            "",
            "Post",
            "post",
            &keys(&[("post.new", "New Post"), ("post.index.title", "Post index")]),
        );
        let edited = ftl.replace(
            "post.index.title = Post index\n",
            "\n# careful: this one is on a button\npost.index.title = Post index\n",
        );
        assert_ne!(edited, ftl, "fixture must actually insert the separator");
        let out = remove_en_ftl_keys(&edited, "Post", "post", &HashSet::new());
        assert!(
            !out.contains("post.index.title"),
            "a key below the separator is still the generator's:\n{out}"
        );
        assert!(!out.contains("post.new"), "{out}");
        assert!(!out.contains("# — end Post —"), "{out}");
    }

    /// A bundle written before blocks carried closing markers still merges and
    /// destroys correctly — the boundary falls back to the first blank line or
    /// foreign comment.
    #[test]
    fn a_block_without_a_closing_marker_still_round_trips() {
        let legacy = concat!(
            "# Post — generated by `autumn generate scaffold --i18n`.\n",
            "post.new = New Post\n",
            "\n",
            "# App copy\n",
            "post.email.subject = Welcome\n",
        );
        let out = remove_en_ftl_keys(legacy, "Post", "post", &chrome(&["common.create"]));
        assert!(!out.contains("post.new"), "{out}");
        assert!(out.contains("post.email.subject = Welcome"), "{out}");
    }

    /// A `dir` that moved since an earlier run leaves that run's `COPY` pair
    /// behind. `COPY` fails the build when its source is gone from the context,
    /// so this has to be surfaced rather than quietly doubled up.
    #[test]
    fn a_moved_locale_dir_is_reported_against_the_dockerfile() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "COPY migrations ./migrations\n",
            "COPY i18n ./i18n\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
            "COPY --from=builder /app/i18n /app/i18n\n",
        );
        assert_eq!(
            stale_dockerfile_i18n_dir(dockerfile, "translations").as_deref(),
            Some("i18n")
        );
        // The configured directory is not stale, and neither is a Dockerfile
        // this generator has never touched.
        assert_eq!(stale_dockerfile_i18n_dir(dockerfile, "i18n"), None);
        assert_eq!(
            stale_dockerfile_i18n_dir(
                "FROM rust AS builder\nCOPY migrations ./migrations\n",
                "i18n"
            ),
            None
        );
    }

    /// Docker strips comments before executing, so a `# COPY i18n ./i18n` left
    /// in the file as an example installs nothing. Reading it as installed
    /// returns the Dockerfile untouched and the container then panics in
    /// `.i18n_auto()` with no bundle to load.
    #[test]
    fn a_commented_copy_is_not_a_wired_dockerfile() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "# COPY i18n ./i18n\n",
            "COPY migrations ./migrations\n",
            "\n",
            "FROM debian AS runtime\n",
            "# COPY --from=builder /app/i18n /app/i18n\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
        );
        let out = ensure_dockerfile_i18n_copy(dockerfile, "i18n").expect("anchors present");
        // Asserted WITHOUT `has_active_line`: a test that checks the fix
        // through the helper the fix lives in passes with the fix reverted.
        let active = |needle: &str| out.lines().any(|line| line.trim() == needle);
        assert!(
            active("COPY i18n ./i18n"),
            "the builder stage needs a real instruction:\n{out}"
        );
        assert!(
            active("COPY --from=builder /app/i18n /app/i18n"),
            "and so does the runtime stage:\n{out}"
        );
        // The examples are left where they were.
        assert_eq!(out.matches("# COPY i18n ./i18n").count(), 1, "{out}");
    }

    /// And a COMMENTED anchor cannot capture the insertion either — the new
    /// line would land in a stage that never runs it.
    #[test]
    fn insertion_follows_the_active_anchor_not_a_commented_one() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "# COPY migrations ./migrations\n",
            "COPY migrations ./migrations\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
        );
        let out = ensure_dockerfile_i18n_copy(dockerfile, "i18n").expect("anchors present");
        let commented = out.find("# COPY migrations").expect("comment kept");
        let active = out
            .find("\nCOPY migrations ./migrations")
            .expect("active anchor kept");
        let inserted = out.find("COPY i18n ./i18n").expect("line inserted");
        assert!(
            inserted > active && active > commented,
            "the copy must follow the instruction, not the example:\n{out}"
        );
    }

    /// `#[cfg(unix)] fn main()` beside `#[cfg(windows)] fn main()` is one entry
    /// point per target and both are production. Wiring only the first leaves
    /// the other rendering raw keys, and the idempotency guard means no later
    /// run repairs it.
    #[test]
    fn every_cfg_selected_main_is_wired() {
        let main_rs = concat!(
            "#[cfg(unix)]\n",
            "fn main() {\n",
            "    App::new().routes(routes![index]).serve();\n",
            "}\n",
            "\n",
            "#[cfg(windows)]\n",
            "fn main() {\n",
            "    App::new().routes(routes![index]).serve();\n",
            "}\n",
        );
        let I18nAutoWiring::Wired(out) = ensure_i18n_auto(main_rs) else {
            panic!("both entry points are production");
        };
        assert_eq!(
            out.matches(".i18n_auto()").count(),
            2,
            "each `main` needs its own:\n{out}"
        );
        assert_eq!(
            ensure_i18n_auto(&out),
            I18nAutoWiring::Wired(out.clone()),
            "and a re-run adds nothing"
        );
    }

    /// A nested `dir` is a legal configuration, and one this generator writes
    /// the `COPY` pair for itself — so the detector has to read one back. The
    /// runtime side used to reject any path with a separator while the builder
    /// side accepted it, so the two could never agree and the warning never
    /// fired for the versioned-directory layout that most needs it.
    #[test]
    fn a_moved_nested_locale_dir_is_reported_too() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "COPY migrations ./migrations\n",
            "COPY locales/v1 ./locales/v1\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
            "COPY --from=builder /app/locales/v1 /app/locales/v1\n",
        );
        assert_eq!(
            stale_dockerfile_i18n_dir(dockerfile, "locales/v2").as_deref(),
            Some("locales/v1"),
            "the old pair is stale once `dir` moves"
        );
        assert_eq!(
            stale_dockerfile_i18n_dir(dockerfile, "locales/v1"),
            None,
            "and not stale while it is still the configured one"
        );
    }

    /// The shape it matches (`COPY <x> ./<x>`) is also an ordinary asset copy,
    /// so agreement across BOTH stages is what promotes it from coincidence —
    /// and even then the caller only warns.
    #[test]
    fn an_unrelated_copy_in_one_stage_is_not_read_as_a_moved_bundle() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "COPY migrations ./migrations\n",
            "COPY static ./static\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
            "COPY --from=builder /app/assets /app/assets\n",
        );
        assert_eq!(stale_dockerfile_i18n_dir(dockerfile, "i18n"), None);
    }

    /// A comma inside a quoted value belongs to the value. Split through it and
    /// `toml_scalar_value` sees an unterminated string and discards it, so the
    /// generator falls back to `i18n/` and writes where the runtime never looks.
    /// `["i18n"]` is the same table as `[i18n]`. Not recognising it appends a
    /// second definition of it, which makes `autumn.toml` unparseable for the
    /// app that has to read it.
    #[test]
    fn a_quoted_table_header_names_the_same_table() {
        assert_eq!(toml_table_name(r#"["i18n"]"#), Some("i18n"));
        assert_eq!(toml_table_name("['i18n']"), Some("i18n"));
        assert_eq!(toml_table_name("[i18n]"), Some("i18n"));
        assert_eq!(toml_table_name(r#"["i18n"]  # notes"#), Some("i18n"));
        assert!(defines_i18n(
            r#"["i18n"]
default_locale = "fr"
"#
        ));
        // Still not a table header at all.
        assert_eq!(toml_table_name("i18n = 1"), None);
    }

    #[test]
    fn an_inline_table_splits_on_separators_not_on_commas_in_values() {
        let toml = r#"i18n = { dir = "translations,v2", default_locale = "fr" }"#;
        assert_eq!(
            configured_i18n(toml),
            (Some("fr".to_owned()), Some("translations,v2".to_owned()))
        );
        // An escaped quote inside a basic string does not end it.
        let escaped = r#"i18n = { dir = "od\"d", default_locale = "fr" }"#;
        assert_eq!(configured_i18n(escaped).1.as_deref(), Some(r#"od"d"#));
    }

    /// `dir` is the one config value that becomes Rust SOURCE, and TOML happily
    /// carries characters Rust's lexer reads as escapes.
    #[test]
    fn the_embedded_locale_dir_is_escaped_as_a_rust_literal() {
        let main_rs = concat!(
            "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n",
            "fn main() {\n",
            "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
            "}\n",
        );
        let out = ensure_embedded_locales(main_rs, r"translations\bundles").expect("anchors");
        assert!(
            out.contains(r#"embed_locales!("translations\\bundles")"#),
            "a backslash must reach Rust as an escaped backslash, not as `\\b`:\n{out}"
        );
        let quoted = ensure_embedded_locales(main_rs, r#"od"d"#).expect("anchors");
        assert!(
            quoted.contains(r#"embed_locales!("od\"d")"#),
            "a quote must not terminate the literal:\n{quoted}"
        );
    }

    #[test]
    fn toml_values_are_decoded_before_they_become_paths() {
        // A basic string processes escapes; the app's loader reads the DECODED
        // value, so the generator has to write to the same place.
        assert_eq!(
            toml_scalar_value(r#" "fr" "#).as_deref(),
            Some("fr"),
            "a `\\u` escape must resolve"
        );
        assert_eq!(
            toml_scalar_value(r#" "i18n\\bundles" "#).as_deref(),
            Some(r"i18n\bundles"),
            "an escaped backslash is one backslash"
        );
        // A literal string does NOT process escapes, by TOML's definition.
        assert_eq!(
            toml_scalar_value(r" 'i18n\\bundles' ").as_deref(),
            Some(r"i18n\\bundles")
        );
        // An unknown escape survives rather than failing generation.
        assert_eq!(toml_scalar_value(r#" "a\qb" "#).as_deref(), Some(r"a\qb"));
        assert_eq!(toml_scalar_value(r#" "plain" "#).as_deref(), Some("plain"));
    }

    #[test]
    fn dockerfile_gains_the_bundle_in_both_stages() {
        let dockerfile = concat!(
            "FROM rust AS builder\n",
            "COPY migrations ./migrations\n",
            "\n",
            "FROM debian AS runtime\n",
            "COPY --from=builder /app/migrations /app/migrations\n",
        );
        let out = ensure_dockerfile_i18n_copy(dockerfile, "i18n").expect("anchors present");
        assert!(out.contains("COPY i18n ./i18n"), "{out}");
        assert!(
            out.contains("COPY --from=builder /app/i18n /app/i18n"),
            "{out}"
        );
        assert_eq!(
            ensure_dockerfile_i18n_copy(&out, "i18n").as_deref(),
            Some(out.as_str()),
            "must be idempotent"
        );
        // A Dockerfile with no anchor is reported, not guessed at.
        assert_eq!(ensure_dockerfile_i18n_copy("FROM scratch\n", "i18n"), None);
    }
}