autumn-cli 0.8.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
//! `autumn generate pwa` — scaffold an installable Progressive Web App.
//!
//! Creates:
//!   - `static/manifest.webmanifest`   — Web App Manifest (application/manifest+json)
//!   - `static/service-worker.js`      — Service Worker with offline-shell caching
//!   - `static/pwa-register.js`        — SW registration script (avoids CSP inline-script issues)
//!   - `static/icons/icon.svg`         — Placeholder app icon (replace with real PNG)
//!   - `static/icons/maskable-icon.svg` — Maskable variant (safe-zone compliant)
//!   - `src/main.rs`                   — Route handlers for `/manifest.webmanifest`,
//!     `/service-worker.js`, `/pwa-register.js`, and `/offline`; PWA `<link>` /
//!     `<meta>` tags injected into the shared `layout` head block.
//!   - `tests/system/pwa_smoke.rs`     — Smoke test (manifest content-type + SW registration)
//!   - `Cargo.toml`                    — `system-tests` feature added if absent

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

use autumn_web::config::DatabaseBackend;
use autumn_web::push::PUSH_SUBSCRIPTIONS_TABLE;

use super::dsl::{Field, FieldConstraints, FieldKind, IdType};
use super::emit::Plan;
use super::schema_edit::{
    create_table_sql_with_metadata_and_id_for, drop_table_sql, update_main_rs,
};
use super::system_test::patch_cargo_toml as patch_system_test_cargo_toml;
use super::{GenerateError, detect_backend, ensure_project_root, timestamp_now};

// ── Public API ────────────────────────────────────────────────────────────────

/// The actions and reverts common to both `plan_pwa` and
/// [`plan_pwa_destroy_fallback`]: every PWA-generated file is fully static
/// (parameter-free — none of it depends on `src/main.rs`'s current shape),
/// and the revert descriptors only need paths, not content (they read
/// `main.rs`/`Cargo.toml` fresh off disk when `Plan::revert` runs them).
fn plan_pwa_shared(project_root: &Path) -> Plan {
    let mut plan = Plan::new(project_root);

    // Static assets (served via generated route handlers + participate in fingerprinting)
    plan.create(
        project_root.join("static").join("manifest.webmanifest"),
        render_manifest(),
    );
    plan.create(
        project_root.join("static").join("service-worker.js"),
        render_service_worker(),
    );
    plan.create(
        project_root.join("static").join("pwa-register.js"),
        render_pwa_register_js(),
    );
    plan.create(
        project_root.join("static").join("icons").join("icon.svg"),
        render_icon_svg(),
    );
    plan.create(
        project_root
            .join("static")
            .join("icons")
            .join("maskable-icon.svg"),
        render_maskable_icon_svg(),
    );

    // Pushed unconditionally — see `plan_cargo_deps`'s matching comment in
    // model.rs: destroy recomputes this plan against the already-generated
    // main.rs, where these edits are by definition already present.
    let main_path = project_root.join("src").join("main.rs");
    plan.push_revert(crate::generate::emit::Revert::PwaMainRsInjection {
        path: main_path.clone(),
    });
    plan.push_revert(crate::generate::emit::Revert::RoutesEntries {
        path: main_path,
        entries: vec![
            "pwa_manifest".to_owned(),
            "pwa_service_worker".to_owned(),
            "pwa_register_js".to_owned(),
            "pwa_offline".to_owned(),
        ],
    });

    // migrations/<ts>_create_push_subscriptions/{up,down}.sql — the table the
    // framework's `DbPushSubscriptionStore` reads (issue #1392).
    //
    // Like the notifications feed, push subscriptions are a singleton scaffold:
    // re-running (especially with `--force`) must not mint a SECOND
    // `*_create_push_subscriptions` directory, since two `CREATE TABLE
    // push_subscriptions` migrations would fail the next `autumn migrate` on
    // the duplicate table and make destroy's suffix match ambiguous. So reuse
    // an existing directory when one is present, minting a fresh timestamped
    // one only on a clean project.
    let backend = detect_backend(project_root);
    let migration_dir = existing_push_migration_dir(project_root).unwrap_or_else(|| {
        project_root.join("migrations").join(format!(
            "{}_create_{PUSH_SUBSCRIPTIONS_TABLE}",
            timestamp_now()
        ))
    });
    plan.create(
        migration_dir.join("up.sql"),
        push_subscriptions_up_sql(backend),
    );
    plan.create(
        migration_dir.join("down.sql"),
        drop_table_sql(PUSH_SUBSCRIPTIONS_TABLE),
    );

    // System test
    let system_test_path = project_root
        .join("tests")
        .join("system")
        .join("pwa_smoke.rs");
    plan.create(system_test_path, render_pwa_system_test());

    // Cargo.toml: add system-tests feature if absent
    let cargo_path = project_root.join("Cargo.toml");
    plan.push_revert(crate::generate::emit::Revert::SystemTestCargoPatch {
        path: cargo_path,
        snake_name: "pwa_smoke".to_owned(),
    });

    plan
}

/// Compute the file actions for `autumn generate pwa`.
///
/// # Errors
/// Returns [`GenerateError::NotInProject`] when not at a project root,
/// [`GenerateError::Io`] if `src/main.rs` / `Cargo.toml` can't be read, or
/// [`GenerateError::Config`] when `src/main.rs`'s `layout()` doesn't accept
/// `current_path` — the generated `pwa_offline` handler calls `layout()`
/// with the current `nav_bar`-based scaffold's arity, so an app that
/// hasn't migrated its own `layout()` needs to before running this.
pub fn plan_pwa(project_root: &Path) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;

    // Read src/main.rs up front (rather than where it's injected below) so
    // the layout() shape can be validated before any plan actions are built.
    let main_path = project_root.join("src").join("main.rs");
    let main_existing = std::fs::read_to_string(&main_path).map_err(|_| {
        GenerateError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("missing {}", main_path.display()),
        ))
    })?;
    if layout_missing_current_path(&main_existing) {
        return Err(GenerateError::Config(format!(
            "{}'s layout() takes fewer than 4 parameters — the current \
             nav_bar-based scaffold needs layout(title: &str, current_path: &str, \
             flash: Markup, content: Markup) (see autumn-cli/src/templates/main.rs.tmpl \
             for the current shape; the path parameter's name doesn't matter) \
             before running `autumn generate pwa`",
            main_path.display()
        )));
    }

    let mut plan = plan_pwa_shared(project_root);

    // src/main.rs: inject PWA meta tags + route handlers (idempotent)
    let updated_main = inject_pwa_into_main(&main_existing);
    // A silently unmounted router is the worst outcome here: the command exits
    // 0, the client snippet ships, and every `fetch` it makes 404s with
    // nothing pointing at the cause. Say so instead.
    if !push_router_already_mounted(&updated_main) {
        plan.warn(
            "could not find the app builder in src/main.rs, so the Web Push routes were not \
             mounted. Add this line to your builder chain by hand:\n    \
             .merge(autumn_web::push::router())\n  \
             Without it the generated subscribe snippet will 404. See \
             docs/guide/web-push.md.",
        );
    }
    if updated_main != main_existing {
        plan.modify(main_path, updated_main);
    }

    // Cargo.toml: add system-tests feature if absent
    let cargo_path = project_root.join("Cargo.toml");
    let cargo_existing = std::fs::read_to_string(&cargo_path).map_err(GenerateError::Io)?;
    let patched_cargo = patch_system_test_cargo_toml(&cargo_existing, "pwa_smoke");
    if patched_cargo != cargo_existing {
        plan.modify(cargo_path, patched_cargo);
    }

    Ok(plan)
}

/// Destroy-only fallback (issue #1048 PR review): `plan_pwa` validates that
/// `src/main.rs`'s `layout()` takes 4 parameters before building anything —
/// necessary so a *fresh* generate never emits a call with the wrong arity,
/// but that precondition is irrelevant (and can wrongly block cleanup) once
/// `main.rs` has since been hand-edited, reverted, or otherwise no longer
/// matches the shape `plan_pwa` expects. Every PWA-generated file is fully
/// static, and `Plan::revert` never consults `Action::Modify` content —
/// only `self.reverts`, which read `main.rs`/`Cargo.toml` fresh off disk at
/// revert time — so `plan_pwa_shared` alone is already a complete, exact
/// destroy plan; unlike the model-dependent admin/migration fallbacks, no
/// `--force` is needed to use it.
pub fn plan_pwa_destroy_fallback(project_root: &Path) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    Ok(plan_pwa_shared(project_root))
}

// ── Content renderers ─────────────────────────────────────────────────────────

/// The existing `migrations/<ts>_create_push_subscriptions/` directory, if the
/// project already has one — so a re-run reuses it in place rather than
/// minting a second singleton migration. Matched by the same
/// `_create_push_subscriptions` suffix destroy uses, so the two stay in
/// agreement. If more than one somehow exists (a hand-added duplicate), the
/// lexicographically-smallest is chosen deterministically.
fn existing_push_migration_dir(project_root: &Path) -> Option<PathBuf> {
    let suffix = format!("_create_{PUSH_SUBSCRIPTIONS_TABLE}");
    let mut matches: Vec<PathBuf> = std::fs::read_dir(project_root.join("migrations"))
        .ok()?
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| {
            path.is_dir()
                && path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.ends_with(&suffix))
        })
        .collect();
    matches.sort();
    matches.into_iter().next()
}

/// The four non-`id` columns of the `push_subscriptions` table, expressed in
/// the migration DSL so the DDL comes out of the same shared helper every
/// other generator uses (`id` and `created_at` come from the helper itself).
///
/// The column types must match the framework store's diesel `table!` in
/// `autumn_web::push::store` (`Text` throughout; `Timestamptz` on Postgres,
/// `TimestamptzSqlite` — RFC 3339 `TEXT` — on SQLite): that store, not any
/// generated model, is what reads this table. The two key columns hold the
/// browser's own base64url strings rather than raw bytes, which keeps one
/// `table!` definition working on both backends.
fn push_subscription_fields() -> Vec<Field> {
    let field = |name: &str, unique: bool| Field {
        name: name.to_owned(),
        kind: FieldKind::String,
        nullable: false,
        variants: Vec::new(),
        unique,
        constraints: FieldConstraints::default(),
        state_machine: None,
    };
    vec![
        field("principal_id", false),
        // UNIQUE is load-bearing, not decoration: it is what makes the store's
        // `ON CONFLICT (endpoint) DO UPDATE` upsert atomic rather than a racy
        // select-then-insert, and what stops one browser accumulating a row
        // per page load.
        field("endpoint", true),
        field("p256dh", false),
        field("auth", false),
    ]
}

/// Build the `push_subscriptions` `up.sql` for the target `backend`.
///
/// The shared helper's stock `created_at` is `TIMESTAMP`; the Postgres output
/// rewrites that one column to `TIMESTAMPTZ` to stay in lockstep with the
/// framework store's `Timestamptz` mapping — the same adjustment the
/// notifications generator makes, for the same reason. The `SQLite` output
/// already matches and is left exactly as the helper emits it.
fn push_subscriptions_up_sql(backend: DatabaseBackend) -> String {
    let indexes: BTreeSet<String> = std::iter::once("principal_id".to_owned()).collect();
    let sql = create_table_sql_with_metadata_and_id_for(
        backend,
        PUSH_SUBSCRIPTIONS_TABLE,
        &push_subscription_fields(),
        &indexes,
        &BTreeMap::new(),
        IdType::BigSerial,
    );
    match backend {
        DatabaseBackend::Postgres => sql.replace(
            "created_at TIMESTAMP NOT NULL DEFAULT NOW()",
            "created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()",
        ),
        DatabaseBackend::Sqlite => sql,
    }
}

fn render_manifest() -> String {
    concat!(
        "{\n",
        "  \"name\": \"My App\",\n",
        "  \"short_name\": \"My App\",\n",
        "  \"description\": \"Built with Autumn\",\n",
        "  \"start_url\": \"/\",\n",
        "  \"display\": \"standalone\",\n",
        "  \"background_color\": \"#ffffff\",\n",
        "  \"theme_color\": \"#ffffff\",\n",
        "  \"icons\": [\n",
        "    {\n",
        "      \"src\": \"/static/icons/icon.svg\",\n",
        "      \"sizes\": \"any\",\n",
        "      \"type\": \"image/svg+xml\",\n",
        "      \"purpose\": \"any\"\n",
        "    },\n",
        "    {\n",
        "      \"src\": \"/static/icons/maskable-icon.svg\",\n",
        "      \"sizes\": \"any\",\n",
        "      \"type\": \"image/svg+xml\",\n",
        "      \"purpose\": \"maskable\"\n",
        "    }\n",
        "  ]\n",
        "}\n",
    )
    .to_owned()
}

fn render_service_worker() -> String {
    r"const CACHE_NAME = 'autumn-pwa-v1';
const OFFLINE_URL = '/offline';
const PRECACHE_URLS = [OFFLINE_URL];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => cache.addAll(PRECACHE_URLS))
      .then(() => self.skipWaiting())
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys()
      .then((names) => Promise.all(
        names.filter((n) => n !== CACHE_NAME).map((n) => caches.delete(n))
      ))
      .then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') {
    return;
  }
  if (event.request.mode === 'navigate') {
    event.respondWith(
      fetch(event.request).catch(() =>
        caches.match(OFFLINE_URL).then((r) => r || new Response('Offline', { status: 503 }))
      )
    );
    return;
  }
  if (event.request.url.includes('/static/')) {
    event.respondWith(
      caches.match(event.request).then((cached) => {
        if (cached) return cached;
        return fetch(event.request).then((response) => {
          if (response.ok) {
            const copy = response.clone();
            caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
          }
          return response;
        });
      })
    );
  }
});

// ── Web Push ────────────────────────────────────────────────────────────────
// Fired by the browser even when every tab of this site is closed. The payload
// is what `autumn_web::push::PushMessage` serializes: {title, body, url?, icon?}.

self.addEventListener('push', (event) => {
  // A push can legitimately arrive with no payload, and a payload from any
  // other sender need not be JSON. Throwing here makes the browser show a
  // generic 'site updated in the background' notice instead, so always fall
  // back to something readable.
  let payload = {};
  if (event.data) {
    try {
      payload = event.data.json();
    } catch (e) {
      payload = { body: event.data.text() };
    }
  }
  const title = payload.title || 'Notification';
  const options = {
    body: payload.body || '',
    icon: payload.icon || '/static/icons/icon.svg',
    // Carried through to `notificationclick` below.
    data: { url: payload.url || '/' },
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const target = new URL(
    (event.notification.data && event.notification.data.url) || '/',
    self.location.origin
  );
  // Cross-origin targets are dropped: the payload travels through a third-party
  // push service, so a notification must never be able to navigate this app's
  // users off-origin.
  const url = target.origin === self.location.origin ? target.href : self.location.origin + '/';
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windows) => {
      // Prefer focusing a tab that is already on the target rather than
      // opening a duplicate one.
      for (const client of windows) {
        if (client.url === url && 'focus' in client) {
          return client.focus();
        }
      }
      if (windows.length > 0 && 'navigate' in windows[0] && 'focus' in windows[0]) {
        // `navigate()` REJECTS for a client this service worker does not
        // control — and `includeUncontrolled: true` above is exactly how such
        // clients get into this list. An unhandled rejection inside
        // `waitUntil` means the click does nothing at all, so fall back.
        return windows[0]
          .navigate(url)
          .then((client) => (client ? client.focus() : undefined))
          .catch(() => self.clients.openWindow(url));
      }
      return self.clients.openWindow(url);
    })
  );
});
"
    .to_owned()
}

fn render_icon_svg() -> String {
    // Note: using concat! to avoid raw-string issues with #ffffff and system-ui
    concat!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 192 192\">\n",
        "  <!-- Replace this placeholder with your app icon (PNG recommended for broad compatibility) -->\n",
        "  <rect width=\"192\" height=\"192\" rx=\"24\" fill=\"#4F7942\"/>\n",
        "  <text x=\"96\" y=\"140\" font-size=\"110\" text-anchor=\"middle\" font-family=\"system-ui\">&#x1F342;</text>\n",
        "</svg>\n",
    )
    .to_owned()
}

fn render_maskable_icon_svg() -> String {
    concat!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 192 192\">\n",
        "  <!-- Maskable icon: keep important content within the inner 116x116 safe zone -->\n",
        "  <!-- Replace this placeholder with your app icon (PNG recommended for broad compatibility) -->\n",
        "  <rect width=\"192\" height=\"192\" fill=\"#4F7942\"/>\n",
        "  <text x=\"96\" y=\"124\" font-size=\"72\" text-anchor=\"middle\" font-family=\"system-ui\">&#x1F342;</text>\n",
        "</svg>\n",
    )
    .to_owned()
}

/// The `static/pwa-register.js` the generator emits.
///
/// Served as a same-origin script to avoid CSP `script-src 'self'` blocking
/// inline scripts that the default `SecurityHeadersLayer` enforces.
///
/// Two halves, split across two functions so each stays readable: unconditional
/// service-worker registration, and the Web Push opt-in (issue #1392).
fn render_pwa_register_js() -> String {
    format!(
        "{}\n{}",
        render_service_worker_registration(),
        render_push_opt_in()
    )
}

/// The service-worker registration half of `pwa-register.js`.
///
/// Sets `data-sw-registered="true"` on `<html>` once registration resolves;
/// the generated system test polls for that attribute.
fn render_service_worker_registration() -> String {
    r"if ('serviceWorker' in navigator) {
  navigator.serviceWorker
    .register('/service-worker.js', { scope: '/' })
    .then(() => { document.documentElement.dataset.swRegistered = 'true'; })
    .catch(console.error);
}
"
    .to_owned()
}

/// The Web Push opt-in half of `pwa-register.js` (issue #1392).
///
/// Deliberately NOT run on load: a permission prompt fired without a user
/// gesture is the fastest way to get permanently blocked, and both Chrome and
/// Firefox penalise it. The subscribe flow is exposed as
/// `window.autumnPushSubscribe()` and wired to any element carrying
/// `data-autumn-push-subscribe`, so an app gets an opt-in button with no
/// JavaScript of its own:
///
/// ```html
/// <button data-autumn-push-subscribe>Enable notifications</button>
/// ```
///
/// Every path and header name below comes from `autumn_web::push::router`'s own
/// constants, so the snippet and the mounted routes can never drift apart.
fn render_push_opt_in() -> String {
    format!("{}{}", render_push_helpers(), render_push_entry_points())
}

/// The shared helpers the push entry points below build on: CSRF header
/// assembly, the base64url→`Uint8Array` key decode, the rotated-key check, and
/// the CSRF capture.
fn render_push_helpers() -> String {
    format!(
        r"// Autumn's CSRF layer rejects an unaccompanied mutating request, so both POSTs
// below must carry a token. Without one they 403 the moment
// `[security.csrf] enabled = true` — which the production smart defaults do —
// and the tempting workaround (exempting `/push/`) would be far worse than the
// bug it hides: a forced subscribe would register an ATTACKER's keys under the
// victim's session, letting them decrypt every notification sent to that user.
//
// The CSRF cookie is HttpOnly, so this cannot read it. Two sources, in order:
// the public-key response (which the subscribe flow fetches anyway, and which
// carries the token for exactly this purpose), then `<meta name=csrf-token>`
// for an app that already publishes it the way `autumn generate auth` does.
let autumnPushCsrf = null;

function autumnPushHeaders() {{
  const headers = {{ 'content-type': 'application/json' }};
  if (autumnPushCsrf && autumnPushCsrf.token) {{
    headers[autumnPushCsrf.header || 'X-CSRF-Token'] = autumnPushCsrf.token;
    return headers;
  }}
  // Unquoted attribute values (both are valid CSS identifiers) so this stays
  // inside a Rust raw string that cannot contain a double quote.
  const token = document.querySelector('meta[name=csrf-token]');
  if (token && token.content) {{
    const header = document.querySelector('meta[name=csrf-token-header]');
    headers[(header && header.content) || 'X-CSRF-Token'] = token.content;
  }}
  return headers;
}}

// Whether an existing subscription was created with `key`.
//
// `options.applicationServerKey` is the ArrayBuffer the browser recorded at
// subscribe time; comparing bytes is the only way to notice a server-side key
// rotation before `subscribe()` throws over it.
function autumnPushKeyMatches(subscription, key) {{
  const recorded = subscription.options && subscription.options.applicationServerKey;
  if (!recorded) {{
    // The browser does not expose it (older Safari): assume it still matches
    // rather than churning a working subscription on every page load.
    return true;
  }}
  const bytes = new Uint8Array(recorded);
  if (bytes.length !== key.length) {{
    return false;
  }}
  for (let i = 0; i < bytes.length; i += 1) {{
    if (bytes[i] !== key[i]) {{
      return false;
    }}
  }}
  return true;
}}

// Read the CSRF token off a public-key response. Same-origin only: a
// cross-origin reader cannot see these headers without the app opting in via
// CORS, which is the property double-submit CSRF already depends on.
function autumnPushCaptureCsrf(response) {{
  const token = response.headers.get('{csrf_token_header}');
  if (token) {{
    autumnPushCsrf = {{
      token: token,
      header: response.headers.get('{csrf_header_name_header}'),
    }};
  }}
}}

// `applicationServerKey` takes a BufferSource, not the base64url string the
// endpoint serves, and `atob` only understands standard base64 — so translate
// base64url's `-` and `_` back to `+` and `/` and re-pad before decoding.
function autumnDecodeVapidKey(base64url) {{
  const padding = '='.repeat((4 - (base64url.length % 4)) % 4);
  const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
  const raw = atob(base64);
  const bytes = new Uint8Array(raw.length);
  for (let i = 0; i < raw.length; i += 1) {{
    bytes[i] = raw.charCodeAt(i);
  }}
  return bytes;
}}

",
        csrf_token_header = autumn_web::push::CSRF_TOKEN_HEADER,
        csrf_header_name_header = autumn_web::push::CSRF_TOKEN_HEADER_NAME_HEADER,
    )
}

/// `window.autumnPushSubscribe` / `window.autumnPushUnsubscribe`, plus the
/// declarative `data-autumn-push-subscribe` wiring.
fn render_push_entry_points() -> String {
    format!("{}{}", render_push_subscribe(), render_push_teardown())
}

/// `window.autumnPushSubscribe` — the opt-in half.
fn render_push_subscribe() -> String {
    format!(
        r"// Opt the current visitor in to Web Push. Call it from a click handler — it
// prompts for notification permission, so it needs a user gesture.
// Resolves `true` once the subscription has been recorded server-side.
window.autumnPushSubscribe = async function autumnPushSubscribe() {{
  // Safari on older iOS has service workers but no Push API at all.
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {{
    return false;
  }}
  if ((await Notification.requestPermission()) !== 'granted') {{
    return false;
  }}
  const response = await fetch('{key_path}', {{ credentials: 'same-origin' }});
  if (!response.ok) {{
    // 503 means the app has not configured `[push] private_key` yet.
    console.error('web push is not configured on this server');
    return false;
  }}
  autumnPushCaptureCsrf(response);
  const registration = await navigator.serviceWorker.ready;
  const applicationServerKey = autumnDecodeVapidKey((await response.text()).trim());

  // A browser keeps its subscription across deployments. If this deployment
  // rotated `[push] private_key`, that stored subscription was created with
  // the OLD applicationServerKey, and `subscribe()` then REJECTS rather than
  // replacing it — leaving the user unable to opt back in through the button
  // without manually clearing site data. Drop a subscription whose key no
  // longer matches and subscribe afresh.
  const existing = await registration.pushManager.getSubscription();
  if (existing && !autumnPushKeyMatches(existing, applicationServerKey)) {{
    await fetch('{unsubscribe_path}', {{
      method: 'POST',
      headers: autumnPushHeaders(),
      credentials: 'same-origin',
      body: JSON.stringify({{ endpoint: existing.endpoint }}),
    }}).catch(() => {{}});
    await existing.unsubscribe();
  }}

  const subscription = await registration.pushManager.subscribe({{
    // Chrome refuses a subscription without this, and it is also the honest
    // contract: every push this app sends raises a visible notification.
    userVisibleOnly: true,
    applicationServerKey,
  }});
  const recorded = await fetch('{subscribe_path}', {{
    method: 'POST',
    headers: autumnPushHeaders(),
    // Send the session cookie so the server knows whose subscription this is.
    credentials: 'same-origin',
    body: JSON.stringify(subscription),
  }});
  return recorded.ok;
}};

// Undo the above: forget this browser's subscription, server-side and locally.
// Drop this browser's subscription SERVER-SIDE, leaving the browser's own
// subscription intact.
//
// This is what sign-out wants, and revoking the browser subscription there
// would be actively wrong: an origin has ONE `PushSubscription` shared by
// every tab, so with two accounts open the row belongs to whichever signed in
// last. A stale tab signing out gets a `204` from the scoped delete whether or
// not it owned the row — the route is deliberately indistinguishable, so it
// cannot be used to probe who owns an endpoint — and revoking on the strength
// of that `204` would invalidate the OTHER account's endpoint. Its next push
// would `410`, be pruned, and that account would silently stop receiving
// notifications until it opted in again.
window.autumnPushForget = async function autumnPushForget() {{
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {{
    return false;
  }}
  const registration = await navigator.serviceWorker.ready;
  const subscription = await registration.pushManager.getSubscription();
  if (!subscription) {{
    return true;
  }}
  // This can be the first call of the page, before anything primed the token;
  // one cheap GET is enough to obtain it.
  if (!autumnPushCsrf) {{
    autumnPushCaptureCsrf(
      await fetch('{key_path}', {{ credentials: 'same-origin' }})
    );
  }}
  const response = await fetch('{unsubscribe_path}', {{
    method: 'POST',
    headers: autumnPushHeaders(),
    credentials: 'same-origin',
    body: JSON.stringify({{ endpoint: subscription.endpoint }}),
  }});
  return response.ok;
}};

",
        key_path = autumn_web::push::VAPID_PUBLIC_KEY_PATH,
        subscribe_path = autumn_web::push::SUBSCRIBE_PATH,
        unsubscribe_path = autumn_web::push::UNSUBSCRIBE_PATH,
    )
}

/// `window.autumnPushForget` / `window.autumnPushUnsubscribe`, the sign-out
/// hook, and the declarative `data-autumn-push-subscribe` wiring.
fn render_push_teardown() -> String {
    format!(
        r"// Fully opt this browser out: forget the row server-side AND revoke the
// browser's subscription.
//
// Revoking is correct HERE and only here — the visitor is explicitly asking to
// stop receiving on this device, so taking the shared subscription down with
// them is the intent, not a side effect.
window.autumnPushUnsubscribe = async function autumnPushUnsubscribe() {{
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {{
    return false;
  }}
  await window.autumnPushForget();
  const registration = await navigator.serviceWorker.ready;
  const subscription = await registration.pushManager.getSubscription();
  return subscription ? subscription.unsubscribe() : true;
}};

// Unsubscribe on the way out of a session.
//
// A subscription outliving the session that created it is a privacy leak, not
// just untidiness: the row stays bound to the user who logged out, so the app
// keeps pushing their notifications to that browser — in front of whoever uses
// the device next. Nothing in a logout flow knows about push, so this hooks
// the submit instead, while the session is still valid enough for the
// server-side unsubscribe to authorize.
//
// Matches any form posting to `/logout` (what `autumn generate auth` emits) and
// anything explicitly marked `data-autumn-push-unsubscribe`, for an app whose
// sign-out is shaped differently.
document.addEventListener('submit', (event) => {{
  const form = event.target;
  if (!(form instanceof HTMLFormElement) || form.dataset.autumnPushHandled) {{
    return;
  }}
  const action = form.getAttribute('action') || '';
  const isSignOut =
    form.hasAttribute('data-autumn-push-unsubscribe') || /\/logout\/?$/.test(action);
  if (!isSignOut) {{
    return;
  }}
  event.preventDefault();
  // Re-entrancy guard: `form.submit()` below does not re-fire this handler in
  // any current browser, but the flag makes that independent of that detail.
  form.dataset.autumnPushHandled = 'true';
  // Raced against a deadline — `catch` alone is not enough here.
  //
  // `autumnPushUnsubscribe` awaits `navigator.serviceWorker.ready`, which by
  // specification NEVER REJECTS: it stays pending until a worker becomes
  // active. So if the service worker fails to install, a bare
  // `.catch().finally()` never runs — and since this handler has already
  // called `preventDefault()`, the user cannot log out at all. Blocking a
  // sign-out is far worse than leaving a subscription behind, which the push
  // service prunes with a `410` soon enough anyway.
  // `autumnPushForget`, NOT `autumnPushUnsubscribe`: see that function's
  // comment — revoking the shared browser subscription on sign-out would take
  // another still-signed-in account's notifications down with it.
  const cleanup = window.autumnPushForget().catch(console.error);
  const deadline = new Promise((resolve) => setTimeout(resolve, {LOGOUT_UNSUBSCRIBE_TIMEOUT_MS}));
  Promise.race([cleanup, deadline]).then(() => form.submit());
}});

// Declarative opt-in: no application JavaScript required.
document.addEventListener('click', (event) => {{
  // A synthetic `document.dispatchEvent(new MouseEvent('click'))` — the common
  // close-the-open-dropdown idiom — has `document` as its target, which has no
  // `closest`. Guard rather than throw on every such click.
  if (!(event.target instanceof Element)) {{
    return;
  }}
  const trigger = event.target.closest('[data-autumn-push-subscribe]');
  if (trigger) {{
    event.preventDefault();
    window.autumnPushSubscribe().catch(console.error);
  }}
}});",
    )
}

fn render_pwa_system_test() -> String {
    let manifest_selector = r#"link[rel="manifest"]"#;
    // Handler stubs are defined inline so this integration test crate compiles without
    // depending on src/main.rs.  The real handlers (with include_str! paths and the app's
    // layout helper) are injected there by `inject_pwa_into_main`.
    let stubs = concat!(
        "#[get(\"/manifest.webmanifest\")]\n",
        "async fn pwa_manifest() -> impl IntoResponse {\n",
        "    ([(\"content-type\", \"application/manifest+json\")], \"\")\n",
        "}\n",
        "\n",
        "#[get(\"/service-worker.js\")]\n",
        "async fn pwa_service_worker() -> impl IntoResponse {\n",
        "    (\n",
        "        [\n",
        "            (\"content-type\", \"text/javascript; charset=utf-8\"),\n",
        "            (\"service-worker-allowed\", \"/\"),\n",
        "        ],\n",
        "        \"\",\n",
        "    )\n",
        "}\n",
        "\n",
        "#[get(\"/pwa-register.js\")]\n",
        "async fn pwa_register_js() -> impl IntoResponse {\n",
        "    ([(\"content-type\", \"text/javascript; charset=utf-8\")], \"\")\n",
        "}\n",
        "\n",
        "#[get(\"/offline\")]\n",
        "async fn pwa_offline() -> impl IntoResponse {\n",
        "    autumn_web::reexports::axum::response::Html(\n",
        "        \"<html><head><link rel=\\\"manifest\\\" href=\\\"/manifest.webmanifest\\\"></head><body></body></html>\",\n",
        "    )\n",
        "}\n",
        "\n",
    );
    format!(
        "//! PWA smoke test \u{2014} manifest content-type + service-worker registration.\n\
         //!\n\
         //! Run with:\n\
         //!   cargo test --features system-tests --test pwa_smoke -- --include-ignored\n\
         \n\
         #![cfg(feature = \"system-tests\")]\n\
         \n\
         use autumn_web::prelude::*;\n\
         use autumn_web::system_test::SystemTest;\n\
         \n\
         {stubs}\
         /// Checks that `GET /manifest.webmanifest` returns `application/manifest+json`\n\
         /// and that the `<link rel=\"manifest\">` tag is present in the page DOM.\n\
         #[tokio::test]\n\
         #[ignore = \"requires Chromium; run with --include-ignored\"]\n\
         async fn pwa_manifest_loads_with_correct_content_type() {{\n\
             let runner = SystemTest::new()\n\
                 .routes(routes![pwa_manifest, pwa_service_worker, pwa_register_js, pwa_offline])\n\
                 .build()\n\
                 .await\n\
                 .expect(\"test runner\");\n\
             let base_url = runner.base_url();\n\
             let page = runner.page().await.expect(\"page\");\n\
             \n\
             // Verify HTTP content-type via raw TCP to avoid a reqwest dev-dependency.\n\
             {{\n\
                 use std::io::{{Read, Write}};\n\
                 let host_port = base_url\n\
                     .trim_start_matches(\"http://\")\n\
                     .trim_start_matches(\"https://\");\n\
                 let mut stream = std::net::TcpStream::connect(host_port)\n\
                     .expect(\"connect to test server\");\n\
                 let req = format!(\"GET /manifest.webmanifest HTTP/1.1\\r\\nHost: {{host_port}}\\r\\nConnection: close\\r\\n\\r\\n\");\n\
                 stream.write_all(req.as_bytes()).expect(\"write request\");\n\
                 let mut response = String::new();\n\
                 stream.read_to_string(&mut response).expect(\"read response\");\n\
                 assert!(\n\
                     response.starts_with(\"HTTP/1.1 200\") || response.starts_with(\"HTTP/1.0 200\"),\n\
                     \"manifest must return 200, got: {{response}}\"\n\
                 );\n\
                 assert!(\n\
                     response.contains(\"application/manifest+json\"),\n\
                     \"manifest content-type must be application/manifest+json\"\n\
                 );\n\
             }}\n\
             \n\
             // Browser check: <link rel=\"manifest\"> is in <head>\n\
             page.visit(\"/offline\").await.expect(\"offline page loaded\");\n\
             page.expect_attribute({manifest_selector:?}, \"href\", \"/manifest.webmanifest\")\n\
                 .await\n\
                 .expect(\"manifest link present in DOM\");\n\
         }}\n\
         \n\
         /// Verifies that the service worker registers successfully (scope covers the whole app).\n\
         /// The `/offline` page is used as the test shell since it is always available.\n\
         #[tokio::test]\n\
         #[ignore = \"requires Chromium; run with --include-ignored\"]\n\
         async fn service_worker_registers_successfully() {{\n\
             let runner = SystemTest::new()\n\
                 .routes(routes![pwa_manifest, pwa_service_worker, pwa_register_js, pwa_offline])\n\
                 .build()\n\
                 .await\n\
                 .expect(\"test runner\");\n\
             let page = runner.page().await.expect(\"page\");\n\
             \n\
             // `/pwa-register.js` sets `data-sw-registered=\"true\"` on `<html>`\n\
             // after the SW registers.  Visiting `/offline` (which uses layout)\n\
             // loads the script without needing the user's root route.\n\
             page.visit(\"/offline\").await.expect(\"offline page loaded\");\n\
             page.expect_attribute(\"html\", \"data-sw-registered\", \"true\")\n\
                 .await\n\
                 .expect(\"service worker registered and controlling page\");\n\
         }}\n"
    )
}

// ── src/main.rs patching ──────────────────────────────────────────────────────

/// Inject all PWA additions into `src/main.rs` in a single idempotent pass:
/// 1. Add PWA `<meta>` / `<link>` tags + external register script to the `head {}` block.
/// 2. Add `pwa_manifest`, `pwa_service_worker`, `pwa_register_js`, and `pwa_offline` handlers.
/// 3. Register those handlers in `routes![…]`.
pub fn inject_pwa_into_main(source: &str) -> String {
    let with_meta = inject_pwa_meta_into_head(source);
    let with_handlers = inject_pwa_handlers(&with_meta);
    let with_push_router = inject_push_router(&with_handlers);
    let route_entries = vec![
        "pwa_manifest".to_owned(),
        "pwa_service_worker".to_owned(),
        "pwa_register_js".to_owned(),
        "pwa_offline".to_owned(),
    ];
    update_main_rs(&with_push_router, &[], &route_entries)
}

/// The trailing marker on the mount line [`inject_push_router`] inserts.
///
/// Load-bearing for [`remove_push_router`]: destroy must remove only the line
/// *this generator* wrote. Without a marker it would also delete a mount the
/// developer had written themselves before ever running the generator — which
/// `Plan::revert` documents it never does.
const PUSH_ROUTER_MARKER: &str = "// added by `autumn generate pwa`";

/// How long the generated sign-out waits for the push unsubscribe before
/// submitting the form regardless.
///
/// `navigator.serviceWorker.ready` never rejects — it stays pending until a
/// worker activates — so a worker that failed to install would otherwise hang
/// the logout forever. Two seconds is generous for a local
/// `getSubscription()` plus one same-origin POST, and short enough that a user
/// who hits the broken case barely notices.
const LOGOUT_UNSUBSCRIBE_TIMEOUT_MS: u32 = 2_000;

/// The line [`inject_push_router`] inserts, and [`remove_push_router`] removes.
///
/// Mounting the framework's built-in push routes is what makes the generated
/// client snippet work: without it every `fetch` in `pwa-register.js` 404s.
const PUSH_ROUTER_LINE: &str =
    "        .merge(autumn_web::push::router()) // added by `autumn generate pwa`";

/// Mount `autumn_web::push::router()` on the app builder in `main()`.
///
/// Anchored on the `autumn_web::app()` line that every scaffolded `main.rs`
/// opens its builder chain with. Idempotent, and — like
/// [`inject_pwa_meta_into_head`] — a **no-op** when no usable anchor is found,
/// rather than a guess: an app whose `main.rs` has been restructured keeps
/// compiling and mounts the router itself with the one line the guide shows.
/// The caller reports that no-op as a warning; a silently unmounted router
/// would look like success and 404 on every call from the generated snippet.
///
/// # Anchor selection
///
/// Matching `autumn_web::app()` by text alone is not safe: this project's own
/// documentation (and `autumn_web::push::router`'s doc comment) shows a
/// quick-start snippet containing that exact line, so a `main.rs` that pasted
/// it into a comment would get the mount spliced **into the comment** —
/// producing a file that does not compile *and* a `main()` that never mounts
/// the router. So the scan walks lines with a byte cursor (never re-locating
/// by text, which could land on an earlier occurrence), skips anything inside
/// a comment, and only accepts an anchor at or after `async fn main`.
fn inject_push_router(source: &str) -> String {
    if push_router_already_mounted(source) {
        return source.to_owned();
    }
    let Some(anchor_end) = push_router_anchor(source) else {
        return source.to_owned();
    };
    let mut result = String::with_capacity(source.len() + PUSH_ROUTER_LINE.len() + 1);
    result.push_str(&source[..anchor_end]);
    result.push('\n');
    result.push_str(PUSH_ROUTER_LINE);
    result.push_str(&source[anchor_end..]);
    result
}

/// Whether `main.rs` already mounts the push router **in code**.
///
/// A plain substring test is not enough: this project's own documentation (and
/// `autumn_web::push::routes`' doc comment) shows a quick-start snippet
/// containing that exact call, so a `main.rs` that pasted it into a comment
/// would look mounted, skip injection, *and* skip the warning the caller emits
/// off this same predicate — leaving every generated `fetch` to 404 with
/// nothing pointing at the cause. So the scan ignores comments, exactly as
/// [`push_router_anchor`] does.
fn push_router_already_mounted(source: &str) -> bool {
    crate::rust_source::for_each_code_line(source, |line, _offset| {
        line.contains("autumn_web::push::router()").then_some(())
    })
    .is_some()
}

/// Byte offset just past the builder-opening `autumn_web::app()` inside
/// `main()`, or `None` when there is no unambiguous anchor.
///
/// See [`inject_push_router`]'s "Anchor selection" for why each rule is here.
fn push_router_anchor(source: &str) -> Option<usize> {
    let mut seen_main = false;
    crate::rust_source::for_each_code_line(source, |line, offset| {
        if line.trim().contains("async fn main") {
            seen_main = true;
        }
        // Only a line that ENDS with the builder opener is an anchor: a
        // single-line chain (`autumn_web::app().routes(…).run().await;`) has
        // no place to insert a `.merge(…)` line, so it is deliberately left
        // alone and reported instead of being spliced mid-expression.
        (seen_main && line.trim_end().ends_with("autumn_web::app()"))
            .then(|| offset + line.trim_end().len())
    })
}

/// Inverse of [`inject_push_router`]: remove exactly the line it inserted.
///
/// Matched on the [`PUSH_ROUTER_MARKER`] this generator writes, so a mount the
/// developer added themselves is left untouched — `Plan::revert`'s contract is
/// that it never removes content the plan did not itself add. A no-op when the
/// marked line is absent (already destroyed, or hand-edited away).
fn remove_push_router(existing: &str) -> String {
    if !existing.contains(PUSH_ROUTER_MARKER) {
        return existing.to_owned();
    }
    let mut out = String::with_capacity(existing.len());
    for line in existing.split_inclusive('\n') {
        let trimmed = line.trim();
        if trimmed.contains("autumn_web::push::router()") && trimmed.ends_with(PUSH_ROUTER_MARKER) {
            continue;
        }
        out.push_str(line);
    }
    out
}

/// Insert PWA `<link>` / `<meta>` tags into the `head {}` block of the
/// `layout` function.  Idempotent — skipped if `rel="manifest"` is already
/// present.
fn inject_pwa_meta_into_head(source: &str) -> String {
    if source.contains("/pwa-register.js") {
        return source.to_owned();
    }

    let lines: Vec<&str> = source.lines().collect();

    // Find the first `head {` line (Maud DSL — no leading keyword).
    // Support both `head {` and `head{` (both are valid Maud syntax).
    let Some(head_idx) = lines.iter().position(|l| {
        let t = l.trim();
        t == "head {" || t == "head{"
    }) else {
        return source.to_owned();
    };

    let head_indent = indent_count(lines[head_idx]);

    // Find the closing `}` of the head block (first `}` at the same indent
    // level as `head {`, after `head {`).
    let Some(close_rel) = lines[head_idx + 1..]
        .iter()
        .position(|l| indent_count(l) == head_indent && l.trim() == "}")
    else {
        return source.to_owned();
    };
    let close_idx = head_idx + 1 + close_rel;

    let inner_indent = " ".repeat(head_indent + 4);
    // Use an external script to stay compliant with `script-src 'self'` CSP.
    // The script sets `data-sw-registered="true"` on `<html>` after registration;
    // the system test polls for that attribute.
    let meta_block = format!(
        "{inner_indent}link rel=\"manifest\" href=\"/manifest.webmanifest\";\n\
         {inner_indent}meta name=\"theme-color\" content=\"#ffffff\";\n\
         {inner_indent}link rel=\"apple-touch-icon\" href=\"/static/icons/icon.svg\";\n\
         {inner_indent}script src=\"/pwa-register.js\" {{}}\n"
    );

    let mut result = lines[..close_idx].join("\n");
    result.push('\n');
    result.push_str(&meta_block);
    result.push_str(lines[close_idx]);
    if close_idx + 1 < lines.len() {
        result.push('\n');
        result.push_str(&lines[close_idx + 1..].join("\n"));
    }
    if source.ends_with('\n') {
        result.push('\n');
    }
    result
}

/// True when `source` defines a `layout()` function with fewer than 4
/// parameters — the pre-`nav_bar` scaffold shape (`layout(title, flash,
/// content)`) rather than the current one (`layout(title, current_path,
/// flash, content)`). `pwa_offline`'s generated call assumes 4 positional
/// arguments, so this gates [`plan_pwa`] with an actionable error instead
/// of emitting code with the wrong arity.
///
/// Checks parameter *count*, not a specific name — Rust calls are
/// positional, so a caller who named their path parameter `path` or
/// `request_path` instead of `current_path` still compiles fine and must
/// not be rejected.
fn layout_missing_current_path(source: &str) -> bool {
    let Some(start) = source.find("fn layout(") else {
        return false;
    };
    let after_paren = &source[start + "fn layout(".len()..];
    let Some(params) = balanced_prefix(after_paren) else {
        return false;
    };
    count_params(params) < 4
}

/// Count comma-separated parameters in a (possibly multi-line, possibly
/// trailing-comma) parameter list — the trailing comma rustfmt always adds
/// when it wraps a signature onto separate lines doesn't itself count as an
/// extra parameter.
fn count_params(params: &str) -> usize {
    let trimmed = params.trim();
    if trimmed.is_empty() {
        return 0;
    }
    let commas = count_top_level_commas(trimmed);
    if trimmed.ends_with(',') {
        commas
    } else {
        commas + 1
    }
}

/// The prefix of `s` up to (not including) the `)` that closes the opening
/// paren implicit in the caller's position — tracks `(`/`[` nesting (e.g. a
/// closure-typed parameter like `Fn(i32) -> bool`) so an inner `)` doesn't
/// end the scan early. Returns `None` if unbalanced.
fn balanced_prefix(s: &str) -> Option<&str> {
    let mut depth = 0i32;
    for (i, c) in s.char_indices() {
        match c {
            '(' | '[' => depth += 1,
            ')' if depth == 0 => return Some(&s[..i]),
            ')' | ']' => depth -= 1,
            _ => {}
        }
    }
    None
}

/// Count commas in `s` that aren't nested inside `(...)`/`[...]` — a cheap
/// proxy for "how many parameters does this signature have" without a real
/// parser. Doesn't track `<...>` generic nesting, so a parameter type with a
/// top-level comma inside angle brackets (e.g. `HashMap<K, V>`) would
/// over-count — harmless here since over-counting only makes this check
/// *more* permissive, never a false rejection.
fn count_top_level_commas(s: &str) -> usize {
    let mut depth = 0i32;
    let mut count = 0;
    for c in s.chars() {
        match c {
            '(' | '[' => depth += 1,
            ')' | ']' => depth -= 1,
            ',' if depth == 0 => count += 1,
            _ => {}
        }
    }
    count
}

/// Append `pwa_manifest`, `pwa_service_worker`, `pwa_register_js`, and `pwa_offline`
/// handler functions just before `#[autumn_web::main]`.  Idempotent — skipped when
/// `pwa_manifest` is already defined.
const PWA_HANDLERS_BLOCK: &str = "\
#[get(\"/manifest.webmanifest\")]\n\
async fn pwa_manifest() -> impl IntoResponse {\n\
    (\n\
        [\n\
            (\"content-type\", \"application/manifest+json\"),\n\
            (\"cache-control\", \"public, max-age=3600\"),\n\
        ],\n\
        include_str!(\"../static/manifest.webmanifest\"),\n\
    )\n\
}\n\
\n\
#[get(\"/service-worker.js\")]\n\
async fn pwa_service_worker() -> impl IntoResponse {\n\
    (\n\
        [\n\
            (\"content-type\", \"text/javascript; charset=utf-8\"),\n\
            (\"service-worker-allowed\", \"/\"),\n\
            (\"cache-control\", \"no-cache\"),\n\
        ],\n\
        include_str!(\"../static/service-worker.js\"),\n\
    )\n\
}\n\
\n\
#[get(\"/pwa-register.js\")]\n\
async fn pwa_register_js() -> impl IntoResponse {\n\
    (\n\
        [\n\
            (\"content-type\", \"text/javascript; charset=utf-8\"),\n\
            (\"cache-control\", \"public, max-age=3600\"),\n\
        ],\n\
        include_str!(\"../static/pwa-register.js\"),\n\
    )\n\
}\n\
\n\
#[get(\"/offline\")]\n\
async fn pwa_offline(flash: Flash, path: CurrentPath) -> maud::Markup {\n\
    layout(\n\
        \"Offline\",\n\
        path.as_str(),\n\
        flash.render().await,\n\
        maud::html! {\n\
            h1 { \"You are offline\" }\n\
            p { \"Check your internet connection and try again.\" }\n\
        },\n\
    )\n\
}\n\
\n";

fn inject_pwa_handlers(source: &str) -> String {
    if source.contains("async fn pwa_manifest()") {
        return source.to_owned();
    }

    // Insert before the line that is exactly `#[autumn_web::main]` — a naive
    // substring search would also match the text inside a comment that merely
    // mentions the macro (e.g. `// routes are wired under #[autumn_web::main]`)
    // and slice the file mid-comment. Appends at end as fallback.
    find_main_attr_line_start(source).map_or_else(
        || {
            let mut result = source.to_owned();
            if !result.ends_with('\n') {
                result.push('\n');
            }
            result.push('\n');
            result.push_str(PWA_HANDLERS_BLOCK);
            result
        },
        |pos| {
            let mut result = String::with_capacity(source.len() + PWA_HANDLERS_BLOCK.len());
            result.push_str(&source[..pos]);
            result.push_str(PWA_HANDLERS_BLOCK);
            result.push_str(&source[pos..]);
            result
        },
    )
}

/// Byte offset of the start of the first line whose entire content (modulo
/// surrounding whitespace) is `#[autumn_web::main]`, or `None` when no such
/// line exists. Line-exact matching prevents false positives on comments
/// that mention the attribute.
fn find_main_attr_line_start(source: &str) -> Option<usize> {
    let mut offset = 0;
    for line in source.split_inclusive('\n') {
        if line.trim() == "#[autumn_web::main]" {
            return Some(offset);
        }
        offset += line.len();
    }
    None
}

fn indent_count(line: &str) -> usize {
    line.len() - line.trim_start().len()
}

/// Inverse of [`inject_pwa_into_main`] (`autumn destroy`, issue #1048).
///
/// Removes the PWA `<link>`/`<meta>` tags from the `head {}` block and the
/// `pwa_manifest`/`pwa_service_worker`/`pwa_register_js`/`pwa_offline`
/// handler functions this generator injected. A no-op wherever its target
/// isn't present (already destroyed, or hand-edited away).
pub(super) fn remove_pwa_injection(existing: &str) -> String {
    let without_router = remove_push_router(existing);
    let without_handlers = remove_pwa_handlers(&without_router);
    remove_pwa_meta_from_head(&without_handlers)
}

/// Inverse of [`inject_pwa_meta_into_head`]. Removes exactly the four lines
/// that function inserts (three tag lines + the register-script line),
/// identified by the unique `/pwa-register.js` script line together with the
/// three lines immediately preceding it matching the known tag text
/// (ignoring indentation) — restoring the `head {}` block byte-identically.
///
/// A no-op if the script line isn't present, or the three preceding lines
/// don't match (hand-edited — never guesses at a partial match).
fn remove_pwa_meta_from_head(existing: &str) -> String {
    const SCRIPT_LINE: &str = "script src=\"/pwa-register.js\" {}";
    const PRECEDING_LINES: [&str; 3] = [
        "link rel=\"manifest\" href=\"/manifest.webmanifest\";",
        "meta name=\"theme-color\" content=\"#ffffff\";",
        "link rel=\"apple-touch-icon\" href=\"/static/icons/icon.svg\";",
    ];
    let lines: Vec<&str> = existing.lines().collect();
    let Some(script_idx) = lines.iter().position(|l| l.trim() == SCRIPT_LINE) else {
        return existing.to_owned();
    };
    if script_idx < PRECEDING_LINES.len() {
        return existing.to_owned();
    }
    let start = script_idx - PRECEDING_LINES.len();
    let matches = PRECEDING_LINES
        .iter()
        .enumerate()
        .all(|(offset, expected)| lines[start + offset].trim() == *expected);
    if !matches {
        return existing.to_owned();
    }
    let mut new_lines: Vec<&str> = Vec::with_capacity(lines.len());
    new_lines.extend_from_slice(&lines[..start]);
    new_lines.extend_from_slice(&lines[script_idx + 1..]);
    let mut out = new_lines.join("\n");
    if existing.ends_with('\n') {
        out.push('\n');
    }
    out
}

/// Inverse of [`inject_pwa_handlers`]. Removes the exact
/// [`PWA_HANDLERS_BLOCK`] text that function inserts verbatim.
///
/// A no-op if the block isn't present (already destroyed, or hand-edited
/// away).
fn remove_pwa_handlers(existing: &str) -> String {
    let Some(pos) = existing.find(PWA_HANDLERS_BLOCK) else {
        return existing.to_owned();
    };
    let mut out = String::with_capacity(existing.len() - PWA_HANDLERS_BLOCK.len());
    out.push_str(&existing[..pos]);
    out.push_str(&existing[pos + PWA_HANDLERS_BLOCK.len()..]);
    out
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    use tempfile::TempDir;

    use super::*;
    use crate::generate::Flags;

    // ── Fixtures ──────────────────────────────────────────────────────────────

    fn project_with_main(main_rs: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"my-app\"\nversion=\"0.1.0\"\nedition=\"2024\"\n\n[dependencies]\nautumn-web = \"0.6.0\"\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(tmp.path().join("src/main.rs"), main_rs).unwrap();
        tmp
    }

    const DEFAULT_MAIN: &str = "\
use autumn_web::form::skip_link;
use autumn_web::migrate::{EmbeddedMigrations, embed_migrations};
use autumn_web::prelude::*;

const MIGRATIONS: EmbeddedMigrations = embed_migrations!();

pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {
    let nav = NavBarConfig::new()
        .brand(\"My App\", \"/\")
        .aria_label(\"Main navigation\")
        .item(NavItem::link(\"/\", \"Home\"));
    maud::html! {
        (maud::DOCTYPE)
        html lang=\"en\" {
            head {
                meta charset=\"utf-8\";
                meta name=\"viewport\" content=\"width=device-width, initial-scale=1\";
                title { (title) }
                link rel=\"stylesheet\" href=(autumn_web::flash::FLASH_CSS_PATH);
                link rel=\"stylesheet\" href=\"/static/css/app.css\";
                script src=(autumn_web::htmx::AUTUMN_WIDGETS_JS_PATH) defer {}
            }
            body {
                (skip_link(\"#main-content\", \"Skip to main content\"))
                header role=\"banner\" {
                    (nav_bar(current_path, &nav))
                }
                main id=\"main-content\" role=\"main\" {
                    (flash)
                    (content)
                }
                footer role=\"contentinfo\" {
                    p { \"Built with Autumn\" }
                }
            }
        }
    }
}

#[get(\"/\")]
async fn index(flash: Flash, path: CurrentPath) -> maud::Markup {
    layout(\"Welcome\", path.as_str(), flash.render().await, maud::html! {
        h1 { \"Welcome!\" }
    })
}

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .migrations(MIGRATIONS)
        .run()
        .await;
}
";

    /// The pre-`nav_bar` scaffold shape: `layout()` has no `current_path`
    /// parameter. Apps generated before `nav_bar` shipped still look like this.
    const OLD_SHAPE_MAIN: &str = "\
use autumn_web::form::skip_link;
use autumn_web::migrate::{EmbeddedMigrations, embed_migrations};
use autumn_web::prelude::*;

const MIGRATIONS: EmbeddedMigrations = embed_migrations!();

pub fn layout(title: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {
    maud::html! {
        (maud::DOCTYPE)
        html lang=\"en\" {
            head {
                meta charset=\"utf-8\";
                title { (title) }
            }
            body {
                (skip_link(\"#main-content\", \"Skip to main content\"))
                main id=\"main-content\" role=\"main\" {
                    (flash)
                    (content)
                }
            }
        }
    }
}

#[get(\"/\")]
async fn index(flash: Flash) -> maud::Markup {
    layout(\"Welcome\", flash.render().await, maud::html! {
        h1 { \"Welcome!\" }
    })
}

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .migrations(MIGRATIONS)
        .run()
        .await;
}
";

    // ── plan_pwa: file plan tests ─────────────────────────────────────────────

    #[test]
    fn plan_pwa_rejects_layout_missing_current_path() {
        // nav_bar's arrival made layout() take current_path as its second
        // argument; pwa_offline's generated call now assumes that shape.
        // Running against an app that hasn't migrated must fail loudly with
        // an actionable message instead of silently emitting a call that
        // won't compile.
        let tmp = project_with_main(OLD_SHAPE_MAIN);
        let err = plan_pwa(tmp.path()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("current_path"), "{msg}");
        assert!(msg.contains("layout"), "{msg}");
    }

    #[test]
    fn plan_pwa_accepts_rustfmt_wrapped_layout_signature() {
        // rustfmt wraps layout()'s ~108-char signature onto separate lines
        // (verified: `rustfmt` puts each param on its own line at the
        // default 100-column width) — current_path then no longer shares a
        // physical line with `fn layout(`, so a naive single-line scan would
        // false-positive as "missing current_path" on any formatted,
        // up-to-date project.
        let wrapped_main = DEFAULT_MAIN.replace(
            "pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {",
            "pub fn layout(\n    title: &str,\n    current_path: &str,\n    flash: maud::Markup,\n    content: maud::Markup,\n) -> maud::Markup {",
        );
        assert_ne!(
            wrapped_main, DEFAULT_MAIN,
            "replacement must actually match"
        );
        let tmp = project_with_main(&wrapped_main);
        plan_pwa(tmp.path())
            .expect("rustfmt-wrapped current_path parameter must still be detected");
    }

    #[test]
    fn plan_pwa_accepts_layout_with_renamed_path_parameter() {
        // Rust calls are positional — a layout() with 4 parameters compiles
        // fine against pwa_offline's 4-arg call regardless of what the
        // second parameter is named. Requiring the literal name
        // "current_path" would reject valid, already-migrated apps that
        // simply chose a different name (e.g. `path`, `request_path`).
        let renamed_main = DEFAULT_MAIN.replace(
            "pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {",
            "pub fn layout(title: &str, request_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {",
        );
        assert_ne!(
            renamed_main, DEFAULT_MAIN,
            "replacement must actually match"
        );
        let tmp = project_with_main(&renamed_main);
        plan_pwa(tmp.path())
            .expect("a differently-named 4th parameter must still be accepted (arity, not name)");
    }

    #[test]
    fn plan_pwa_requires_project_root() {
        let tmp = TempDir::new().unwrap();
        let err = plan_pwa(tmp.path()).unwrap_err();
        assert!(matches!(err, GenerateError::NotInProject));
    }

    #[test]
    fn plan_creates_manifest_webmanifest() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("manifest.webmanifest")),
            "plan must include manifest.webmanifest"
        );
    }

    #[test]
    fn plan_creates_service_worker_js() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("service-worker.js")),
            "plan must include service-worker.js"
        );
    }

    #[test]
    fn plan_creates_pwa_register_js() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("pwa-register.js")),
            "plan must include pwa-register.js"
        );
    }

    #[test]
    fn plan_creates_icons() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        assert!(
            plan.actions.iter().any(|a| a.path().ends_with("icon.svg")),
            "plan must include icon.svg"
        );
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("maskable-icon.svg")),
            "plan must include maskable-icon.svg"
        );
    }

    #[test]
    fn plan_creates_system_test() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("pwa_smoke.rs")),
            "plan must include pwa_smoke.rs"
        );
    }

    // ── manifest content ──────────────────────────────────────────────────────

    #[test]
    fn manifest_is_valid_json() {
        let content = render_manifest();
        let parsed: serde_json::Value =
            serde_json::from_str(&content).expect("manifest.webmanifest must be valid JSON");
        assert!(parsed["name"].is_string(), "manifest must have a name");
        assert!(parsed["icons"].is_array(), "manifest must have icons array");
    }

    #[test]
    fn manifest_has_required_fields_for_installability() {
        let content = render_manifest();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(parsed["start_url"].is_string());
        assert!(
            ["fullscreen", "standalone", "minimal-ui"]
                .contains(&parsed["display"].as_str().unwrap_or(""))
        );
        let icons = parsed["icons"].as_array().unwrap();
        assert!(!icons.is_empty(), "at least one icon required");
    }

    #[test]
    fn manifest_has_both_icon_purposes() {
        let content = render_manifest();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let icons = parsed["icons"].as_array().unwrap();
        let purposes: Vec<&str> = icons.iter().filter_map(|i| i["purpose"].as_str()).collect();
        assert!(
            purposes
                .iter()
                .any(|p| p.contains("any") || p.contains("monochrome")),
            "must have a general-purpose icon"
        );
        assert!(
            purposes.iter().any(|p| p.contains("maskable")),
            "must have a maskable icon"
        );
    }

    // ── service worker content ────────────────────────────────────────────────

    #[test]
    fn service_worker_has_offline_fallback_for_navigation() {
        let sw = render_service_worker();
        assert!(
            sw.contains("navigate"),
            "SW must handle navigation requests"
        );
        assert!(sw.contains("offline"), "SW must have offline fallback");
    }

    #[test]
    fn service_worker_precaches_offline_url() {
        let sw = render_service_worker();
        assert!(
            sw.contains("PRECACHE_URLS"),
            "SW must declare precache list"
        );
        assert!(
            sw.contains("/offline"),
            "SW must precache the offline shell"
        );
    }

    #[test]
    fn service_worker_has_install_and_activate_handlers() {
        let sw = render_service_worker();
        assert!(sw.contains("install"), "SW must have install handler");
        assert!(sw.contains("activate"), "SW must have activate handler");
    }

    #[test]
    fn service_worker_caches_static_assets_first() {
        let sw = render_service_worker();
        assert!(sw.contains("/static/"), "SW must cache static assets");
    }

    // ── inject_pwa_meta_into_head ─────────────────────────────────────────────

    #[test]
    fn inject_adds_manifest_link() {
        let updated = inject_pwa_meta_into_head(DEFAULT_MAIN);
        assert!(
            updated.contains(r#"rel="manifest""#),
            "must add rel=manifest link"
        );
        assert!(
            updated.contains("/manifest.webmanifest"),
            "must reference /manifest.webmanifest"
        );
    }

    #[test]
    fn inject_adds_external_register_script() {
        let updated = inject_pwa_meta_into_head(DEFAULT_MAIN);
        assert!(
            updated.contains("src=\"/pwa-register.js\""),
            "must add external SW registration script (avoids CSP inline-script issues)"
        );
        assert!(
            !updated.contains("serviceWorker"),
            "must not embed inline serviceWorker JS"
        );
    }

    #[test]
    fn inject_adds_theme_color_meta() {
        let updated = inject_pwa_meta_into_head(DEFAULT_MAIN);
        assert!(
            updated.contains("theme-color"),
            "must add theme-color meta tag"
        );
    }

    #[test]
    fn inject_adds_apple_touch_icon() {
        let updated = inject_pwa_meta_into_head(DEFAULT_MAIN);
        assert!(
            updated.contains("apple-touch-icon"),
            "must add apple-touch-icon link"
        );
    }

    #[test]
    fn inject_meta_is_idempotent() {
        let once = inject_pwa_meta_into_head(DEFAULT_MAIN);
        let twice = inject_pwa_meta_into_head(&once);
        assert_eq!(once, twice, "inject_pwa_meta_into_head must be idempotent");
    }

    #[test]
    fn inject_meta_preserves_existing_content() {
        let updated = inject_pwa_meta_into_head(DEFAULT_MAIN);
        assert!(updated.contains(r#"meta charset="utf-8""#));
        assert!(updated.contains(r#"meta name="viewport""#));
        assert!(updated.contains(r#"link rel="stylesheet""#));
    }

    #[test]
    fn inject_meta_no_op_when_head_absent() {
        let src = "fn main() { println!(\"hello\"); }\n";
        let result = inject_pwa_meta_into_head(src);
        assert_eq!(result, src, "must be unchanged if no head {{}} block found");
    }

    // ── inject_pwa_handlers ───────────────────────────────────────────────────

    #[test]
    fn inject_handlers_adds_manifest_route() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        assert!(
            updated.contains("async fn pwa_manifest()"),
            "must add pwa_manifest handler"
        );
        assert!(
            updated.contains("application/manifest+json"),
            "pwa_manifest must set correct content-type"
        );
    }

    #[test]
    fn inject_handlers_adds_service_worker_route() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        assert!(
            updated.contains("async fn pwa_service_worker()"),
            "must add pwa_service_worker handler"
        );
        assert!(
            updated.contains("service-worker-allowed"),
            "service-worker handler must set Service-Worker-Allowed header"
        );
    }

    #[test]
    fn inject_handlers_adds_register_js_route() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        assert!(
            updated.contains("async fn pwa_register_js()"),
            "must add pwa_register_js handler"
        );
        assert!(
            updated.contains("include_str!(\"../static/pwa-register.js\")"),
            "pwa_register_js must embed file at compile time via include_str!"
        );
    }

    #[test]
    fn inject_handlers_adds_offline_route() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        assert!(
            updated.contains("async fn pwa_offline("),
            "must add pwa_offline handler"
        );
    }

    #[test]
    fn inject_handlers_is_idempotent() {
        let once = inject_pwa_handlers(DEFAULT_MAIN);
        let twice = inject_pwa_handlers(&once);
        assert_eq!(once, twice, "inject_pwa_handlers must be idempotent");
    }

    #[test]
    fn inject_handlers_places_before_main() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        let handler_pos = updated.find("async fn pwa_manifest()").unwrap();
        let main_pos = updated.find("#[autumn_web::main]").unwrap();
        assert!(
            handler_pos < main_pos,
            "PWA handlers must appear before #[autumn_web::main]"
        );
    }

    #[test]
    fn inject_handlers_ignores_main_attr_mentioned_in_comment() {
        // A comment that merely mentions `#[autumn_web::main]` must not be
        // treated as the insertion point — the naive substring search used to
        // slice the file mid-comment, leaving the handlers inside the comment
        // text and the file uncompilable.
        let source = "\
use autumn_web::prelude::*;

// Route handlers are registered under #[autumn_web::main] via routes![].
fn helper() {}

#[autumn_web::main]
async fn main() {
    autumn_web::app().routes(routes![]).run().await;
}
";
        let updated = inject_pwa_handlers(source);
        assert!(
            updated.contains(
                "// Route handlers are registered under #[autumn_web::main] via routes![]."
            ),
            "comment must be untouched: {updated}"
        );
        let handler_pos = updated.find("async fn pwa_manifest()").unwrap();
        let helper_pos = updated.find("fn helper()").unwrap();
        let real_main_pos = updated.find("\n#[autumn_web::main]\n").unwrap();
        assert!(
            helper_pos < handler_pos && handler_pos < real_main_pos,
            "handlers must be inserted immediately before the real attribute line: {updated}"
        );
    }

    #[test]
    fn inject_handlers_appends_when_only_comment_mentions_main_attr() {
        let source = "// see #[autumn_web::main]\nfn main() {}\n";
        let updated = inject_pwa_handlers(source);
        assert!(
            updated.starts_with("// see #[autumn_web::main]\nfn main() {}\n"),
            "original source must be untouched: {updated}"
        );
        assert!(
            updated.ends_with(PWA_HANDLERS_BLOCK),
            "handlers must be appended at end as fallback: {updated}"
        );
    }

    #[test]
    fn pwa_manifest_handler_uses_include_str() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        assert!(
            updated.contains("include_str!(\"../static/manifest.webmanifest\")"),
            "pwa_manifest must embed file at compile time via include_str!"
        );
    }

    #[test]
    fn pwa_service_worker_handler_uses_include_str() {
        let updated = inject_pwa_handlers(DEFAULT_MAIN);
        assert!(
            updated.contains("include_str!(\"../static/service-worker.js\")"),
            "pwa_service_worker must embed file at compile time via include_str!"
        );
    }

    // ── inject_pwa_into_main (combined) ──────────────────────────────────────

    #[test]
    fn full_inject_adds_routes_to_routes_macro() {
        let updated = inject_pwa_into_main(DEFAULT_MAIN);
        assert!(
            updated.contains("pwa_manifest"),
            "routes![] must include pwa_manifest"
        );
        assert!(
            updated.contains("pwa_service_worker"),
            "routes![] must include pwa_service_worker"
        );
        assert!(
            updated.contains("pwa_register_js"),
            "routes![] must include pwa_register_js"
        );
        assert!(
            updated.contains("pwa_offline"),
            "routes![] must include pwa_offline"
        );
    }

    #[test]
    fn full_inject_is_idempotent() {
        let once = inject_pwa_into_main(DEFAULT_MAIN);
        let twice = inject_pwa_into_main(&once);
        assert_eq!(once, twice, "inject_pwa_into_main must be idempotent");
    }

    #[test]
    fn full_inject_does_not_duplicate_manifest_link() {
        let once = inject_pwa_into_main(DEFAULT_MAIN);
        let twice = inject_pwa_into_main(&once);
        let count = twice.matches(r#"rel="manifest""#).count();
        assert_eq!(count, 1, "must not duplicate rel=manifest link");
    }

    #[test]
    fn full_inject_does_not_duplicate_pwa_routes() {
        let once = inject_pwa_into_main(DEFAULT_MAIN);
        let twice = inject_pwa_into_main(&once);
        let handler_count = twice.matches("async fn pwa_manifest()").count();
        assert_eq!(handler_count, 1, "must not duplicate pwa_manifest handler");
    }

    #[test]
    fn pwa_offline_handler_matches_current_layout_arity() {
        // The scaffold's layout() takes (title, current_path, flash, content) —
        // pwa_offline must extract CurrentPath and pass it through, or the
        // generated src/main.rs fails to compile with an arity mismatch.
        let updated = inject_pwa_into_main(DEFAULT_MAIN);
        assert!(
            updated.contains("async fn pwa_offline(flash: Flash, path: CurrentPath)"),
            "pwa_offline must extract CurrentPath alongside Flash: {updated}"
        );
        let offline_fn_start = updated
            .find("async fn pwa_offline")
            .expect("pwa_offline handler must be present");
        let offline_fn = &updated[offline_fn_start..offline_fn_start + 200];
        assert!(
            offline_fn.contains("\"Offline\"") && offline_fn.contains("path.as_str()"),
            "pwa_offline must pass path.as_str() as layout()'s second argument: {offline_fn}"
        );
    }

    // ── plan execution ────────────────────────────────────────────────────────

    #[test]
    fn plan_execute_creates_manifest_file() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let manifest_path = tmp.path().join("static/manifest.webmanifest");
        assert!(
            manifest_path.exists(),
            "static/manifest.webmanifest must exist"
        );
        let content = fs::read_to_string(&manifest_path).unwrap();
        let _: serde_json::Value = serde_json::from_str(&content)
            .expect("manifest.webmanifest must be valid JSON after execution");
    }

    #[test]
    fn plan_execute_creates_service_worker_file() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            tmp.path().join("static/service-worker.js").exists(),
            "static/service-worker.js must exist"
        );
    }

    #[test]
    fn plan_execute_creates_pwa_register_js_file() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            tmp.path().join("static/pwa-register.js").exists(),
            "static/pwa-register.js must exist"
        );
        let content = fs::read_to_string(tmp.path().join("static/pwa-register.js")).unwrap();
        assert!(
            content.contains("serviceWorker"),
            "pwa-register.js must contain SW registration code"
        );
    }

    #[test]
    fn plan_execute_creates_icon_files() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            tmp.path().join("static/icons/icon.svg").exists(),
            "static/icons/icon.svg must exist"
        );
        assert!(
            tmp.path().join("static/icons/maskable-icon.svg").exists(),
            "static/icons/maskable-icon.svg must exist"
        );
    }

    #[test]
    fn plan_execute_creates_system_test_file() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            tmp.path().join("tests/system/pwa_smoke.rs").exists(),
            "tests/system/pwa_smoke.rs must exist"
        );
    }

    #[test]
    fn plan_execute_updates_main_rs_with_pwa_meta_and_handlers() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let main_rs = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(main_rs.contains(r#"rel="manifest""#));
        assert!(main_rs.contains("src=\"/pwa-register.js\""));
        assert!(main_rs.contains("async fn pwa_manifest()"));
        assert!(main_rs.contains("async fn pwa_service_worker()"));
        assert!(main_rs.contains("async fn pwa_register_js()"));
        assert!(main_rs.contains("async fn pwa_offline("));
    }

    #[test]
    fn generate_then_destroy_pwa_round_trips_to_original_project_state() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let cargo_path = tmp.path().join("Cargo.toml");
        let main_path = tmp.path().join("src/main.rs");
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();

        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(tmp.path().join("static/manifest.webmanifest").exists());
        assert!(
            fs::read_to_string(&main_path)
                .unwrap()
                .contains("async fn pwa_manifest()")
        );
        assert!(
            fs::read_to_string(&cargo_path)
                .unwrap()
                .contains("system-tests")
        );

        plan_pwa(tmp.path())
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join("static/manifest.webmanifest").exists());
        assert!(!tmp.path().join("static").exists());
        assert!(!tmp.path().join("tests/system/pwa_smoke.rs").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
    }

    #[test]
    fn destroy_pwa_still_works_after_main_rs_reverted_to_pre_nav_bar_shape() {
        // issue #1048 PR review: `plan_pwa` (used to recompute the plan for
        // destroy too) rejects `main.rs` whenever `layout()` has fewer than
        // 4 parameters. That precondition only matters for a *fresh*
        // generate — but a common cleanup order (hand-revert `main.rs` to
        // the pre-`nav_bar` shape, or run a competing generator that
        // rewrites `layout()`) would otherwise strand every PWA file
        // because `destroy pwa` fails before `Plan::revert` ever runs.
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(tmp.path().join("static/manifest.webmanifest").exists());

        // Simulate main.rs having been rewritten to the old, incompatible
        // arity after PWA was generated (still contains the PWA injections,
        // just with layout() narrowed back down).
        let main_path = tmp.path().join("src/main.rs");
        let with_pwa = fs::read_to_string(&main_path).unwrap();
        let narrowed = with_pwa.replace(
            "pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {",
            "pub fn layout(title: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {",
        );
        assert_ne!(narrowed, with_pwa, "replacement must actually match");
        fs::write(&main_path, &narrowed).unwrap();
        assert!(plan_pwa(tmp.path()).is_err());

        plan_pwa_destroy_fallback(tmp.path())
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join("static/manifest.webmanifest").exists());
        assert!(!tmp.path().join("static").exists());
        assert!(!tmp.path().join("tests/system/pwa_smoke.rs").exists());
    }

    #[test]
    fn plan_execute_is_idempotent_with_force() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags {
                force: true,
                dry_run: false,
            })
            .unwrap();
        let main_rs = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert_eq!(
            main_rs.matches(r#"rel="manifest""#).count(),
            1,
            "re-running must not duplicate manifest link"
        );
        assert_eq!(
            main_rs.matches("async fn pwa_manifest()").count(),
            1,
            "re-running must not duplicate pwa_manifest handler"
        );
    }

    #[test]
    fn dry_run_writes_nothing() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let original_main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags {
                dry_run: true,
                force: false,
            })
            .unwrap();
        assert!(
            !tmp.path().join("static/manifest.webmanifest").exists(),
            "dry-run must not create manifest"
        );
        let after = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert_eq!(original_main, after, "dry-run must not modify main.rs");
    }

    // ── Web Push (issue #1392) ──────────────────────────────────────────────

    /// The text an emitted action would write.
    fn action_contents(action: &crate::generate::emit::Action) -> String {
        match action {
            crate::generate::emit::Action::Create { contents, .. }
            | crate::generate::emit::Action::Modify { contents, .. }
            | crate::generate::emit::Action::CreateIfAbsent { contents, .. } => contents.clone(),
            crate::generate::emit::Action::CreateBytes { bytes, .. } => {
                String::from_utf8_lossy(bytes).into_owned()
            }
        }
    }

    #[test]
    fn service_worker_has_a_push_handler() {
        let sw = render_service_worker();
        assert!(
            sw.contains("addEventListener('push'"),
            "without a `push` handler the browser shows nothing when the tab is closed — \
             the entire point of Web Push:\n{sw}"
        );
        assert!(
            sw.contains("showNotification"),
            "the push handler must actually raise a notification:\n{sw}"
        );
    }

    #[test]
    fn push_handler_reads_the_frameworks_json_payload() {
        let sw = render_service_worker();
        // The framework sends `{title, body, url?, icon?}` — the SW must read
        // those exact keys or every notification renders blank.
        for key in ["title", "body", "icon"] {
            assert!(
                sw.contains(key),
                "the push handler must read `{key}` from the payload:\n{sw}"
            );
        }
    }

    #[test]
    fn push_handler_survives_a_payload_that_is_not_json() {
        // A push with no payload (or a non-JSON one from another sender) must
        // still show *something* rather than throwing inside the SW, which
        // browsers surface as a generic "site updated in the background".
        let sw = render_service_worker();
        assert!(
            sw.contains("catch"),
            "the push handler must guard payload parsing:\n{sw}"
        );
    }

    #[test]
    fn service_worker_has_a_notificationclick_handler_that_focuses_or_opens() {
        let sw = render_service_worker();
        assert!(
            sw.contains("addEventListener('notificationclick'"),
            "clicking a notification must do something:\n{sw}"
        );
        assert!(
            sw.contains("clients.matchAll"),
            "clicking must FOCUS an already-open tab rather than always opening \
             a duplicate one:\n{sw}"
        );
        assert!(
            sw.contains("openWindow"),
            "…and open a new window when none is focusable:\n{sw}"
        );
        assert!(
            sw.contains("notification.close()"),
            "the notification must be dismissed on click:\n{sw}"
        );
    }

    #[test]
    fn client_snippet_subscribes_against_the_frameworks_public_key_endpoint() {
        let js = render_pwa_register_js();
        assert!(
            js.contains(autumn_web::push::VAPID_PUBLIC_KEY_PATH),
            "the snippet must fetch the key from the built-in endpoint so the two \
             can never drift:\n{js}"
        );
        assert!(
            js.contains(autumn_web::push::SUBSCRIBE_PATH),
            "the snippet must POST the subscription to the built-in endpoint:\n{js}"
        );
        assert!(
            js.contains("pushManager.subscribe"),
            "the snippet must actually subscribe:\n{js}"
        );
        assert!(
            js.contains("userVisibleOnly"),
            "Chrome refuses a subscription without `userVisibleOnly: true`:\n{js}"
        );
    }

    #[test]
    fn client_snippet_converts_the_key_to_the_uint8array_the_api_requires() {
        // `applicationServerKey` takes a BufferSource, not the base64url
        // string the endpoint serves; passing the string fails at runtime.
        let js = render_pwa_register_js();
        assert!(
            js.contains("Uint8Array"),
            "the base64url key must be decoded to a Uint8Array:\n{js}"
        );
        assert!(js.contains("atob"), "…via base64 decoding:\n{js}");
        assert!(
            js.contains("replace"),
            "…after translating base64url's -/_ back to +/ for atob:\n{js}"
        );
    }

    #[test]
    fn client_snippet_never_prompts_for_permission_on_page_load() {
        // A permission prompt fired on load is the single fastest way to get
        // permanently blocked, and Chrome/Firefox both penalise it. The
        // snippet must expose an explicit opt-in instead.
        //
        // The check has to be positional, not a substring test: `contains`
        // cannot tell a call INSIDE `autumnPushSubscribe` from one at top
        // level, which is exactly the failure being guarded against. So find
        // every `requestPermission` and require each to sit inside a function
        // body — i.e. on an indented line.
        let js = render_pwa_register_js();
        let prompts: Vec<&str> = js
            .lines()
            .filter(|line| line.contains("requestPermission"))
            .collect();
        assert!(
            !prompts.is_empty(),
            "the snippet must request permission somewhere:\n{js}"
        );
        for line in prompts {
            assert!(
                line.starts_with(' '),
                "`requestPermission` must be called inside the opt-in function, never at \
                 top level where it would run on page load:\n{line}"
            );
        }
        assert!(
            js.contains("window.autumnPushSubscribe = "),
            "the snippet must expose a callable opt-in entry point:\n{js}"
        );
        assert!(
            js.contains("data-autumn-push-subscribe"),
            "…and wire it to a declarative opt-in attribute so an app needs no JS \
             of its own:\n{js}"
        );
    }

    #[test]
    fn client_snippet_sends_a_csrf_token_with_both_push_posts() {
        // Autumn's production smart defaults turn CSRF on, and the CSRF cookie
        // is HttpOnly — so without this the generated subscribe/unsubscribe
        // POSTs 403 and push opt-in is unusable in exactly the environment it
        // is meant for.
        let js = render_push_opt_in();
        assert!(
            js.contains(autumn_web::push::CSRF_TOKEN_HEADER),
            "the snippet must read the token the public-key response serves:\n{js}"
        );
        assert!(
            js.contains(autumn_web::push::CSRF_TOKEN_HEADER_NAME_HEADER),
            "…and the configured header name to send it back in:\n{js}"
        );
        // Every POST must go through the helper that attaches it — a `fetch`
        // with a hand-written `content-type` header would silently skip it.
        // Counted, not fixed at a number: adding a POST later must not be able
        // to quietly ship one without a token.
        let posts = js.matches("method: 'POST'").count();
        assert!(
            posts >= 2,
            "expected at least the subscribe and unsubscribe POSTs:\n{js}"
        );
        assert_eq!(
            js.matches("headers: autumnPushHeaders()").count(),
            posts,
            "every push POST must attach the CSRF token:\n{js}"
        );
    }

    #[test]
    fn client_snippet_replaces_a_subscription_made_with_a_rotated_key() {
        // A browser keeps its subscription across deployments. After a
        // `[push] private_key` rotation `subscribe()` REJECTS rather than
        // replacing one made with the old applicationServerKey, so without
        // this the affected users cannot opt back in through the generated
        // button at all.
        let js = render_push_opt_in();
        assert!(
            js.contains("autumnPushKeyMatches"),
            "the snippet must compare the stored key against the current one:\n{js}"
        );
        assert!(
            js.contains("applicationServerKey"),
            "…by reading `options.applicationServerKey`:\n{js}"
        );
        assert!(
            js.contains("existing.unsubscribe()"),
            "…and drop the stale subscription before re-subscribing:\n{js}"
        );
        // The server-side row must go too, or it lingers until the push
        // service reports it gone.
        assert!(
            js.contains("existing.endpoint"),
            "…telling the server to forget the old endpoint as well:\n{js}"
        );
    }

    #[test]
    fn a_browser_that_hides_the_recorded_key_is_left_alone() {
        // Older Safari does not expose `options.applicationServerKey`.
        // Churning a working subscription on every page load would be worse
        // than the rotation case this guards.
        let js = render_push_opt_in();
        assert!(
            js.contains("return true;"),
            "an unavailable recorded key must be treated as matching:\n{js}"
        );
    }

    #[test]
    fn the_registration_half_stays_free_of_push_concerns() {
        // Registration must work on a build that never configures push.
        let js = render_service_worker_registration();
        assert!(js.contains("serviceWorker"), "{js}");
        assert!(
            !js.contains("pushManager") && !js.contains("autumnPush"),
            "service-worker registration must not depend on the push half:\n{js}"
        );
    }

    #[test]
    fn a_router_mount_inside_a_comment_does_not_count_as_mounted() {
        // This project's own docs show a quick-start snippet containing the
        // mount call, so a `main.rs` that pasted it into a comment would look
        // mounted, skip injection AND skip the warning — leaving every
        // generated `fetch` to 404 with nothing pointing at the cause.
        let commented = DEFAULT_MAIN.replace(
            "#[autumn_web::main]",
            "// Example from the guide:\n             //     .merge(autumn_web::push::router())\n             #[autumn_web::main]",
        );
        assert!(
            !push_router_already_mounted(&commented),
            "a commented-out mount must not count as mounted"
        );
        let injected = inject_pwa_into_main(&commented);
        assert!(
            push_router_already_mounted(&injected),
            "…so injection must still happen:\n{injected}"
        );
    }

    #[test]
    fn a_real_router_mount_does_count_as_mounted() {
        let injected = inject_pwa_into_main(DEFAULT_MAIN);
        assert!(push_router_already_mounted(&injected));
        assert_eq!(
            inject_pwa_into_main(&injected)
                .matches("autumn_web::push::router()")
                .count(),
            1,
            "and a second run must not add another"
        );
    }

    #[test]
    fn signing_out_forgets_the_row_without_revoking_a_shared_subscription() {
        // An origin has ONE `PushSubscription` shared by every tab. With two
        // accounts open, the row belongs to whichever signed in last, and the
        // scoped unsubscribe route returns `204` either way (deliberately, so
        // it cannot be used to probe who owns an endpoint). Revoking the
        // browser subscription on the strength of that `204` would invalidate
        // the OTHER account's endpoint — its next push `410`s, gets pruned,
        // and it silently stops receiving until it opts in again.
        let js = render_push_opt_in();
        assert!(
            js.contains("window.autumnPushForget = "),
            "sign-out needs a server-side-only path:\n{js}"
        );
        assert!(
            js.contains("window.autumnPushForget().catch"),
            "…and the sign-out hook must use it:\n{js}"
        );

        // The full opt-out keeps revoking — there the visitor is explicitly
        // asking to stop receiving on this device.
        let opt_out = js
            .split_once("window.autumnPushUnsubscribe = ")
            .expect("the full opt-out exists")
            .1;
        assert!(
            opt_out.contains("subscription.unsubscribe()"),
            "an explicit opt-out must still revoke the browser subscription:\n{opt_out}"
        );
        // And `autumnPushForget` must NOT revoke.
        let forget = js
            .split_once("window.autumnPushForget = ")
            .expect("forget exists")
            .1
            .split_once("window.autumnPushUnsubscribe = ")
            .expect("…and ends where the opt-out begins")
            .0;
        assert!(
            !forget.contains("unsubscribe()"),
            "the sign-out path must never revoke the shared subscription:\n{forget}"
        );
    }

    #[test]
    fn client_snippet_unsubscribes_when_the_user_signs_out() {
        // A subscription outliving its session is a privacy leak: the row
        // stays bound to the user who logged out, so the app keeps pushing
        // their notifications to that browser — in front of whoever uses the
        // device next.
        let js = render_push_opt_in();
        assert!(
            js.contains("addEventListener('submit'"),
            "sign-out must be hooked; nothing in a logout flow knows about push:\n{js}"
        );
        assert!(
            js.contains("/logout"),
            "…matching what `autumn generate auth` emits:\n{js}"
        );
        assert!(
            js.contains("data-autumn-push-unsubscribe"),
            "…plus an opt-in attribute for a differently-shaped sign-out:\n{js}"
        );
        assert!(
            js.contains("autumnPushForget()"),
            "…and it must actually drop the server-side row:\n{js}"
        );
    }

    #[test]
    fn a_stalled_unsubscribe_never_traps_the_user_in_their_session() {
        // The logout POST is preventDefault'd, so the form MUST submit
        // regardless of what the unsubscribe promise does.
        //
        // `.catch(…).finally(…)` looks sufficient and is not:
        // `autumnPushUnsubscribe` awaits `navigator.serviceWorker.ready`,
        // which by specification never rejects — it stays pending until a
        // worker activates. A worker that fails to install therefore leaves
        // `finally` unreached and the user unable to log out. Only a race
        // against a deadline actually secures the invariant this test names,
        // so that is what is asserted.
        let js = render_push_opt_in();
        assert!(
            js.contains("Promise.race("),
            "the submit must be raced against a deadline, not chained off a \
             promise that may never settle:\n{js}"
        );
        assert!(
            js.contains("setTimeout(resolve"),
            "…with an actual timer as the other racer:\n{js}"
        );
        assert!(
            js.contains(&format!("{LOGOUT_UNSUBSCRIBE_TIMEOUT_MS}")),
            "…bounded by the documented timeout:\n{js}"
        );
        assert!(
            js.contains("form.submit()"),
            "…and the form must actually be submitted:\n{js}"
        );
        assert!(
            js.contains("autumnPushHandled"),
            "…guarded against re-entering the handler:\n{js}"
        );
    }

    #[test]
    fn client_snippet_still_falls_back_to_the_csrf_meta_tag() {
        // An app that already publishes the token the way `autumn generate
        // auth` does must keep working.
        let js = render_pwa_register_js();
        assert!(
            js.contains("meta[name=csrf-token]"),
            "the meta-tag fallback must remain:\n{js}"
        );
    }

    #[test]
    fn client_snippet_sends_credentials_on_every_push_request() {
        // The server resolves the subscriber from the session; without the
        // cookie every call is an anonymous 401.
        //
        // Compared against the number of `fetch` calls rather than a fixed
        // count: every request the push half makes either authenticates or
        // reads a per-visitor token, so a new one without credentials is a bug
        // whatever the total happens to be.
        let js = render_push_opt_in();
        assert_eq!(
            js.matches("credentials: 'same-origin'").count(),
            js.matches("fetch(").count(),
            "every push request must carry the session cookie:\n{js}"
        );
    }

    #[test]
    fn client_snippet_skips_push_entirely_when_the_browser_lacks_support() {
        let js = render_pwa_register_js();
        assert!(
            js.contains("PushManager"),
            "the snippet must feature-detect before touching the Push API — Safari \
             on older iOS has service workers but no PushManager:\n{js}"
        );
    }

    #[test]
    fn plan_creates_the_push_subscriptions_migration() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        let up = plan
            .actions
            .iter()
            .find(|a| {
                a.path()
                    .to_string_lossy()
                    .contains("create_push_subscriptions")
                    && a.path().ends_with("up.sql")
            })
            .expect("the pwa generator must scaffold the push_subscriptions table");
        let sql = action_contents(up);
        assert!(sql.contains("CREATE TABLE"), "{sql}");
        for column in ["principal_id", "endpoint", "p256dh", "auth"] {
            assert!(
                sql.contains(column),
                "the DDL must match the framework store's columns; missing `{column}`:\n{sql}"
            );
        }
        assert!(
            sql.to_uppercase().contains("UNIQUE"),
            "`endpoint` must be UNIQUE — it is what makes the store's upsert atomic \
             rather than a racy select-then-insert:\n{sql}"
        );
    }

    /// Pins the generated Postgres DDL against the exact schema the framework
    /// store is tested on.
    ///
    /// The two live in different crates — `autumn-web`'s tests cannot depend
    /// on `autumn-cli` — so this assertion and the `CREATE_PUSH_SUBSCRIPTIONS_SQL`
    /// constant in `autumn/tests/integration/push_end_to_end.rs` are the only
    /// thing binding them. A column renamed, retyped, or dropped on either
    /// side fails here.
    #[test]
    fn generated_push_ddl_matches_the_ddl_the_framework_store_is_tested_against() {
        let sql = push_subscriptions_up_sql(DatabaseBackend::Postgres);

        for column in [
            "principal_id TEXT NOT NULL",
            "endpoint TEXT NOT NULL",
            "p256dh TEXT NOT NULL",
            "auth TEXT NOT NULL",
        ] {
            assert!(
                sql.contains(column),
                "the store's diesel `table!` expects `{column}`:\n{sql}"
            );
        }
        assert!(
            sql.contains("id BIGSERIAL PRIMARY KEY"),
            "the store selects `id` as BigInt:\n{sql}"
        );
        // The store maps `created_at` as `Timestamptz`. The shared helper emits
        // a plain `TIMESTAMP`, so this generator rewrites that one column — if
        // the helper's spacing ever changes, the rewrite silently no-ops and
        // this is what catches it.
        assert!(
            sql.contains("created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()"),
            "`created_at` must be TIMESTAMPTZ to match the store's mapping:\n{sql}"
        );
        assert!(
            !sql.contains("created_at TIMESTAMP NOT NULL"),
            "the TIMESTAMP → TIMESTAMPTZ rewrite did not apply:\n{sql}"
        );
    }

    #[test]
    fn push_migration_makes_endpoint_unique_specifically() {
        // `contains("UNIQUE")` alone would pass with the constraint on the
        // wrong column — and `endpoint` being unique is what makes the store's
        // `ON CONFLICT (endpoint) DO UPDATE` atomic rather than a racy
        // select-then-insert.
        let sql = push_subscriptions_up_sql(DatabaseBackend::Postgres);
        let unique_line = sql
            .lines()
            .find(|line| line.to_uppercase().contains("UNIQUE"))
            .unwrap_or_else(|| panic!("no UNIQUE constraint in:\n{sql}"));
        assert!(
            unique_line.contains("(endpoint)"),
            "UNIQUE must be on `endpoint`, not another column: {unique_line}"
        );
    }

    #[test]
    fn push_migration_indexes_principal_id_for_the_send_path() {
        // Every send does `WHERE principal_id = …`; without the index that is
        // a sequential scan of every subscription in the system.
        let sql = push_subscriptions_up_sql(DatabaseBackend::Postgres);
        assert!(
            sql.contains("(principal_id)"),
            "`principal_id` must be indexed:\n{sql}"
        );
    }

    #[test]
    fn push_migration_is_emitted_for_sqlite_too() {
        let sql = push_subscriptions_up_sql(DatabaseBackend::Sqlite);
        assert!(sql.contains("CREATE TABLE"), "{sql}");
        assert!(
            !sql.contains("BIGSERIAL"),
            "SQLite has no BIGSERIAL:\n{sql}"
        );
        assert!(
            !sql.contains("TIMESTAMPTZ"),
            "the SQLite lane stores RFC 3339 TEXT, matching TimestamptzSqlite:\n{sql}"
        );
    }

    #[test]
    fn push_migration_has_a_matching_down() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let plan = plan_pwa(tmp.path()).unwrap();
        let down = plan
            .actions
            .iter()
            .find(|a| {
                a.path()
                    .to_string_lossy()
                    .contains("create_push_subscriptions")
                    && a.path().ends_with("down.sql")
            })
            .expect("every migration needs a down");
        let sql = action_contents(down);
        assert!(sql.contains("DROP TABLE"), "{sql}");
    }

    #[test]
    fn re_running_reuses_the_existing_push_migration_directory() {
        // Two `*_create_push_subscriptions` directories would fail the next
        // `autumn migrate` on the duplicate table — the same singleton rule
        // the notifications generator follows.
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags {
                force: true,
                ..Flags::default()
            })
            .unwrap();

        let dirs: Vec<_> = fs::read_dir(tmp.path().join("migrations"))
            .unwrap()
            .filter_map(Result::ok)
            .filter(|e| {
                e.file_name()
                    .to_string_lossy()
                    .ends_with("_create_push_subscriptions")
            })
            .collect();
        assert_eq!(
            dirs.len(),
            1,
            "re-running must reuse the existing migration directory, not mint a second"
        );
    }

    #[test]
    fn inject_mounts_the_built_in_push_router() {
        let injected = inject_pwa_into_main(DEFAULT_MAIN);
        assert!(
            injected.contains("autumn_web::push::router()"),
            "without the router mounted the generated client snippet 404s on every \
             call:\n{injected}"
        );
    }

    #[test]
    fn inject_push_router_is_idempotent() {
        let once = inject_pwa_into_main(DEFAULT_MAIN);
        let twice = inject_pwa_into_main(&once);
        assert_eq!(once, twice);
        assert_eq!(
            twice.matches("autumn_web::push::router()").count(),
            1,
            "a second run must not mount the router twice:\n{twice}"
        );
    }

    #[test]
    fn generate_then_destroy_removes_the_push_router_mount_too() {
        let tmp = project_with_main(DEFAULT_MAIN);
        let main_path = tmp.path().join("src/main.rs");
        let original_main = fs::read_to_string(&main_path).unwrap();

        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            fs::read_to_string(&main_path)
                .unwrap()
                .contains("autumn_web::push::router()")
        );

        plan_pwa(tmp.path())
            .unwrap()
            .revert(Flags::default())
            .unwrap();
        assert_eq!(
            fs::read_to_string(&main_path).unwrap(),
            original_main,
            "destroy must restore main.rs byte-for-byte, router mount included"
        );
    }

    #[test]
    fn dry_run_writes_no_push_files() {
        let tmp = project_with_main(DEFAULT_MAIN);
        plan_pwa(tmp.path())
            .unwrap()
            .execute(Flags {
                dry_run: true,
                ..Flags::default()
            })
            .unwrap();
        assert!(
            !tmp.path().join("migrations").exists(),
            "--dry-run must write nothing"
        );
        assert!(
            !fs::read_to_string(tmp.path().join("src/main.rs"))
                .unwrap()
                .contains("autumn_web::push::router()")
        );
    }
}