waterui-cli 0.1.4

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

use std::{
    io,
    path::{Path, PathBuf},
};

use crate::build_info::{
    ANDROID_BACKEND, APPLE_BACKEND, DEW_VERSION, GTK_BACKEND_VERSION, HYDROLYSIS_M3_VERSION,
    HYDROLYSIS_VERSION, PREVIEW_PROTOCOL_VERSION, PREVIEW_VERSION, WATERUI_BROWSER_CEF_VERSION,
    WATERUI_CORE_VERSION, WATERUI_FFI_VERSION, WATERUI_VERSION,
};
use askama::Template;

use crate::project::ResolvedWebViewBackend;

use include_dir::{Dir, include_dir};
use smol::fs;

use crate::project_types::{BundleIdentifier, CrateName, RustIdent};

/// Normalize a path to use forward slashes for config files (Cargo.toml, Xcode projects, etc.)
/// This is necessary because Windows uses backslashes but these config files expect forward slashes.
fn normalize_path_for_config(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn cargo_semver(version: &str) -> cargo_toml::SemVer {
    version
        .parse()
        .unwrap_or_else(|error| panic!("Invalid Cargo semantic version `{version}`: {error}"))
}

fn cargo_version_req(version: &str) -> cargo_toml::VersionReq {
    version
        .parse()
        .unwrap_or_else(|error| panic!("Invalid Cargo version requirement `{version}`: {error}"))
}

/// Embedded template directories.
/// A stable digest of every scaffold template baked into this CLI.
///
/// The generated host crates are a product of these templates, so anything that
/// caches a generated crate has to treat a template edit the same way it treats
/// a runtime source edit. Without this, upgrading the CLI leaves previously
/// generated crates in place, and they fail to compile against the API they
/// were meant to be regenerated for.
pub fn scaffold_template_digest() -> String {
    use sha2::Digest as _;

    fn hash_dir(hasher: &mut sha2::Sha256, dir: &Dir<'_>) {
        // `include_dir` yields entries in a stable order, but sort anyway so the
        // digest cannot depend on directory-walk order.
        let mut files: Vec<_> = dir.files().collect();
        files.sort_by_key(|file| file.path());
        for file in files {
            hasher.update(file.path().to_string_lossy().as_bytes());
            hasher.update(file.contents());
        }
        let mut dirs: Vec<_> = dir.dirs().collect();
        dirs.sort_by_key(|entry| entry.path());
        for entry in dirs {
            hash_dir(hasher, entry);
        }
    }

    let mut hasher = sha2::Sha256::new();
    for dir in [
        &embedded::ROOT,
        &embedded::HYDROLYSIS,
        &embedded::PREVIEW,
        &embedded::PREVIEW_FFI,
        &embedded::INSPECTOR,
        &embedded::FFI,
    ] {
        hash_dir(&mut hasher, dir);
    }
    let digest = hasher.finalize();
    digest.iter().take(8).fold(String::new(), |mut out, byte| {
        use core::fmt::Write as _;
        let _ = write!(out, "{byte:02x}");
        out
    })
}

mod embedded {
    use super::{Dir, include_dir};

    pub static APPLE: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/apple");
    pub static ANDROID: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/android");
    pub static FFI: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/ffi");
    pub static GTK4: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/gtk4");
    pub static HYDROLYSIS: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/hydrolysis");
    pub static ESP32: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/esp32");
    pub static PREVIEW: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/preview");
    pub static PREVIEW_FFI: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/preview_ffi");
    pub static INSPECTOR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/inspector");
    pub static ROOT: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates");
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AndroidPermissionTemplateEntry {
    pub name: &'static str,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IosPermissionTemplateEntry {
    pub plist_key: &'static str,
    pub description: String,
}

impl IosPermissionTemplateEntry {
    #[must_use]
    pub fn escaped_description(&self) -> String {
        self.description.replace('"', "\\\"")
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontRegistrationTemplateEntry {
    pub family_name: String,
    pub file_name: String,
}

/// ESP32 harness parameters substituted into the generated firmware crate.
///
/// `chip` is the single source of truth; the firmware fields are derived from
/// it via [`crate::esp32::chip::Esp32Chip::firmware_params`] when the entry is
/// constructed, so the harness templates never special-case a chip by name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Esp32TemplateEntry {
    /// Target chip (e.g. "esp32s3"); selects the target triple and every
    /// chip-specific firmware parameter below.
    pub chip: String,
    /// Panel width in pixels.
    pub panel_width: u32,
    /// Panel height in pixels.
    pub panel_height: u32,
    /// Maximum rows per rasterization band (bounds scratch memory).
    pub band_height: u32,
    /// Absolute paths of TTF/OTF binaries the harness `include_bytes!`es
    /// into flash for dew text shaping. Firmware has no font directory to
    /// enumerate, so a text-rendering app must bundle at least one face.
    pub fonts: Vec<String>,
    /// Route the firmware console to UART0 (`true`) or USB-Serial-JTAG.
    pub console_uart_default: bool,
    /// Flash size in megabytes (`CONFIG_ESPTOOLPY_FLASHSIZE_*MB`).
    pub flash_size_mb: u32,
    /// Main-task stack size in bytes (`CONFIG_ESP_MAIN_TASK_STACK_SIZE`).
    pub main_task_stack_bytes: u32,
    /// Offset of the app (`factory`) partition.
    pub app_partition_offset: String,
    /// Size of the app (`factory`) partition.
    pub app_partition_size: String,
    /// Cargo codegen `opt-level` for the firmware profiles.
    pub opt_level: String,
}

impl Esp32TemplateEntry {
    /// Builds a harness entry for `chip` with the given panel geometry,
    /// deriving every chip-specific firmware parameter from the chip's
    /// architecture.
    #[must_use]
    pub fn new(
        chip: crate::esp32::chip::Esp32Chip,
        panel_width: u32,
        panel_height: u32,
        band_height: u32,
    ) -> Self {
        let params = chip.firmware_params();
        Self {
            chip: chip.id().to_string(),
            panel_width,
            panel_height,
            band_height,
            fonts: Vec::new(),
            console_uart_default: params.console_uart_default,
            flash_size_mb: params.flash_size_mb,
            main_task_stack_bytes: params.main_task_stack_bytes,
            app_partition_offset: params.app_partition_offset.to_string(),
            app_partition_size: params.app_partition_size.to_string(),
            opt_level: params.opt_level.to_string(),
        }
    }

    /// Sets the flash-bundled font binaries (absolute paths).
    #[must_use]
    pub fn with_fonts(mut self, fonts: Vec<String>) -> Self {
        self.fonts = fonts;
        self
    }

    /// The Rust target triple for the configured chip (e.g.
    /// `riscv32imc-esp-espidf`), used by the `.cargo/config.toml` template and
    /// by regeneration checks.
    ///
    /// # Panics
    ///
    /// Panics when `chip` is not a supported ESP32 chip; the entry is only ever
    /// constructed from an already-validated [`crate::esp32::chip::Esp32Chip`].
    #[must_use]
    pub fn resolved_target_triple(&self) -> &'static str {
        self.chip
            .parse::<crate::esp32::chip::Esp32Chip>()
            .unwrap_or_else(|error| panic!("Esp32TemplateEntry holds an invalid chip: {error}"))
            .target_triple()
    }
}

impl Default for Esp32TemplateEntry {
    fn default() -> Self {
        Self::new(crate::esp32::chip::Esp32Chip::Esp32S3, 410, 502, 16)
    }
}

/// What the application's own dependency graph says about browser components.
///
/// Nothing here is configuration: the engine that draws a `WebView` is a crate
/// the application links and installs, so the generated backend only has to
/// know whether it should bridge the platform's own engine, and whether the
/// package needs a CEF subprocess helper.
#[derive(Debug, Clone, Copy, Default)]
pub struct BrowserTemplateContext {
    /// Whether the packaged application links the standard `WebView` component.
    pub webview_enabled: bool,
    /// Whether the packaged application links the independent Chromium component.
    pub chromium_enabled: bool,
    /// The browser engine crate the application links, if any.
    pub engine: Option<ResolvedWebViewBackend>,
}

/// Context for rendering templates with type-safe substitutions.
#[derive(Debug, Clone)]
pub struct TemplateContext {
    /// The application display name (e.g., "My App")
    pub app_display_name: String,
    /// The application name for file/folder naming (e.g., "`MyApp`")
    pub app_name: String,
    /// The Rust crate name (e.g., "`my_app`")
    pub crate_name: CrateName,
    /// The bundle identifier (e.g., "dev.waterui.myapp")
    pub bundle_identifier: BundleIdentifier,
    /// The author name
    pub author: String,
    /// Path to the Android backend (relative or absolute)
    pub android_backend_path: Option<PathBuf>,
    /// Whether to use remote dev backend (`JitPack`) instead of local
    pub use_remote_dev_backend: bool,
    /// Path to local `WaterUI` repository (for dev mode)
    pub waterui_path: Option<PathBuf>,
    /// Browser engine and component selections for generated backend manifests.
    pub browser: BrowserTemplateContext,
    /// Path to the backend project being scaffolded.
    ///
    /// This may be relative to the project root or an absolute cache path.
    pub backend_project_path: Option<PathBuf>,
    /// Absolute path to the user project root when scaffolding generated backend projects.
    pub project_root_path: Option<PathBuf>,
    /// Android permissions to include in the manifest (e.g., "internet", "camera")
    pub android_permissions: Vec<AndroidPermissionTemplateEntry>,
    /// iOS permissions to include in Info.plist (e.g., "microphone", "camera")
    pub ios_permissions: Vec<IosPermissionTemplateEntry>,
    /// Whether to build as an accessory (headless) app on macOS.
    pub accessory: bool,
    /// Preview runtime fingerprint inserted into preview support app templates.
    pub preview_runtime_fingerprint: Option<String>,
    /// Exact `WaterUI` feature set linked into a preview support runtime.
    pub preview_runtime_features: Vec<String>,
    /// User crate whose dependency graph defines the preview runtime ABI.
    pub preview_app_dependency: Option<(CrateName, PathBuf)>,
    /// Package type of the project being scaffolded.
    pub package_type: crate::project::PackageType,
    /// ESP32 harness parameters used by the esp32 templates.
    pub esp32: Esp32TemplateEntry,
}

impl TemplateContext {
    /// Build a template context for a new root project scaffold.
    #[must_use]
    pub fn for_create_options(
        options: &crate::project::CreateOptions,
        crate_name: CrateName,
    ) -> Self {
        let waterui_path = options.waterui_path.clone();
        Self {
            app_display_name: options.name.clone(),
            app_name: options.name.replace(' ', ""),
            crate_name,
            bundle_identifier: options.bundle_identifier.clone(),
            author: options.author.clone(),
            android_backend_path: waterui_path
                .as_ref()
                .map(|path| path.join("backends/android")),
            use_remote_dev_backend: waterui_path.is_none(),
            waterui_path,
            browser: BrowserTemplateContext::default(),
            backend_project_path: None,
            project_root_path: None,
            android_permissions: Vec::new(),
            ios_permissions: Vec::new(),
            accessory: false,
            preview_runtime_fingerprint: None,
            preview_runtime_features: Vec::new(),
            preview_app_dependency: None,
            package_type: options.package_type,
            esp32: Esp32TemplateEntry::default(),
        }
    }

    /// Build a context from an existing project manifest for backend scaffolding.
    #[must_use]
    pub fn for_project_manifest(
        manifest: &crate::project::Manifest,
        crate_name: CrateName,
        app_name: impl Into<String>,
    ) -> Self {
        Self {
            app_display_name: manifest.package.name.clone(),
            app_name: app_name.into(),
            crate_name,
            bundle_identifier: manifest.package.bundle_identifier.clone(),
            author: String::new(),
            android_backend_path: None,
            use_remote_dev_backend: manifest.waterui_path.is_none(),
            waterui_path: manifest.waterui_path.as_ref().map(PathBuf::from),
            browser: BrowserTemplateContext::default(),
            backend_project_path: None,
            project_root_path: None,
            android_permissions: Vec::new(),
            ios_permissions: Vec::new(),
            accessory: manifest.package.accessory,
            preview_runtime_fingerprint: None,
            preview_runtime_features: Vec::new(),
            preview_app_dependency: None,
            package_type: manifest.package.package_type,
            esp32: Esp32TemplateEntry::default(),
        }
    }

    /// Build a context for support applications that always run as playground projects.
    #[must_use]
    pub fn for_support_playground(
        app_display_name: impl Into<String>,
        app_name: impl Into<String>,
        crate_name: CrateName,
        bundle_identifier: BundleIdentifier,
        waterui_path: Option<PathBuf>,
        accessory: bool,
        preview_runtime_fingerprint: Option<String>,
    ) -> Self {
        let android_backend_path = waterui_path
            .as_ref()
            .map(|waterui_path| waterui_path.join("backends/android"));
        // A support app exists to host one specific WaterUI runtime, so it has
        // to resolve dependencies exactly the way that runtime's own workspace
        // does — `[patch]` included. Cargo only honours `[patch]` from the root
        // of the workspace being built, and a support app scaffolded outside
        // that tree has no such root: it silently resolves the unpatched
        // crates.io version of every forked dependency. The app then links a
        // different graphics stack than the module it loads, and the module
        // fails to `dlopen` against symbols that no longer match.
        let project_root_path = waterui_path.clone();
        Self {
            app_display_name: app_display_name.into(),
            app_name: app_name.into(),
            crate_name,
            bundle_identifier,
            author: String::new(),
            android_backend_path,
            use_remote_dev_backend: waterui_path.is_none(),
            waterui_path,
            browser: BrowserTemplateContext::default(),
            backend_project_path: None,
            project_root_path,
            android_permissions: Vec::new(),
            ios_permissions: Vec::new(),
            accessory,
            preview_runtime_fingerprint,
            preview_runtime_features: Vec::new(),
            preview_app_dependency: None,
            package_type: crate::project::PackageType::Playground,
            esp32: Esp32TemplateEntry::default(),
        }
    }

    /// Set backend project path for template rendering.
    #[must_use]
    pub fn with_backend_project_path(mut self, path: PathBuf) -> Self {
        self.backend_project_path = Some(path);
        self
    }

    /// Set absolute project root path for template rendering.
    #[must_use]
    pub fn with_project_root_path(mut self, path: PathBuf) -> Self {
        self.project_root_path = Some(path);
        self
    }

    /// Set whether the application runtime graph links `waterui-webview`.
    #[must_use]
    pub const fn with_webview_enabled(mut self, enabled: bool) -> Self {
        self.browser.webview_enabled = enabled;
        self
    }

    /// Set whether the application runtime graph links `waterui-chromium`.
    #[must_use]
    pub const fn with_chromium_enabled(mut self, enabled: bool) -> Self {
        self.browser.chromium_enabled = enabled;
        self
    }

    /// Set the browser engine crate the application's runtime graph links.
    #[must_use]
    pub const fn with_browser_engine(mut self, engine: Option<ResolvedWebViewBackend>) -> Self {
        self.browser.engine = engine;
        self
    }

    /// The backend feature that bridges the platform's own web engine.
    ///
    /// An application that linked an engine of its own draws through that
    /// instead, and the bridge would take the component by type before the
    /// application's realization was ever consulted — so the backend compiles
    /// no web engine at all.
    const fn webview_backend_feature(&self) -> Option<&'static str> {
        if self.browser.webview_enabled && self.browser.engine.is_none() {
            Some("webview-system")
        } else {
            None
        }
    }

    const fn chromium_enabled(&self) -> bool {
        self.browser.chromium_enabled
    }

    /// Whether the standard `WebView` in this application is drawn by CEF.
    const fn cef_webview_enabled(&self) -> bool {
        self.browser.webview_enabled && self.cef_runtime_enabled()
    }

    const fn cef_runtime_enabled(&self) -> bool {
        matches!(self.browser.engine, Some(ResolvedWebViewBackend::Cef))
    }

    /// Set the exact `WaterUI` feature set used by a preview support runtime.
    #[must_use]
    pub fn with_preview_runtime_features(mut self, features: Vec<String>) -> Self {
        self.preview_runtime_features = features;
        self
    }

    /// Set the user crate used to reproduce the preview module's dependency graph.
    #[must_use]
    pub fn with_preview_app_dependency(mut self, crate_name: CrateName, path: PathBuf) -> Self {
        self.preview_app_dependency = Some((crate_name, path));
        self
    }

    /// Set Android permissions for template rendering.
    #[must_use]
    pub fn with_android_permissions(
        mut self,
        permissions: Vec<AndroidPermissionTemplateEntry>,
    ) -> Self {
        self.android_permissions = permissions;
        self
    }

    /// Set iOS permissions for template rendering.
    #[must_use]
    pub fn with_ios_permissions(mut self, permissions: Vec<IosPermissionTemplateEntry>) -> Self {
        self.ios_permissions = permissions;
        self
    }

    /// Set ESP32 harness parameters for template rendering.
    #[must_use]
    pub fn with_esp32(mut self, esp32: Esp32TemplateEntry) -> Self {
        self.esp32 = esp32;
        self
    }

    #[must_use]
    pub fn crate_name_ident(&self) -> RustIdent {
        self.crate_name.rust_ident()
    }

    #[must_use]
    pub fn android_package_name(&self) -> String {
        self.bundle_identifier
            .android_package_name()
            .unwrap_or_else(|error| panic!("{error}"))
            .to_string()
    }

    #[must_use]
    #[expect(
        clippy::unused_self,
        reason = "Askama invokes template context values through instance methods"
    )]
    pub const fn android_min_api_level(&self) -> u32 {
        crate::android::ANDROID_MIN_API_LEVEL
    }

    #[must_use]
    pub fn android_backend_path(&self) -> String {
        if self.use_remote_dev_backend {
            return String::new();
        }

        self.compute_android_backend_path().unwrap_or_else(|| {
            panic!(
                "TemplateContext missing local Android backend path: \
use_remote_dev_backend=false requires waterui_path or android_backend_path"
            )
        })
    }

    #[must_use]
    #[allow(clippy::unused_self)]
    pub fn android_remote_backend_dependency(&self) -> String {
        jitpack_dependency_coordinate(ANDROID_BACKEND.repository_url, ANDROID_BACKEND.commit)
    }

    #[must_use]
    pub fn is_playground(&self) -> bool {
        self.package_type == crate::project::PackageType::Playground
    }

    #[must_use]
    pub const fn macos_lsuielement(&self) -> &'static str {
        if self.accessory { "YES" } else { "NO" }
    }

    #[must_use]
    pub fn preview_runtime_fingerprint(&self) -> &str {
        self.preview_runtime_fingerprint
            .as_deref()
            .unwrap_or_default()
    }

    /// Transform a path by replacing "`AppName`" with the actual app name.
    #[must_use]
    pub fn transform_path(&self, path: &Path) -> PathBuf {
        let path_str = path.to_string_lossy();
        PathBuf::from(path_str.replace("AppName", &self.app_name))
    }

    /// Compute the relative path from the backend project to a `WaterUI` backend.
    ///
    /// This accounts for the project being in a generated backend subdirectory.
    fn compute_relative_backend_path(&self, backend_subdir: &str) -> Option<String> {
        let waterui_path = self.waterui_path.as_ref()?;

        // If `waterui_path` is absolute, use it directly. This avoids producing invalid
        // paths like `../../../..//Users/...` in generated config files.
        if waterui_path.is_absolute() {
            let absolute_backend_path = waterui_path.join("backends").join(backend_subdir);
            return Some(normalize_path_for_config(&absolute_backend_path));
        }

        if let Some(backend_project_path) = self
            .backend_project_path
            .as_ref()
            .filter(|path| path.is_absolute())
        {
            let project_root = self.project_root_path.as_ref().unwrap_or_else(|| {
                panic!(
                    "TemplateContext missing project_root_path for absolute backend project {}",
                    backend_project_path.display()
                )
            });
            let absolute_backend_path = project_root
                .join(waterui_path)
                .join("backends")
                .join(backend_subdir);
            let relative_path = pathdiff::diff_paths(&absolute_backend_path, backend_project_path)
                .unwrap_or_else(|| {
                    panic!(
                        "Failed to compute backend dependency path from {} to {}",
                        backend_project_path.display(),
                        absolute_backend_path.display()
                    )
                });
            return Some(normalize_path_for_config(&relative_path));
        }

        // Count how many levels deep the project is from the project root.
        // Default is 1 level (e.g., "android"), generated playground backends may be deeper.
        let project_depth = self
            .backend_project_path
            .as_ref()
            .map_or(1, |p| p.components().count());

        // Build the relative path: go up `project_depth` levels, then to waterui_path/backends/<backend>.
        // Use `PathBuf` joins to avoid accidental `//` sequences and to keep behavior consistent
        // across platforms.
        let mut backend_path = PathBuf::new();
        for _ in 0..project_depth {
            backend_path.push("..");
        }
        backend_path.push(waterui_path);
        backend_path.push("backends");
        backend_path.push(backend_subdir);

        Some(normalize_path_for_config(&backend_path))
    }

    /// Compute the relative path from the Xcode project to the `WaterUI` Swift backend.
    fn compute_apple_backend_path(&self) -> Option<String> {
        self.compute_relative_backend_path("apple")
    }

    /// Compute the relative path from the Android project to the `WaterUI` Android backend.
    fn compute_android_backend_path(&self) -> Option<String> {
        self.android_backend_path
            .as_ref()
            .map(|path| normalize_path_for_config(path))
            .or_else(|| self.compute_relative_backend_path("android"))
    }

    /// Absolute path of the `WaterUI` workspace root when building against a
    /// local checkout, resolved against the project root for relative
    /// `waterui_path` values. `None` in remote-backend mode.
    fn waterui_workspace_root(&self) -> Option<PathBuf> {
        let waterui_path = self.waterui_path.as_ref()?;
        if waterui_path.is_absolute() {
            return Some(waterui_path.clone());
        }
        self.project_root_path
            .as_ref()
            .map(|project_root| project_root.join(waterui_path))
    }

    /// Compute the relative path from the backend project directory to the project root.
    ///
    /// For a backend at `apple/`, returns `..` (go up 1 level).
    /// For a backend at `managed_backends/apple/`, returns `../..` (go up 2 levels).
    fn project_root_relative_path(&self) -> String {
        if let Some(backend_project_path) = self
            .backend_project_path
            .as_ref()
            .filter(|path| path.is_absolute())
        {
            let project_root = self.project_root_path.as_ref().unwrap_or_else(|| {
                panic!(
                    "TemplateContext missing project_root_path for absolute backend project {}",
                    backend_project_path.display()
                )
            });
            let relative_path = pathdiff::diff_paths(project_root, backend_project_path)
                .unwrap_or_else(|| {
                    panic!(
                        "Failed to compute project root path from {} to {}",
                        backend_project_path.display(),
                        project_root.display()
                    )
                });
            return normalize_path_for_config(&relative_path);
        }

        let depth = self
            .backend_project_path
            .as_ref()
            .map_or(1, |p| p.components().count());

        (0..depth).map(|_| "..").collect::<Vec<_>>().join("/")
    }

    /// Generate the `XCode` package reference entry line for the project file.
    fn swift_package_reference_entry(&self) -> String {
        const PACKAGE_ID: &str = "D01867782E6C82CA00802E96";
        const INDENT: &str = "\t\t\t\t";
        let repository_name = github_repository_name(APPLE_BACKEND.repository_url);

        self.compute_apple_backend_path().map_or_else(
            || {
                format!(
                    "{INDENT}{PACKAGE_ID} /* XCRemoteSwiftPackageReference \"{repository_name}\" */,"
                )
            },
            |backend_path| {
                format!(
                    "{INDENT}{PACKAGE_ID} /* XCLocalSwiftPackageReference \"{backend_path}\" */,"
                )
            },
        )
    }

    /// Generate the `XCode` package reference section for the project file.
    fn swift_package_reference_section(&self) -> String {
        const PACKAGE_ID: &str = "D01867782E6C82CA00802E96";
        let repository_name = github_repository_name(APPLE_BACKEND.repository_url);

        self.compute_apple_backend_path().map_or_else(
            || {
                format!(
                    "/* Begin XCRemoteSwiftPackageReference section */\n\
                    \t\t{PACKAGE_ID} /* XCRemoteSwiftPackageReference \"{repository_name}\" */ = {{\n\
                    \t\t\tisa = XCRemoteSwiftPackageReference;\n\
                    \t\t\trepositoryURL = \"{}\";\n\
                    \t\t\trequirement = {{\n\
                    \t\t\t\tkind = revision;\n\
                    \t\t\t\trevision = \"{}\";\n\
                    \t\t\t}};\n\
                    \t\t}};\n\
                    /* End XCRemoteSwiftPackageReference section */",
                    APPLE_BACKEND.repository_url,
                    APPLE_BACKEND.commit,
                )
            },
            |backend_path| {
                format!(
                    "/* Begin XCLocalSwiftPackageReference section */\n\
                    \t\t{PACKAGE_ID} /* XCLocalSwiftPackageReference \"{backend_path}\" */ = {{\n\
                    \t\t\tisa = XCLocalSwiftPackageReference;\n\
                    \t\t\trelativePath = \"{backend_path}\";\n\
                    \t\t}};\n\
                    /* End XCLocalSwiftPackageReference section */"
                )
            },
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TemplateNamespace {
    Apple,
    Android,
    Ffi,
    Gtk4,
    Hydrolysis,
    Esp32,
    Inspector,
    Preview,
    PreviewFfi,
    Root,
}

impl TemplateNamespace {
    const fn scaffold_template_prefix(self) -> &'static str {
        match self {
            Self::Apple => "src/templates/apple",
            Self::Android => "src/templates/android",
            Self::Ffi => "src/templates/ffi",
            Self::Gtk4 => "src/templates/gtk4",
            Self::Hydrolysis => "src/templates/hydrolysis",
            Self::Esp32 => "src/templates/esp32",
            Self::Inspector => "src/templates/inspector",
            Self::Preview => "src/templates/preview",
            Self::PreviewFfi => "src/templates/preview_ffi",
            Self::Root => "src/templates",
        }
    }
}

fn scaffold_template_dispatch_path(namespace: TemplateNamespace, relative_path: &Path) -> String {
    let relative_path = normalize_path_for_config(relative_path);
    if relative_path.starts_with("src/templates/") {
        return relative_path;
    }
    format!("{}/{relative_path}", namespace.scaffold_template_prefix())
}

fn github_repository_owner_and_name(repository_url: &str) -> (&str, &str) {
    let path = repository_url
        .strip_prefix("https://github.com/")
        .or_else(|| repository_url.strip_prefix("git@github.com:"))
        .unwrap_or_else(|| panic!("unsupported GitHub repository URL: {repository_url}"));
    let path = path.strip_suffix(".git").unwrap_or(path);
    let mut segments = path.split('/');
    let owner = segments
        .next()
        .filter(|segment| !segment.is_empty())
        .unwrap_or_else(|| panic!("missing GitHub owner in repository URL: {repository_url}"));
    let repo = segments
        .next()
        .filter(|segment| !segment.is_empty())
        .unwrap_or_else(|| {
            panic!("missing GitHub repository name in repository URL: {repository_url}")
        });
    assert!(
        segments.next().is_none(),
        "unsupported GitHub repository URL path: {repository_url}"
    );
    (owner, repo)
}

fn github_repository_name(repository_url: &str) -> &str {
    let (_, repo) = github_repository_owner_and_name(repository_url);
    repo
}

fn jitpack_dependency_coordinate(repository_url: &str, commit: &str) -> String {
    let (owner, repo) = github_repository_owner_and_name(repository_url);
    format!("com.github.{owner}:{repo}:{commit}")
}

macro_rules! define_scaffold_templates {
    ($($name:ident => ($namespace:ident, $path:literal)),* $(,)?) => {
        $(
            #[derive(Template)]
            #[template(path = $path, escape = "none")]
            struct $name<'a> {
                ctx: &'a TemplateContext,
            }
        )*

        fn render_scaffold_template(
            namespace: TemplateNamespace,
            relative_path: &Path,
            content: &str,
            ctx: &TemplateContext,
        ) -> io::Result<String> {
            let display_path = relative_path.to_string_lossy();
            let dispatch_path = scaffold_template_dispatch_path(namespace, relative_path);
            match dispatch_path.as_str() {
                "src/templates/apple/AppName/WaterUIFonts.swift.tpl" => {
                    let empty_font_entries: &[FontRegistrationTemplateEntry] = &[];
                    ScaffoldAppleFontTemplate {
                        font_entries: empty_font_entries,
                    }
                    .render()
                    .map_err(|error| {
                        io::Error::new(
                            io::ErrorKind::InvalidData,
                            format!("Failed to render template {display_path}: {error}"),
                        )
                    })
                }
                "src/templates/esp32/Cargo.toml.tpl" => Esp32CargoTomlTemplate::from_ctx(ctx)
                    .render()
                    .map_err(|error| {
                        io::Error::new(
                            io::ErrorKind::InvalidData,
                            format!("Failed to render template {display_path}: {error}"),
                        )
                    }),
                $(
                    $path => $name { ctx }
                        .render()
                        .map_err(|error| {
                            io::Error::new(
                                io::ErrorKind::InvalidData,
                                format!("Failed to render template {display_path}: {error}"),
                            )
                        }),
                )*
                _ => Ok(content.to_string()),
            }
        }
    };
}

#[derive(Template)]
#[template(
    path = "src/templates/apple/AppName/WaterUIFonts.swift.tpl",
    escape = "none"
)]
struct ScaffoldAppleFontTemplate<'a> {
    font_entries: &'a [FontRegistrationTemplateEntry],
}

/// Generated `Cargo.toml` for the ESP32 firmware harness crate.
///
/// Rendered through an askama template (instead of a serialized manifest)
/// so the generated file can carry the Xtensa miscompilation profile note.
#[derive(Template)]
#[template(path = "src/templates/esp32/Cargo.toml.tpl", escape = "none")]
struct Esp32CargoTomlTemplate {
    package_name: String,
    app_crate_name: String,
    app_crate_path: String,
    dew_path: Option<String>,
    core_path: Option<String>,
    dew_version: &'static str,
    waterui_version: &'static str,
    /// The `opt-level` value as a TOML literal: numeric levels are bare
    /// integers, while `"s"`/`"z"` must be quoted strings — cargo rejects a
    /// quoted `"2"`.
    opt_level_literal: String,
}

impl Esp32CargoTomlTemplate {
    fn from_ctx(ctx: &TemplateContext) -> Self {
        let dew_path = ctx.waterui_path.as_ref().map(|waterui_path| {
            compute_native_backend_dependency_path(
                ctx,
                waterui_path,
                NativeBackendDependencyPathKind::BackendsSubdir("dew"),
            )
        });
        let core_path = ctx.waterui_path.as_ref().map(|waterui_path| {
            compute_native_backend_dependency_path(
                ctx,
                waterui_path,
                NativeBackendDependencyPathKind::WorkspaceSubdir("core"),
            )
        });

        Self {
            package_name: ctx.crate_name.with_suffix("esp32").to_string(),
            app_crate_name: ctx.crate_name.to_string(),
            app_crate_path: ctx.project_root_relative_path(),
            dew_path,
            core_path,
            dew_version: DEW_VERSION,
            waterui_version: WATERUI_VERSION,
            opt_level_literal: match ctx.esp32.opt_level.as_str() {
                symbolic @ ("s" | "z") => format!("\"{symbolic}\""),
                numeric => numeric
                    .parse::<u8>()
                    .unwrap_or_else(|error| {
                        panic!(
                            "ESP32 opt-level {numeric:?} is neither symbolic nor numeric: {error}"
                        )
                    })
                    .to_string(),
            },
        }
    }
}

define_scaffold_templates! {
    AssetsReadmeTemplate => (Root, "src/templates/assets_readme.md.tpl"),
    AppleProjectTemplate => (Apple, "src/templates/apple/AppName.xcodeproj/project.pbxproj.tpl"),
    AppleAppTemplate => (Apple, "src/templates/apple/AppName/AppNameApp.swift.tpl"),
    AppleBuildScriptTemplate => (Apple, "src/templates/apple/build-rust.sh.tpl"),
    AndroidGradleAppTemplate => (Android, "src/templates/android/app/build.gradle.kts.tpl"),
    AndroidManifestTemplate => (Android, "src/templates/android/app/src/main/AndroidManifest.xml.tpl"),
    AndroidMainActivityTemplate => (Android, "src/templates/android/app/src/main/java/MainActivity.kt.tpl"),
    AndroidApplicationTemplate => (Android, "src/templates/android/app/src/main/java/WaterUiApplication.kt.tpl"),
    AndroidStringsTemplate => (Android, "src/templates/android/app/src/main/res/values/strings.xml.tpl"),
    AndroidSettingsTemplate => (Android, "src/templates/android/settings.gradle.kts.tpl"),
    FfiLibTemplate => (Ffi, "src/templates/ffi/src/lib.rs.tpl"),
    Gtk4MainTemplate => (Gtk4, "src/templates/gtk4/src/main.rs.tpl"),
    HydrolysisLibTemplate => (Hydrolysis, "src/templates/hydrolysis/src/lib.rs.tpl"),
    HydrolysisMainTemplate => (Hydrolysis, "src/templates/hydrolysis/src/main.rs.tpl"),
    HydrolysisPreviewRuntimeTemplate => (Hydrolysis, "src/templates/hydrolysis/src/preview_runtime.rs.tpl"),
    HydrolysisPreviewTestRuntimeTemplate => (Hydrolysis, "src/templates/hydrolysis/src/preview_test_runtime.rs.tpl"),
    HydrolysisWebIndexTemplate => (Hydrolysis, "src/templates/hydrolysis/web/index.html.tpl"),
    Esp32MainTemplate => (Esp32, "src/templates/esp32/src/main.rs.tpl"),
    Esp32CargoConfigTemplate => (Esp32, "src/templates/esp32/.cargo/config.toml.tpl"),
    Esp32SdkconfigTemplate => (Esp32, "src/templates/esp32/sdkconfig.defaults.tpl"),
    Esp32PartitionsTemplate => (Esp32, "src/templates/esp32/partitions.csv.tpl"),
    PreviewLibTemplate => (Preview, "src/templates/preview/src/lib.rs.tpl"),
    PreviewFfiLibTemplate => (PreviewFfi, "src/templates/preview_ffi/src/lib.rs.tpl"),
}

#[cfg(test)]
mod tests {
    use super::{
        ANDROID_BACKEND, APPLE_BACKEND, BrowserTemplateContext, Esp32TemplateEntry,
        GTK_BACKEND_VERSION, HYDROLYSIS_M3_VERSION, PREVIEW_PROTOCOL_VERSION, PREVIEW_VERSION,
        ResolvedWebViewBackend, TemplateContext, TemplateNamespace, WATERUI_BROWSER_CEF_VERSION,
        WATERUI_CORE_VERSION, embedded, jitpack_dependency_coordinate, normalize_path_for_config,
        preview_ffi, render_scaffold_template,
    };
    use crate::project_types::{BundleIdentifier, CrateName};
    use std::path::PathBuf;
    use tempfile::tempdir;

    fn ctx(
        waterui_path: Option<PathBuf>,
        backend_project_path: Option<PathBuf>,
        project_root_path: Option<PathBuf>,
        package_type: crate::project::PackageType,
    ) -> TemplateContext {
        TemplateContext {
            app_display_name: String::new(),
            app_name: String::new(),
            crate_name: CrateName::try_from("waterui_test").expect("test crate name must be valid"),
            bundle_identifier: BundleIdentifier::try_from("com.example.test")
                .expect("test bundle identifier must be valid"),
            author: String::new(),
            android_backend_path: None,
            use_remote_dev_backend: waterui_path.is_none(),
            waterui_path,
            browser: BrowserTemplateContext::default(),
            backend_project_path,
            project_root_path,
            android_permissions: Vec::new(),
            ios_permissions: Vec::new(),
            accessory: false,
            preview_runtime_fingerprint: None,
            preview_runtime_features: Vec::new(),
            preview_app_dependency: None,
            package_type,
            esp32: Esp32TemplateEntry::default(),
        }
    }

    fn app_ctx() -> TemplateContext {
        ctx(None, None, None, crate::project::PackageType::App)
    }

    fn playground_ctx() -> TemplateContext {
        TemplateContext::for_support_playground(
            "WaterUIApp",
            "WaterUIApp",
            CrateName::try_from("waterui_app").expect("test crate name must be valid"),
            BundleIdentifier::try_from("dev.waterui.playground")
                .expect("test bundle identifier must be valid"),
            Some(PathBuf::from("../..")),
            false,
            None,
        )
        .with_backend_project_path(PathBuf::from("managed_backends/apple"))
    }

    fn render_esp32(relative: &str, ctx: &TemplateContext) -> String {
        let template = embedded::ESP32
            .get_file(relative)
            .unwrap_or_else(|| panic!("esp32 template {relative} must exist"))
            .contents_utf8()
            .expect("esp32 template must be utf-8");
        render_scaffold_template(
            TemplateNamespace::Esp32,
            std::path::Path::new(relative),
            template,
            ctx,
        )
        .unwrap_or_else(|error| panic!("esp32 template {relative} render: {error}"))
    }

    #[test]
    fn esp32_templates_are_chip_architecture_aware() {
        use crate::esp32::chip::Esp32Chip;

        let mut s3 = app_ctx();
        s3.esp32 = Esp32TemplateEntry::new(Esp32Chip::Esp32S3, 410, 502, 16);
        let mut c3 = app_ctx();
        c3.esp32 = Esp32TemplateEntry::new(Esp32Chip::Esp32C3, 200, 240, 16);

        // .cargo/config.toml: Xtensa per-chip triple vs RISC-V architecture triple.
        let s3_cargo = render_esp32(".cargo/config.toml.tpl", &s3);
        assert!(s3_cargo.contains("target = \"xtensa-esp32s3-espidf\""));
        assert!(s3_cargo.contains("MCU = \"esp32s3\""));
        let c3_cargo = render_esp32(".cargo/config.toml.tpl", &c3);
        assert!(c3_cargo.contains("target = \"riscv32imc-esp-espidf\""));
        assert!(c3_cargo.contains("MCU = \"esp32c3\""));

        // sdkconfig: USB-Serial-JTAG + 8 MB + bigger stack on S3; UART0 + 4 MB on C3.
        let s3_sdk = render_esp32("sdkconfig.defaults.tpl", &s3);
        assert!(s3_sdk.contains("CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y"));
        assert!(s3_sdk.contains("CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y"));
        assert!(s3_sdk.contains("CONFIG_ESP_MAIN_TASK_STACK_SIZE=163840"));
        let c3_sdk = render_esp32("sdkconfig.defaults.tpl", &c3);
        assert!(c3_sdk.contains("CONFIG_ESP_CONSOLE_UART_DEFAULT=y"));
        assert!(c3_sdk.contains("CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y"));
        assert!(c3_sdk.contains("CONFIG_ESP_MAIN_TASK_STACK_SIZE=49152"));

        // partitions: 6 MB app on S3, 3 MB on C3.
        assert!(render_esp32("partitions.csv.tpl", &s3).contains("0x10000, 0x600000,"));
        assert!(render_esp32("partitions.csv.tpl", &c3).contains("0x10000, 0x300000,"));

        // Cargo.toml profile: size-opt on Xtensa, full-opt on RISC-V; both enable
        // the dew progress widget.
        let s3_manifest = render_esp32("Cargo.toml.tpl", &s3);
        assert!(s3_manifest.contains("opt-level = \"s\""));
        assert!(s3_manifest.contains("features = [\"espidf\", \"progress\"]"));
        let c3_manifest = render_esp32("Cargo.toml.tpl", &c3);
        assert!(c3_manifest.contains("opt-level = 2"));
        // Release firmware is flash-budgeted: whole-program LTO and symbol
        // stripping are not optional niceties on a 4-16 MB part.
        assert!(c3_manifest.contains("lto = \"fat\""));
        assert!(c3_manifest.contains("codegen-units = 1"));
        assert!(c3_manifest.contains("strip = \"symbols\""));
        assert!(c3_manifest.contains("features = [\"espidf\", \"progress\"]"));

        // main.rs panel geometry follows the entry.
        assert!(render_esp32("src/main.rs.tpl", &c3).contains("PanelConfig::new(200, 240, 16)"));

        // Configured fonts render as flash-embedded binaries; without any,
        // the FONTS table is empty and dew fails fast at the first text.
        let mut with_fonts = app_ctx();
        with_fonts.esp32 = Esp32TemplateEntry::new(Esp32Chip::Esp32C3, 200, 240, 16)
            .with_fonts(vec!["/tmp/fonts/Demo.ttf".to_string()]);
        let main_rs = render_esp32("src/main.rs.tpl", &with_fonts);
        assert!(main_rs.contains("include_bytes!(\"/tmp/fonts/Demo.ttf\")"));
        assert!(main_rs.contains("FONTS"));
        assert!(!render_esp32("src/main.rs.tpl", &c3).contains("include_bytes!"));
    }

    #[test]
    fn relative_waterui_path_produces_clean_relative_backend_path() {
        let ctx = ctx(
            Some(PathBuf::from("../..")),
            Some(PathBuf::from("managed_backends/apple")),
            None,
            crate::project::PackageType::App,
        );

        let path = ctx
            .compute_relative_backend_path("apple")
            .expect("expected relative backend path");

        assert_eq!(path, "../../../../backends/apple");
        assert!(!path.contains("//"));
    }

    #[test]
    fn absolute_waterui_path_is_used_directly() {
        let abs = if cfg!(windows) {
            PathBuf::from(r"C:\waterui")
        } else {
            PathBuf::from("/waterui")
        };

        let ctx = ctx(
            Some(abs),
            Some(PathBuf::from("apple")),
            None,
            crate::project::PackageType::App,
        );
        let path = ctx
            .compute_relative_backend_path("apple")
            .expect("expected backend path");

        let expected = if cfg!(windows) {
            "C:/waterui/backends/apple"
        } else {
            "/waterui/backends/apple"
        };
        assert_eq!(path, expected);
    }

    #[test]
    fn absolute_backend_project_path_uses_real_project_root() {
        let project_root = if cfg!(windows) {
            PathBuf::from(r"C:\Users\lexo\demo")
        } else {
            PathBuf::from("/Users/lexo/demo")
        };
        let backend_project_path = if cfg!(windows) {
            PathBuf::from(
                r"C:\Users\lexo\.water\build_cache\drive-C\Users\lexo\demo\managed_backends\apple",
            )
        } else {
            PathBuf::from("/Users/lexo/.water/build_cache/Users/lexo/demo/managed_backends/apple")
        };

        let ctx = ctx(
            Some(PathBuf::from("../waterui")),
            Some(backend_project_path.clone()),
            Some(project_root.clone()),
            crate::project::PackageType::Playground,
        );

        let path = ctx
            .compute_relative_backend_path("apple")
            .expect("expected backend path");
        let expected_backend_path = pathdiff::diff_paths(
            project_root.join("../waterui").join("backends/apple"),
            &backend_project_path,
        )
        .expect("backend diff path");
        assert_eq!(path, normalize_path_for_config(&expected_backend_path));

        let expected_project_root =
            pathdiff::diff_paths(&project_root, &backend_project_path).expect("project root diff");
        assert_eq!(
            ctx.project_root_relative_path(),
            normalize_path_for_config(&expected_project_root)
        );
    }

    #[test]
    fn android_manifest_enables_picture_in_picture_by_default() {
        let ctx = app_ctx();
        let template = embedded::ANDROID
            .get_file("app/src/main/AndroidManifest.xml.tpl")
            .expect("android manifest template must exist")
            .contents_utf8()
            .expect("android manifest template must be utf-8");

        let rendered = render_scaffold_template(
            TemplateNamespace::Android,
            std::path::Path::new("app/src/main/AndroidManifest.xml.tpl"),
            template,
            &ctx,
        )
        .expect("android manifest render");

        assert!(rendered.contains("android:resizeableActivity=\"true\""));
        assert!(rendered.contains("android:supportsPictureInPicture=\"true\""));
        assert!(rendered.contains(
            "android:configChanges=\"screenSize|smallestScreenSize|screenLayout|orientation\""
        ));
    }

    #[test]
    fn apple_project_enables_picture_in_picture_background_mode_by_default() {
        let ctx = app_ctx();
        let template = embedded::APPLE
            .get_file("AppName.xcodeproj/project.pbxproj.tpl")
            .expect("apple project template must exist")
            .contents_utf8()
            .expect("apple project template must be utf-8");

        let rendered = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("AppName.xcodeproj/project.pbxproj.tpl"),
            template,
            &ctx,
        )
        .expect("apple project render");

        assert!(
            rendered.contains("\"INFOPLIST_KEY_UIBackgroundModes[sdk=iphoneos*][0]\" = audio;")
        );
        assert!(
            rendered
                .contains("\"INFOPLIST_KEY_UIBackgroundModes[sdk=iphonesimulator*][0]\" = audio;")
        );
        // The project must not name the Rust library: its shape depends on the linkage
        // the running command selected (archive when packaging, shared library for a
        // development build), so the CLI injects `-lwaterui_app` into OTHER_LDFLAGS at
        // build time and leaves exactly one matching file in BUILT_PRODUCTS_DIR.
        assert!(!rendered.contains("libwaterui_app"));
        assert!(rendered.contains("LIBRARY_SEARCH_PATHS = \"$(BUILT_PRODUCTS_DIR)\";"));
        assert!(rendered.contains(APPLE_BACKEND.repository_url));
        assert!(rendered.contains(APPLE_BACKEND.commit));
        assert!(rendered.contains("kind = revision;"));
    }

    #[test]
    fn apple_chromium_template_links_and_initializes_cef_before_appkit() {
        let ctx = app_ctx()
            .with_chromium_enabled(true)
            .with_browser_engine(Some(ResolvedWebViewBackend::Cef));
        let project_template = embedded::APPLE
            .get_file("AppName.xcodeproj/project.pbxproj.tpl")
            .expect("apple project template must exist")
            .contents_utf8()
            .expect("apple project template must be utf-8");
        let project = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("AppName.xcodeproj/project.pbxproj.tpl"),
            project_template,
            &ctx,
        )
        .expect("apple Chromium project render");
        assert!(project.contains("WaterUICEF in Frameworks"));
        assert!(project.contains("WaterUIChromium in Frameworks"));
        assert!(!project.contains("WaterUICefWebView in Frameworks"));

        let app_template = embedded::APPLE
            .get_file("AppName/AppNameApp.swift.tpl")
            .expect("apple app template must exist")
            .contents_utf8()
            .expect("apple app template must be utf-8");
        let app = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("AppName/AppNameApp.swift.tpl"),
            app_template,
            &ctx,
        )
        .expect("apple Chromium app render");
        assert!(app.contains("import WaterUICEF"));
        assert!(app.contains("import WaterUIChromium"));
        assert!(app.contains("installWaterUIChromium()"));
        assert!(
            app.find("prepareWaterUICEFApplication()") < app.find("let app = NSApplication.shared")
        );
        assert!(!app.contains("runWaterUICEFSubprocessIfNeeded()"));
    }

    #[test]
    fn apple_cef_webview_template_links_only_the_standard_cef_component() {
        let ctx = app_ctx()
            .with_webview_enabled(true)
            .with_browser_engine(Some(ResolvedWebViewBackend::Cef));
        let project_template = embedded::APPLE
            .get_file("AppName.xcodeproj/project.pbxproj.tpl")
            .expect("apple project template must exist")
            .contents_utf8()
            .expect("apple project template must be utf-8");
        let project = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("AppName.xcodeproj/project.pbxproj.tpl"),
            project_template,
            &ctx,
        )
        .expect("apple CEF WebView project render");
        assert!(project.contains("WaterUICEF in Frameworks"));
        assert!(project.contains("WaterUICefWebView in Frameworks"));
        assert!(!project.contains("WaterUIChromium in Frameworks"));

        let app_template = embedded::APPLE
            .get_file("AppName/AppNameApp.swift.tpl")
            .expect("apple app template must exist")
            .contents_utf8()
            .expect("apple app template must be utf-8");
        let app = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("AppName/AppNameApp.swift.tpl"),
            app_template,
            &ctx,
        )
        .expect("apple CEF WebView app render");
        assert!(app.contains("import WaterUICefWebView"));
        assert!(app.contains("installWaterUICefWebView()"));
        assert!(!app.contains("installWaterUIChromium()"));
    }

    #[test]
    fn android_build_gradle_uses_embedded_remote_backend_commit() {
        let ctx = app_ctx();
        let template = embedded::ANDROID
            .get_file("app/build.gradle.kts.tpl")
            .expect("android build.gradle template must exist")
            .contents_utf8()
            .expect("android build.gradle template must be utf-8");

        let rendered = render_scaffold_template(
            TemplateNamespace::Android,
            std::path::Path::new("app/build.gradle.kts.tpl"),
            template,
            &ctx,
        )
        .expect("android build.gradle render");

        assert!(rendered.contains("minSdk = 26"));
        assert!(rendered.contains(&jitpack_dependency_coordinate(
            ANDROID_BACKEND.repository_url,
            ANDROID_BACKEND.commit,
        )));
    }

    #[test]
    fn android_activity_installs_edge_to_edge_and_leases_activity_context() {
        let ctx = app_ctx();
        let activity_template = embedded::ANDROID
            .get_file("app/src/main/java/MainActivity.kt.tpl")
            .expect("android MainActivity template must exist")
            .contents_utf8()
            .expect("android MainActivity template must be utf-8");

        let activity = render_scaffold_template(
            TemplateNamespace::Android,
            std::path::Path::new("app/src/main/java/MainActivity.kt.tpl"),
            activity_template,
            &ctx,
        )
        .expect("android MainActivity render");

        assert!(activity.contains("enableEdgeToEdge()"));
        assert!(activity.contains("waterUiApplication.acquireRuntime(this)"));
        assert!(activity.contains("androidRuntimeLease.close()"));
        assert!(activity.contains("val reportActivityFinished = !isChangingConfigurations"));
        assert!(activity.contains("reportActivityFinished && releasedActiveRuntime"));
        assert!(activity.contains("WATERUI_ACTIVITY_FINISHED"));

        let application_template = embedded::ANDROID
            .get_file("app/src/main/java/WaterUiApplication.kt.tpl")
            .expect("android WaterUiApplication template must exist")
            .contents_utf8()
            .expect("android WaterUiApplication template must be utf-8");
        let application = render_scaffold_template(
            TemplateNamespace::Android,
            std::path::Path::new("app/src/main/java/WaterUiApplication.kt.tpl"),
            application_template,
            &ctx,
        )
        .expect("android WaterUiApplication render");

        assert!(application.starts_with("package com.example.test"));
        assert!(application.contains("activeRuntime?.let { previous ->"));
        assert!(application.contains("releaseWaterUiRuntime(previous.owner)"));
        assert!(application.contains("bootstrapWaterUiRuntime(activity)"));
        assert!(application.contains("if (runtime.generation != generation) return false"));
        assert!(application.contains("return application.releaseRuntime(generation)"));
        assert!(application.contains("Application(), WaterUiRuntimeOwner"));
        assert!(application.contains("processEnvironment = WuiEnvironment.create()"));
        assert!(application.contains("createWaterUiEnvironment(): WuiEnvironment"));
        assert!(application.contains("}.clone()"));

        let manifest_template = embedded::ANDROID
            .get_file("app/src/main/AndroidManifest.xml.tpl")
            .expect("android manifest template must exist")
            .contents_utf8()
            .expect("android manifest template must be utf-8");
        let manifest = render_scaffold_template(
            TemplateNamespace::Android,
            std::path::Path::new("app/src/main/AndroidManifest.xml.tpl"),
            manifest_template,
            &ctx,
        )
        .expect("android manifest render");

        assert!(manifest.contains("android:name=\".WaterUiApplication\""));
        assert!(manifest.contains("android:launchMode=\"singleTask\""));
    }

    #[test]
    fn gtk4_scaffold_uses_embedded_workspace_version() {
        let ctx = app_ctx();
        let tempdir = tempdir().expect("temporary gtk scaffold dir");

        smol::block_on(crate::templates::gtk4::scaffold(
            tempdir.path(),
            &ctx,
            "waterui-test-gtk",
        ))
        .expect("gtk4 scaffold should succeed");

        let cargo_toml = std::fs::read_to_string(tempdir.path().join("Cargo.toml"))
            .expect("gtk4 Cargo.toml should be written");
        assert!(cargo_toml.contains(&format!("version = \"{GTK_BACKEND_VERSION}\"")));
        assert!(!cargo_toml.contains("webview-default"));
    }

    #[test]
    fn generated_native_backends_only_bridge_the_platform_engine_when_no_engine_is_linked() {
        // No engine crate in the graph: the backend bridges what the platform
        // gives it.
        let gtk_ctx = app_ctx().with_webview_enabled(true);
        let tempdir = tempdir().expect("temporary gtk webview scaffold dir");
        smol::block_on(crate::templates::gtk4::scaffold(
            tempdir.path(),
            &gtk_ctx,
            "waterui-test-gtk",
        ))
        .expect("gtk4 webview scaffold should succeed");
        let gtk_manifest = std::fs::read_to_string(tempdir.path().join("Cargo.toml"))
            .expect("gtk4 Cargo.toml should be written");
        assert!(gtk_manifest.contains("features = [\"webview-system\"]"));

        // An application that linked its own engine draws through that, so the
        // backend compiles no web engine at all.
        let gtk_wpe_ctx = app_ctx()
            .with_webview_enabled(true)
            .with_browser_engine(Some(ResolvedWebViewBackend::Wpe));
        let gtk_wpe_manifest =
            crate::templates::gtk4::rendered_outputs(&gtk_wpe_ctx, "waterui-test-gtk-wpe")
                .expect("GTK WPE outputs should render")
                .into_iter()
                .find_map(|(path, content)| {
                    (path == std::path::Path::new("Cargo.toml"))
                        .then(|| String::from_utf8(content).expect("Cargo.toml must be UTF-8"))
                })
                .expect("GTK WPE Cargo.toml output should exist");
        assert!(!gtk_wpe_manifest.contains("webview-system"));

        let hydrolysis_ctx = app_ctx()
            .with_webview_enabled(true)
            .with_browser_engine(Some(ResolvedWebViewBackend::Cef));
        let cargo_toml = crate::templates::hydrolysis::rendered_outputs(
            &hydrolysis_ctx,
            "waterui-test-hydrolysis",
        )
        .expect("hydrolysis outputs should render")
        .into_iter()
        .find_map(|(path, content)| {
            (path == std::path::Path::new("Cargo.toml"))
                .then(|| String::from_utf8(content).expect("Cargo.toml must be UTF-8"))
        })
        .expect("hydrolysis Cargo.toml output should exist");
        let manifest = cargo_toml
            .parse::<toml::Table>()
            .expect("hydrolysis Cargo.toml should parse");
        let native_dependencies =
            &manifest["target"]["cfg(not(target_arch = \"wasm32\"))"]["dependencies"];
        assert_eq!(
            native_dependencies["waterui-preview"]["version"].as_str(),
            Some(PREVIEW_VERSION),
        );
        assert_eq!(
            native_dependencies["waterui-preview-protocol"]["version"].as_str(),
            Some(PREVIEW_PROTOCOL_VERSION),
        );
        // Each of these is a separately versioned package. Borrowing a sibling's
        // constant reads fine while the numbers happen to coincide and emits an
        // unresolvable requirement the moment one of them bumps on its own.
        assert_eq!(
            native_dependencies["waterui-core"]["version"].as_str(),
            Some(WATERUI_CORE_VERSION),
        );
        assert_eq!(
            native_dependencies["hydrolysis-m3"]["version"].as_str(),
            Some(HYDROLYSIS_M3_VERSION),
        );
        // The subprocess helper dispatches into Chromium directly, so the
        // generated crate depends on the engine the application chose.
        assert_eq!(
            native_dependencies["waterui-browser-cef"]["version"].as_str(),
            Some(WATERUI_BROWSER_CEF_VERSION),
        );
        let features = native_dependencies["hydrolysis"]["features"]
            .as_array()
            .expect("hydrolysis dependency features should be an array")
            .iter()
            .map(|feature| feature.as_str().expect("feature should be a string"))
            .collect::<Vec<_>>();
        assert_eq!(features, ["winit"]);
        assert_eq!(manifest["package"]["autobins"].as_bool(), Some(false));
        let bins = manifest["bin"]
            .as_array()
            .expect("CEF Hydrolysis manifest should declare binaries");
        assert!(bins.iter().any(|bin| {
            bin["name"].as_str() == Some("waterui-cef-helper")
                && bin["path"].as_str() == Some("src/bin/waterui-cef-helper.rs")
        }));
    }

    #[test]
    fn preview_scaffold_uses_embedded_workspace_version() {
        let tempdir = tempdir().expect("temporary preview scaffold dir");
        let ctx = app_ctx()
            .with_preview_runtime_features(vec!["dynamic_linking".to_string(), "gpu".to_string()])
            .with_preview_app_dependency(
                CrateName::try_from("preview_test_app").expect("test crate name must be valid"),
                tempdir.path().join("app"),
            );

        smol::block_on(crate::templates::preview::scaffold(tempdir.path(), &ctx))
            .expect("preview scaffold should succeed");

        let cargo_toml = std::fs::read_to_string(tempdir.path().join("Cargo.toml"))
            .expect("preview Cargo.toml should be written");
        assert!(cargo_toml.contains(&format!("version = \"{PREVIEW_VERSION}\"")));
        assert!(cargo_toml.contains("default-features = false"));
        let manifest = cargo_toml
            .parse::<toml::Table>()
            .expect("preview Cargo.toml should parse");
        let dev_features = manifest["features"]["dev"]
            .as_array()
            .expect("preview dev feature should be an array")
            .iter()
            .map(|feature| feature.as_str().expect("feature should be a string"))
            .collect::<Vec<_>>();
        assert_eq!(dev_features, ["waterui/dynamic_linking", "waterui/gpu"]);
        assert!(cargo_toml.contains("package = \"preview_test_app\""));
        assert!(cargo_toml.contains("features = [\"dev\"]"));

        let lib_rs = std::fs::read_to_string(tempdir.path().join("src/lib.rs"))
            .expect("preview lib.rs should be written");
        assert!(!lib_rs.contains("waterui_ffi::export!()"));
    }

    #[test]
    fn ffi_scaffold_resolves_waterui_ffi_from_playground_cache_path() {
        let tempdir = tempdir().expect("temporary ffi scaffold dir");
        let project_root = tempdir.path().join("playground");
        let ffi_dir = tempdir
            .path()
            .join("cache")
            .join("managed_backends")
            .join("ffi");
        let ctx = ctx(
            Some(PathBuf::from("../waterui")),
            Some(ffi_dir.clone()),
            Some(project_root.clone()),
            crate::project::PackageType::Playground,
        );

        smol::block_on(crate::templates::ffi::scaffold(
            &ffi_dir,
            &ctx,
            "playground-ffi",
        ))
        .expect("ffi scaffold should succeed");

        let cargo_toml = std::fs::read_to_string(ffi_dir.join("Cargo.toml"))
            .expect("ffi Cargo.toml should be written");
        let expected_ffi_path = pathdiff::diff_paths(project_root.join("../waterui/ffi"), &ffi_dir)
            .expect("expected waterui ffi dependency diff path");
        let expected_ffi_path = normalize_path_for_config(&expected_ffi_path);

        assert!(cargo_toml.contains(&format!("path = \"{expected_ffi_path}\"")));
        assert!(cargo_toml.contains("dev = [\"waterui_test/dev\"]"));
        // This crate roots the workspace preview modules join, so a module and the
        // runtime it is loaded into share one Cargo resolution. With none on disk
        // the workspace is empty — never a `modules/*` glob, which Cargo reads as
        // a literal path and rejects when it matches nothing.
        assert!(
            cargo_toml.contains("[workspace]"),
            "generated FFI crate must root the preview module workspace"
        );
        assert!(
            !cargo_toml.contains(crate::templates::PREVIEW_MODULES_DIR),
            "an FFI crate with no preview module on disk must declare no members"
        );
        let manifest = cargo_toml
            .parse::<toml::Table>()
            .expect("ffi Cargo.toml should parse");
        assert_eq!(
            manifest["dependencies"]["waterui-ffi"]["default-features"].as_bool(),
            Some(false)
        );
        assert_eq!(manifest["package"]["autobins"].as_bool(), Some(false));
        assert!(manifest.get("bin").is_none());
    }

    #[test]
    fn ffi_scaffold_declares_minimal_cef_helper_for_chromium() {
        let tempdir = tempdir().expect("temporary ffi scaffold dir");
        let ffi_dir = tempdir.path().join("managed_backends/ffi");
        let ctx = app_ctx()
            .with_backend_project_path(ffi_dir.clone())
            .with_project_root_path(tempdir.path().to_path_buf())
            .with_chromium_enabled(true)
            .with_browser_engine(Some(ResolvedWebViewBackend::Cef));

        smol::block_on(crate::templates::ffi::scaffold(
            &ffi_dir,
            &ctx,
            "chromium-ffi",
        ))
        .expect("Chromium ffi scaffold should succeed");

        let manifest = std::fs::read_to_string(ffi_dir.join("Cargo.toml"))
            .expect("ffi Cargo.toml should be written")
            .parse::<toml::Table>()
            .expect("ffi Cargo.toml should parse");
        let bins = manifest["bin"]
            .as_array()
            .expect("CEF FFI companion should declare a helper binary");
        assert_eq!(bins.len(), 1);
        assert_eq!(bins[0]["name"].as_str(), Some("waterui-cef-helper"));
        assert_eq!(
            bins[0]["path"].as_str(),
            Some("src/bin/waterui-cef-helper.rs")
        );

        let helper = std::fs::read_to_string(ffi_dir.join("src/bin/waterui-cef-helper.rs"))
            .expect("CEF helper source should be written");
        assert!(helper.contains("waterui_cef_run_packaged_subprocess"));
    }

    #[test]
    fn preview_ffi_scaffold_emits_dylib_only_wrapper() {
        let tempdir = tempdir().expect("temporary preview ffi scaffold dir");
        let project_root = tempdir.path().join("playground");
        let preview_ffi_dir = tempdir
            .path()
            .join("cache")
            .join("managed_backends")
            .join("preview_ffi");
        let workspace_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .expect("CLI crate should be inside the WaterUI workspace")
            .to_path_buf();
        let ctx = ctx(
            Some(workspace_root),
            Some(preview_ffi_dir.clone()),
            Some(project_root),
            crate::project::PackageType::Playground,
        );

        smol::block_on(crate::templates::preview_ffi::scaffold(
            &preview_ffi_dir,
            &ctx,
            "playground-preview-ffi",
        ))
        .expect("preview ffi scaffold should succeed");

        let cargo_toml = std::fs::read_to_string(preview_ffi_dir.join("Cargo.toml"))
            .expect("preview ffi Cargo.toml should be written");
        let manifest = cargo_toml
            .parse::<toml::Table>()
            .expect("preview ffi Cargo.toml should parse");
        for (feature, ffi_feature) in [
            (preview_ffi::APPLE_ABI_FEATURE, "waterui-ffi/c-api"),
            (preview_ffi::ANDROID_ABI_FEATURE, "waterui-ffi/android-jni"),
        ] {
            let features = manifest["features"][feature]
                .as_array()
                .expect("platform preview ABI feature should be an array")
                .iter()
                .map(|feature| feature.as_str().expect("feature should be a string"))
                .collect::<Vec<_>>();
            assert_eq!(
                features,
                ["dep:waterui-ffi", ffi_feature, "dep:waterui-preview"]
            );
        }
        assert_eq!(
            manifest["dependencies"]["waterui-ffi"]["optional"].as_bool(),
            Some(true)
        );
        assert_eq!(
            manifest["dependencies"]["waterui-ffi"]["default-features"].as_bool(),
            Some(false)
        );
        // The module is a member of the support runtime's workspace, never a
        // workspace of its own: one Cargo resolution is what makes the module and
        // the runtime it is loaded into agree on the `-C metadata` hash that ends
        // up in every symbol. Profiles and `[patch]` belong to that root.
        assert!(
            !manifest.contains_key("workspace"),
            "preview module must not root its own workspace"
        );
        assert!(
            !manifest.contains_key("patch"),
            "preview module must inherit `[patch]` from the workspace root"
        );
        assert!(
            !manifest.contains_key("profile"),
            "preview module must inherit profiles from the workspace root"
        );
        assert_eq!(
            manifest["dependencies"]["waterui-preview"]["optional"].as_bool(),
            Some(true)
        );
        // Assert on the parsed manifest, not on substrings of the whole file: the file
        // embeds absolute dependency paths, so a checkout living in a directory whose
        // name happens to contain "rlib" or "cdylib" would fail a substring check.
        let crate_types = manifest["lib"]["crate-type"]
            .as_array()
            .expect("crate-type should be an array")
            .iter()
            .map(|value| value.as_str().expect("crate type should be a string"))
            .collect::<Vec<_>>();
        assert_eq!(crate_types, ["dylib"]);
        assert_eq!(
            manifest["dependencies"]["waterui_test"]["features"]
                .as_array()
                .expect("app dependency features should be an array")
                .iter()
                .map(|value| value.as_str().expect("feature should be a string"))
                .collect::<Vec<_>>(),
            ["dev"]
        );
        assert!(manifest["dependencies"].get("waterui").is_none());
    }

    #[test]
    fn generated_ffi_manifest_emits_only_linked_crate_types() {
        let temp = tempfile::tempdir().expect("temp dir");
        let project_root = temp.path().join("project");
        let ffi_dir = temp
            .path()
            .join("cache")
            .join("managed_backends")
            .join("ffi");
        let ctx = ctx(
            Some(PathBuf::from("../waterui")),
            Some(ffi_dir.clone()),
            Some(project_root),
            crate::project::PackageType::Playground,
        );

        smol::block_on(crate::templates::ffi::scaffold(
            &ffi_dir,
            &ctx,
            "playground-ffi",
        ))
        .expect("ffi scaffold should succeed");

        let manifest = std::fs::read_to_string(ffi_dir.join("Cargo.toml"))
            .expect("ffi Cargo.toml should be written")
            .parse::<toml::Table>()
            .expect("ffi Cargo.toml should parse");
        let crate_types = manifest["lib"]["crate-type"]
            .as_array()
            .expect("crate-type should be an array")
            .iter()
            .map(|value| value.as_str().expect("crate type should be a string"))
            .collect::<Vec<_>>();

        // Apple links the staticlib, Android loads the cdylib, and nothing anywhere
        // consumes an rlib of this crate.
        assert_eq!(crate_types, ["staticlib", "cdylib"]);
    }

    #[test]
    fn generated_manifests_keep_debug_info_off_for_dependencies() {
        let temp = tempfile::tempdir().expect("temp dir");
        let project_root = temp.path().join("project");
        let ffi_dir = temp
            .path()
            .join("cache")
            .join("managed_backends")
            .join("ffi");
        let ctx = ctx(
            Some(PathBuf::from("../waterui")),
            Some(ffi_dir.clone()),
            Some(project_root),
            crate::project::PackageType::Playground,
        );

        smol::block_on(crate::templates::ffi::scaffold(
            &ffi_dir,
            &ctx,
            "playground-ffi",
        ))
        .expect("ffi scaffold should succeed");

        let manifest = std::fs::read_to_string(ffi_dir.join("Cargo.toml"))
            .expect("ffi Cargo.toml should be written")
            .parse::<toml::Table>()
            .expect("ffi Cargo.toml should parse");
        let dev = &manifest["profile"]["dev"];

        // Generated crates declare `[workspace]`, so they inherit no profile and have
        // to carry this themselves.
        assert_eq!(dev["debug"].as_integer(), Some(1));
        assert_eq!(dev["package"]["*"]["debug"].as_bool(), Some(false));
        assert_eq!(dev["package"]["*"]["opt-level"].as_integer(), Some(2));
    }

    #[test]
    fn playground_android_manifest_enables_picture_in_picture_by_default() {
        let ctx = playground_ctx();
        let template = embedded::ANDROID
            .get_file("app/src/main/AndroidManifest.xml.tpl")
            .expect("android manifest template must exist")
            .contents_utf8()
            .expect("android manifest template must be utf-8");

        let rendered = render_scaffold_template(
            TemplateNamespace::Android,
            std::path::Path::new("app/src/main/AndroidManifest.xml.tpl"),
            template,
            &ctx,
        )
        .expect("playground android manifest render");

        assert!(rendered.contains("android:resizeableActivity=\"true\""));
        assert!(rendered.contains("android:supportsPictureInPicture=\"true\""));
    }

    #[test]
    fn playground_apple_project_enables_picture_in_picture_background_mode_by_default() {
        let ctx = playground_ctx();
        let template = embedded::APPLE
            .get_file("AppName.xcodeproj/project.pbxproj.tpl")
            .expect("apple project template must exist")
            .contents_utf8()
            .expect("apple project template must be utf-8");

        let rendered = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("AppName.xcodeproj/project.pbxproj.tpl"),
            template,
            &ctx,
        )
        .expect("playground apple project render");

        assert!(
            rendered.contains("\"INFOPLIST_KEY_UIBackgroundModes[sdk=iphoneos*][0]\" = audio;")
        );
        assert!(
            rendered
                .contains("\"INFOPLIST_KEY_UIBackgroundModes[sdk=iphonesimulator*][0]\" = audio;")
        );
        // See the app-mode test: the project never names the Rust library, because its
        // shape is chosen per build and injected as a linker flag.
        assert!(!rendered.contains("libwaterui_app"));
    }

    #[test]
    fn playground_apple_build_script_skips_direct_rust_build() {
        let ctx = playground_ctx();
        let template = embedded::APPLE
            .get_file("build-rust.sh.tpl")
            .expect("apple build script template must exist")
            .contents_utf8()
            .expect("apple build script template must be utf-8");

        let rendered = render_scaffold_template(
            TemplateNamespace::Apple,
            std::path::Path::new("build-rust.sh.tpl"),
            template,
            &ctx,
        )
        .expect("playground apple build script render");

        assert!(rendered.contains("playground support app is managed by water run/package"));
        assert!(rendered.contains("if [ \"true\" = \"true\" ]; then"));
    }
}

/// Scaffold a directory from embedded templates (non-recursive, uses stack).
async fn scaffold_dir(
    namespace: TemplateNamespace,
    embedded_dir: &Dir<'_>,
    base_dir: &Path,
    ctx: &TemplateContext,
) -> io::Result<()> {
    // Use a stack to avoid async recursion (which requires boxing)
    let mut dirs_to_process = vec![embedded_dir];

    while let Some(current_dir) = dirs_to_process.pop() {
        // Process all files in this directory
        for file in current_dir.files() {
            let relative_path = file.path();

            // Determine if this is a template file and compute destination path
            let is_template = relative_path
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| ext == "tpl");

            let dest_path = if is_template {
                // Remove .tpl extension and transform path
                let without_tpl = relative_path.with_extension("");
                ctx.transform_path(&without_tpl)
            } else {
                // Binary file - just transform the path
                ctx.transform_path(relative_path)
            };

            let full_dest = base_dir.join(&dest_path);

            // Create parent directories
            if let Some(parent) = full_dest.parent() {
                fs::create_dir_all(parent).await?;
            }

            // Write file content
            if is_template {
                // Template file - render content
                let content = file
                    .contents_utf8()
                    .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))?;
                let rendered = render_scaffold_template(namespace, relative_path, content, ctx)?;
                write_file_if_changed(&full_dest, rendered.as_bytes()).await?;
            } else {
                // Binary file - copy as-is
                write_file_if_changed(&full_dest, file.contents()).await?;
            }
        }

        // Add subdirectories to the stack
        for subdir in current_dir.dirs() {
            dirs_to_process.push(subdir);
        }
    }

    Ok(())
}

/// Render every file of an embedded scaffold directory to its destination
/// path and content, without touching the filesystem.
///
/// This is the same rendering [`scaffold_dir`] performs, exposed so callers
/// can compare a generated backend against what the current templates would
/// produce (managed backends regenerate exactly when the rendering differs).
fn render_dir_outputs(
    namespace: TemplateNamespace,
    embedded_dir: &Dir<'_>,
    ctx: &TemplateContext,
) -> io::Result<Vec<(PathBuf, Vec<u8>)>> {
    let mut outputs = Vec::new();
    let mut dirs_to_process = vec![embedded_dir];
    while let Some(current_dir) = dirs_to_process.pop() {
        for file in current_dir.files() {
            let relative_path = file.path();
            let is_template = relative_path
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| ext == "tpl");
            if is_template {
                let dest_path = ctx.transform_path(&relative_path.with_extension(""));
                let content = file
                    .contents_utf8()
                    .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))?;
                let rendered = render_scaffold_template(namespace, relative_path, content, ctx)?;
                outputs.push((dest_path, rendered.into_bytes()));
            } else {
                let dest_path = ctx.transform_path(relative_path);
                outputs.push((dest_path, file.contents().to_vec()));
            }
        }
        for subdir in current_dir.dirs() {
            dirs_to_process.push(subdir);
        }
    }
    Ok(outputs)
}

async fn write_file_if_changed(path: &Path, contents: &[u8]) -> io::Result<()> {
    match fs::read(path).await {
        Ok(existing) if existing == contents => return Ok(()),
        Ok(_) | Err(_) => {}
    }

    fs::write(path, contents).await
}

#[derive(serde::Serialize)]
struct SupportCargoManifest {
    package: SupportPackageSection,
    lib: SupportLibSection,
    profile: cargo_toml::Profiles,
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    features: std::collections::BTreeMap<String, Vec<String>>,
    dependencies: std::collections::BTreeMap<String, SupportDependencyValue>,
    workspace: SupportWorkspaceSection,
    /// `[patch]` inherited from the runtime's own workspace.
    ///
    /// Declaring `[workspace]` makes this crate its own workspace root, and
    /// Cargo only honours `[patch]` from the root of the workspace being built.
    /// A support app that skipped these resolved the unpatched crates.io
    /// version of every forked dependency, so it linked a different runtime
    /// than the module it loads — and the module failed to `dlopen` against
    /// symbols whose crate hashes no longer matched.
    #[serde(skip_serializing_if = "cargo_toml::PatchSet::is_empty")]
    patch: cargo_toml::PatchSet,
}

#[derive(serde::Serialize)]
struct SupportPackageSection {
    name: String,
    version: String,
    edition: String,
}

#[derive(serde::Serialize)]
struct SupportLibSection {
    #[serde(rename = "crate-type")]
    crate_type: Vec<String>,
}

#[derive(serde::Serialize)]
struct SupportWorkspaceSection {}

#[derive(serde::Serialize)]
#[serde(untagged)]
enum SupportDependencyValue {
    Simple(String),
    Detailed(SupportDependencyDetail),
}

#[derive(serde::Serialize)]
struct SupportDependencyDetail {
    #[serde(skip_serializing_if = "Option::is_none")]
    package: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    #[serde(rename = "default-features", skip_serializing_if = "Option::is_none")]
    default_features: Option<bool>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    features: Vec<String>,
}

/// Build the `[profile.dev]` section every generated crate carries.
///
/// Generated crates declare `[workspace]`, which makes each of them its own
/// workspace root: they inherit nothing from the repository or the user's project,
/// so whatever profile they should build under has to be written into them here.
/// Without this they defaulted to full debug info for the entire dependency graph,
/// which is the bulk of both the link time and the artifact size of a debug build,
/// and none of which anyone steps through — the `WaterUI` runtime is a dependency of
/// these crates, not the code under debug.
///
/// Dependencies are also compiled with optimizations: the rendering stack
/// (vello, wgpu, parley) is a dependency of every generated crate and sits on
/// every frame's hot path, and at `opt-level` 0 its per-frame encode-and-submit
/// alone costs several milliseconds — a debug `water run` visibly drops frames
/// while scrolling. The generated crate itself stays unoptimized and fully
/// debuggable.
///
/// Line tables are kept for the generated crate itself so panics still resolve to
/// file and line.
fn generated_dev_profile() -> cargo_toml::Profiles {
    let mut dev = cargo_toml::Profile {
        debug: Some(cargo_toml::DebugSetting::Lines),
        ..Default::default()
    };
    let mut dependency_override = toml::value::Table::new();
    dependency_override.insert("debug".to_string(), toml::Value::Boolean(false));
    dependency_override.insert("opt-level".to_string(), toml::Value::Integer(2));
    dev.package
        .insert("*".to_string(), toml::Value::Table(dependency_override));

    cargo_toml::Profiles {
        dev: Some(dev),
        ..Default::default()
    }
}

/// Serialized form of [`generated_dev_profile`], hashed into support-app
/// template fingerprints: the scaffold `Cargo.toml` is generated
/// programmatically rather than from an embedded template file, so cached
/// scaffolds (preview/inspector support apps) would otherwise keep a stale
/// profile when the generated section changes.
fn generated_dev_profile_fingerprint() -> String {
    toml::to_string(&generated_dev_profile()).expect("generated dev profile must serialize to TOML")
}

async fn write_support_cargo_toml(
    base_dir: &Path,
    crate_name: &str,
    features: std::collections::BTreeMap<String, Vec<String>>,
    dependencies: std::collections::BTreeMap<String, SupportDependencyValue>,
    runtime_root: Option<&Path>,
) -> io::Result<()> {
    let patch = match runtime_root {
        Some(root) => {
            let root = root.to_path_buf();
            smol::unblock(move || collect_workspace_patches(&root)).await?
        }
        None => cargo_toml::PatchSet::default(),
    };
    let manifest = SupportCargoManifest {
        package: SupportPackageSection {
            name: crate_name.to_string(),
            version: "0.1.0".to_string(),
            edition: "2024".to_string(),
        },
        lib: SupportLibSection {
            // A support app's own crate is only ever consumed as a Rust dependency of
            // the generated FFI crate, and that FFI crate is what the platform links.
            // Emitting `staticlib`/`cdylib` here archived and relinked the entire
            // dependency graph twice more for products nothing ever loads.
            crate_type: vec!["rlib".to_string()],
        },
        profile: generated_dev_profile(),
        features,
        dependencies,
        workspace: SupportWorkspaceSection {},
        patch,
    };

    let toml_string = toml::to_string_pretty(&manifest)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    fs::create_dir_all(base_dir).await?;
    write_file_if_changed(&base_dir.join("Cargo.toml"), toml_string.as_bytes()).await?;
    Ok(())
}

#[derive(Clone, Copy)]
enum NativeBackendDependencyPathKind<'a> {
    WateruiRoot,
    WorkspaceSubdir(&'a str),
    BackendsSubdir(&'a str),
}

#[derive(Clone, Copy)]
struct NativeBackendDependencySpec<'a> {
    crate_name: &'a str,
    version: &'a str,
    features: &'a [&'a str],
    path_kind: Option<NativeBackendDependencyPathKind<'a>>,
}

impl<'a> NativeBackendDependencySpec<'a> {
    const fn new(
        crate_name: &'a str,
        version: &'a str,
        features: &'a [&'a str],
        path_kind: Option<NativeBackendDependencyPathKind<'a>>,
    ) -> Self {
        Self {
            crate_name,
            version,
            features,
            path_kind,
        }
    }
}

fn compute_native_backend_dependency_path(
    ctx: &TemplateContext,
    waterui_path: &Path,
    path_kind: NativeBackendDependencyPathKind<'_>,
) -> String {
    if waterui_path.is_absolute() {
        let absolute_path = match path_kind {
            NativeBackendDependencyPathKind::WateruiRoot => waterui_path.to_path_buf(),
            NativeBackendDependencyPathKind::WorkspaceSubdir(subdir) => waterui_path.join(subdir),
            NativeBackendDependencyPathKind::BackendsSubdir(subdir) => {
                waterui_path.join("backends").join(subdir)
            }
        };
        return normalize_path_for_config(&absolute_path);
    }

    let project_relative_root = PathBuf::from(ctx.project_root_relative_path());
    let relative_path = match path_kind {
        NativeBackendDependencyPathKind::WateruiRoot => project_relative_root.join(waterui_path),
        NativeBackendDependencyPathKind::WorkspaceSubdir(subdir) => {
            project_relative_root.join(waterui_path).join(subdir)
        }
        NativeBackendDependencyPathKind::BackendsSubdir(subdir) => project_relative_root
            .join(waterui_path)
            .join("backends")
            .join(subdir),
    };
    normalize_path_for_config(&relative_path)
}

async fn write_native_backend_bin_cargo_toml(
    base_dir: &Path,
    ctx: &TemplateContext,
    package_name: &str,
    dependencies: &[NativeBackendDependencySpec<'_>],
) -> io::Result<()> {
    let toml_string = render_native_backend_bin_cargo_toml(ctx, package_name, dependencies)?;
    fs::create_dir_all(base_dir).await?;
    write_file_if_changed(&base_dir.join("Cargo.toml"), toml_string.as_bytes()).await
}

fn render_native_backend_bin_cargo_toml(
    ctx: &TemplateContext,
    package_name: &str,
    dependencies: &[NativeBackendDependencySpec<'_>],
) -> io::Result<String> {
    use cargo_toml::{Dependency, DependencyDetail, Manifest, Package, Workspace};

    let mut manifest = Manifest::<()>::default();
    let mut package = Package::new(package_name.to_string(), cargo_semver("0.1.0"));
    package.edition = cargo_toml::Inheritable::Set(cargo_toml::Edition::E2024);
    manifest.package = Some(package);
    manifest.profile = generated_dev_profile();

    manifest.dependencies.insert(
        ctx.crate_name.to_string(),
        Dependency::Detailed(Box::new(DependencyDetail {
            path: Some(ctx.project_root_relative_path()),
            ..Default::default()
        })),
    );

    for dependency in dependencies {
        let features = dependency
            .features
            .iter()
            .map(std::string::ToString::to_string)
            .collect::<Vec<_>>();

        if let Some(waterui_path) = &ctx.waterui_path
            && let Some(path_kind) = dependency.path_kind
        {
            let dependency_path =
                compute_native_backend_dependency_path(ctx, waterui_path, path_kind);
            manifest.dependencies.insert(
                dependency.crate_name.to_string(),
                Dependency::Detailed(Box::new(DependencyDetail {
                    path: Some(dependency_path),
                    features,
                    ..Default::default()
                })),
            );
            continue;
        }

        manifest.dependencies.insert(
            dependency.crate_name.to_string(),
            Dependency::Detailed(Box::new(DependencyDetail {
                version: Some(cargo_version_req(dependency.version)),
                features,
                ..Default::default()
            })),
        );
    }

    manifest.workspace = Some(Workspace::default());

    toml::to_string_pretty(&manifest)
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}

fn dependency_path(path: &Path) -> SupportDependencyValue {
    SupportDependencyValue::Detailed(SupportDependencyDetail {
        package: None,
        version: None,
        path: Some(normalize_path_for_config(path)),
        default_features: None,
        features: Vec::new(),
    })
}

fn dependency_version(version: &str) -> SupportDependencyValue {
    SupportDependencyValue::Simple(version.to_string())
}

#[derive(serde::Serialize)]
struct GeneratedCargoManifest<T> {
    package: GeneratedPackageSection,
    lib: GeneratedLibSection,
    #[serde(rename = "bin", skip_serializing_if = "Vec::is_empty", default)]
    bins: Vec<GeneratedBinSection>,
    /// Every generated crate declares `[workspace]` and therefore inherits no
    /// profile from the repository or the user's project — see
    /// [`generated_dev_profile`] for why the dev profile has to be carried
    /// here. Backend scaffolds that omitted this built the entire rendering
    /// stack at `opt-level` 0 with full debug info, which is what made debug
    /// `water run` drop frames.
    profile: cargo_toml::Profiles,
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty", default)]
    features: std::collections::BTreeMap<String, Vec<String>>,
    dependencies: std::collections::BTreeMap<String, T>,
    #[serde(
        rename = "build-dependencies",
        skip_serializing_if = "std::collections::BTreeMap::is_empty",
        default
    )]
    build_dependencies: std::collections::BTreeMap<String, T>,
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty", default)]
    target: std::collections::BTreeMap<String, GeneratedTargetSection<T>>,
    workspace: GeneratedWorkspaceSection,
    /// `[patch]` inherited from the runtime's own workspace.
    ///
    /// Declaring `[workspace]` makes a generated backend crate its own
    /// workspace root, and Cargo only honours `[patch]` from the root of the
    /// workspace being built. A backend crate that skips these silently
    /// resolves the unpatched crates.io version of every forked dependency
    /// (`vello_hybrid` above all) and fails to unify types with the
    /// workspace-built crates it links.
    #[serde(skip_serializing_if = "cargo_toml::PatchSet::is_empty", default)]
    patch: cargo_toml::PatchSet,
}

#[derive(serde::Serialize)]
struct GeneratedPackageSection {
    name: String,
    version: String,
    edition: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    autobins: Option<bool>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    authors: Vec<String>,
}

#[derive(serde::Serialize)]
struct GeneratedLibSection {
    #[serde(rename = "crate-type")]
    crate_type: Vec<String>,
}

#[derive(serde::Serialize)]
struct GeneratedBinSection {
    name: String,
    path: String,
}

#[derive(serde::Serialize)]
struct GeneratedTargetSection<T> {
    dependencies: std::collections::BTreeMap<String, T>,
}

#[derive(serde::Serialize)]
struct GeneratedWorkspaceSection {}

#[derive(serde::Serialize)]
#[serde(untagged)]
enum GeneratedDependencyValue {
    Simple(String),
    Detailed(GeneratedDependencyDetail),
}

#[derive(serde::Serialize, Clone)]
struct GeneratedDependencyDetail {
    #[serde(skip_serializing_if = "Option::is_none")]
    version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    #[serde(rename = "default-features", skip_serializing_if = "Option::is_none")]
    default_features: Option<bool>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    features: Vec<String>,
}

impl GeneratedDependencyValue {
    const fn detailed(detail: GeneratedDependencyDetail) -> Self {
        Self::Detailed(detail)
    }

    fn simple(version: &str) -> Self {
        Self::Simple(version.to_string())
    }
}

impl GeneratedDependencyDetail {
    fn path(path: &Path) -> Self {
        Self {
            version: None,
            path: Some(normalize_path_for_config(path)),
            default_features: None,
            features: Vec::new(),
        }
    }

    fn version(version: &str) -> Self {
        Self {
            version: Some(version.to_string()),
            path: None,
            default_features: None,
            features: Vec::new(),
        }
    }

    const fn with_default_features(mut self, default_features: bool) -> Self {
        self.default_features = Some(default_features);
        self
    }

    fn with_features(mut self, features: &[&str]) -> Self {
        self.features = features
            .iter()
            .map(|feature| (*feature).to_string())
            .collect();
        self
    }
}

fn generated_package(name: &str, authors: Vec<String>) -> GeneratedPackageSection {
    GeneratedPackageSection {
        name: name.to_string(),
        version: "0.1.0".to_string(),
        edition: "2024".to_string(),
        autobins: None,
        authors,
    }
}

fn generated_lib(crate_types: &[&str]) -> GeneratedLibSection {
    GeneratedLibSection {
        crate_type: crate_types
            .iter()
            .map(|crate_type| (*crate_type).to_string())
            .collect(),
    }
}

fn generated_dependency_from_spec(
    ctx: &TemplateContext,
    spec: NativeBackendDependencySpec<'_>,
) -> GeneratedDependencyDetail {
    let detail = if let Some(waterui_path) = &ctx.waterui_path
        && let Some(path_kind) = spec.path_kind
    {
        GeneratedDependencyDetail {
            version: None,
            path: Some(compute_native_backend_dependency_path(
                ctx,
                waterui_path,
                path_kind,
            )),
            default_features: None,
            features: Vec::new(),
        }
    } else {
        GeneratedDependencyDetail::version(spec.version)
    };

    detail.with_features(spec.features)
}

fn render_generated_cargo_toml<T: serde::Serialize>(
    manifest: &GeneratedCargoManifest<T>,
) -> io::Result<String> {
    toml::to_string_pretty(manifest)
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}

async fn write_generated_cargo_toml(base_dir: &Path, toml_string: String) -> io::Result<()> {
    fs::create_dir_all(base_dir).await?;
    write_file_if_changed(&base_dir.join("Cargo.toml"), toml_string.as_bytes()).await
}

/// Apple backend templates.
pub mod apple {
    use super::{Path, TemplateContext, TemplateNamespace, embedded, io, scaffold_dir};
    // Only the unix arm below marks the build script executable.
    #[cfg(unix)]
    use super::fs;

    /// Write all Apple templates to the given directory.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        scaffold_dir(TemplateNamespace::Apple, &embedded::APPLE, base_dir, ctx).await?;

        // Make build-rust.sh executable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let script_path = base_dir.join("build-rust.sh");
            if script_path.exists() {
                let mut perms = fs::metadata(&script_path).await?.permissions();
                perms.set_mode(0o755);
                fs::set_permissions(&script_path, perms).await?;
            }
        }

        Ok(())
    }
}

/// Android backend templates.
pub mod android {
    use crate::android::toolchain::AndroidSdk;

    use super::{
        Path, TemplateContext, TemplateNamespace, embedded, fs, io, normalize_path_for_config,
        scaffold_dir, write_file_if_changed,
    };

    /// Write all Android templates to the given directory.
    ///
    /// # Errors
    /// Returns an error if file operations fail.
    pub async fn scaffold(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        scaffold_dir(
            TemplateNamespace::Android,
            &embedded::ANDROID,
            base_dir,
            ctx,
        )
        .await?;

        // Make gradlew executable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let gradlew_path = base_dir.join("gradlew");
            if gradlew_path.exists() {
                let mut perms = fs::metadata(&gradlew_path).await?.permissions();
                perms.set_mode(0o755);
                fs::set_permissions(&gradlew_path, perms).await?;
            }
        }

        // Create jniLibs directories
        for abi in ["arm64-v8a", "x86_64", "armeabi-v7a", "x86"] {
            let jni_dir = base_dir.join(format!("app/src/main/jniLibs/{abi}"));
            fs::create_dir_all(&jni_dir).await?;
        }

        // Generate local.properties with Android SDK path
        if let Some(sdk_path) = AndroidSdk::detect_path() {
            let local_props = base_dir.join("local.properties");
            let content = format!("sdk.dir={}\n", normalize_path_for_config(&sdk_path));
            write_file_if_changed(&local_props, content.as_bytes()).await?;
        }

        Ok(())
    }
}

/// GTK4 backend templates.
pub mod gtk4 {
    use super::{
        GTK_BACKEND_VERSION, NativeBackendDependencyPathKind, NativeBackendDependencySpec, Path,
        TemplateContext, TemplateNamespace, embedded, io, scaffold_dir,
        write_native_backend_bin_cargo_toml,
    };

    /// Write all GTK4 templates to the given directory.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        // Generate Cargo.toml programmatically
        generate_cargo_toml(base_dir, ctx, package_name).await?;

        // Scaffold remaining template files (main.rs, etc.)
        scaffold_dir(TemplateNamespace::Gtk4, &embedded::GTK4, base_dir, ctx).await
    }

    /// Every file `scaffold` would write, without touching the filesystem.
    ///
    /// # Errors
    ///
    /// Returns an error if template or Cargo manifest rendering fails.
    pub fn rendered_outputs(
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<Vec<(std::path::PathBuf, Vec<u8>)>> {
        let mut outputs = super::render_dir_outputs(TemplateNamespace::Gtk4, &embedded::GTK4, ctx)?;
        let features = ctx
            .webview_backend_feature()
            .into_iter()
            .collect::<Vec<_>>();
        let dependencies = [NativeBackendDependencySpec::new(
            "waterui-gtk",
            GTK_BACKEND_VERSION,
            &features,
            Some(NativeBackendDependencyPathKind::BackendsSubdir("gtk")),
        )];
        outputs.push((
            std::path::PathBuf::from("Cargo.toml"),
            super::render_native_backend_bin_cargo_toml(ctx, package_name, &dependencies)?
                .into_bytes(),
        ));
        Ok(outputs)
    }

    /// Generate `GTK4` `Cargo.toml` programmatically using the `cargo_toml` crate.
    async fn generate_cargo_toml(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        let features = ctx
            .webview_backend_feature()
            .into_iter()
            .collect::<Vec<_>>();
        let dependencies = [NativeBackendDependencySpec::new(
            "waterui-gtk",
            GTK_BACKEND_VERSION,
            &features,
            Some(NativeBackendDependencyPathKind::BackendsSubdir("gtk")),
        )];
        write_native_backend_bin_cargo_toml(base_dir, ctx, package_name, &dependencies).await
    }
}

/// Hydrolysis backend templates.
pub mod hydrolysis {
    use super::{
        GeneratedBinSection, GeneratedCargoManifest, GeneratedDependencyDetail,
        GeneratedDependencyValue, GeneratedTargetSection, GeneratedWorkspaceSection,
        HYDROLYSIS_M3_VERSION, HYDROLYSIS_VERSION, NativeBackendDependencyPathKind,
        NativeBackendDependencySpec, PREVIEW_PROTOCOL_VERSION, PREVIEW_VERSION, Path,
        TemplateContext, TemplateNamespace, WATERUI_BROWSER_CEF_VERSION, WATERUI_CORE_VERSION,
        WATERUI_VERSION, embedded, io, scaffold_dir, write_generated_cargo_toml,
    };
    use std::collections::BTreeMap;

    /// Write all hydrolysis templates to the given directory.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        generate_cargo_toml(base_dir, ctx, package_name).await?;
        scaffold_dir(
            TemplateNamespace::Hydrolysis,
            &embedded::HYDROLYSIS,
            base_dir,
            ctx,
        )
        .await
    }

    /// Every file `scaffold` would write, as backend-relative path and
    /// content, without touching the filesystem.
    ///
    /// # Errors
    ///
    /// Returns an error if template rendering fails.
    pub fn rendered_outputs(
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<Vec<(std::path::PathBuf, Vec<u8>)>> {
        let mut outputs =
            super::render_dir_outputs(TemplateNamespace::Hydrolysis, &embedded::HYDROLYSIS, ctx)?;
        let patch = collect_runtime_patches(ctx)?;
        outputs.push((
            std::path::PathBuf::from("Cargo.toml"),
            super::render_generated_cargo_toml(&generated_manifest(ctx, package_name, patch))?
                .into_bytes(),
        ));
        Ok(outputs)
    }

    /// `[patch]` tables of the workspace the backend builds against, so the
    /// generated crate resolves forked dependencies exactly like the
    /// runtime's own workspace does.
    fn collect_runtime_patches(ctx: &TemplateContext) -> io::Result<cargo_toml::PatchSet> {
        ctx.waterui_workspace_root().map_or_else(
            || Ok(cargo_toml::PatchSet::default()),
            |root| super::collect_workspace_patches(&root),
        )
    }

    fn generated_manifest(
        ctx: &TemplateContext,
        package_name: &str,
        patch: cargo_toml::PatchSet,
    ) -> GeneratedCargoManifest<GeneratedDependencyValue> {
        let mut package = super::generated_package(package_name, Vec::new());
        package.autobins = Some(false);
        let mut bins = vec![GeneratedBinSection {
            name: package_name.to_string(),
            path: "src/main.rs".to_string(),
        }];
        if requires_cef(ctx) {
            bins.push(GeneratedBinSection {
                name: "waterui-cef-helper".to_string(),
                path: "src/bin/waterui-cef-helper.rs".to_string(),
            });
        }
        GeneratedCargoManifest {
            package,
            lib: super::generated_lib(&["cdylib", "rlib"]),
            bins,
            profile: super::generated_dev_profile(),
            features: BTreeMap::from([
                ("waterui-preview-mode".to_string(), Vec::new()),
                ("waterui-preview-test-mode".to_string(), Vec::new()),
            ]),
            dependencies: cargo_dependencies(ctx),
            // The build script embeds the staged Windows icon resource; the
            // crate is a no-op on every other target.
            build_dependencies: BTreeMap::from([(
                "winresource".to_string(),
                GeneratedDependencyValue::Simple("0.1".to_string()),
            )]),
            target: cargo_target_dependencies(ctx),
            workspace: GeneratedWorkspaceSection {},
            patch,
        }
    }

    /// Whether this application's graph links the bundled CEF runtime.
    ///
    /// A packaged CEF application needs a subprocess helper binary, and the
    /// helper needs the engine crate; both follow the application's own
    /// dependencies, never a manifest setting.
    const fn requires_cef(ctx: &TemplateContext) -> bool {
        ctx.cef_runtime_enabled()
    }

    async fn generate_cargo_toml(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        let patch = match ctx.waterui_workspace_root() {
            Some(root) => smol::unblock(move || super::collect_workspace_patches(&root)).await?,
            None => cargo_toml::PatchSet::default(),
        };
        let manifest = generated_manifest(ctx, package_name, patch);
        write_generated_cargo_toml(base_dir, super::render_generated_cargo_toml(&manifest)?).await
    }

    fn cargo_dependencies(ctx: &TemplateContext) -> BTreeMap<String, GeneratedDependencyValue> {
        BTreeMap::from([
            (
                ctx.crate_name.to_string(),
                GeneratedDependencyValue::detailed(GeneratedDependencyDetail {
                    version: None,
                    path: Some(ctx.project_root_relative_path()),
                    default_features: None,
                    features: Vec::new(),
                }),
            ),
            (
                "waterui".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "waterui",
                            WATERUI_VERSION,
                            // Hydrolysis draws every pixel itself, so it has no
                            // native player to bridge. Selecting the self-drawn
                            // realization is the application's call, and its
                            // composition root installs it. A realization in a
                            // crate of its own — `waterui-map-gpu` — is a
                            // direct dependency of the application, which
                            // installs it in its own `app(env)`.
                            &["video-gpu"],
                            Some(NativeBackendDependencyPathKind::WateruiRoot),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
        ])
    }

    fn cargo_target_dependencies(
        ctx: &TemplateContext,
    ) -> BTreeMap<String, GeneratedTargetSection<GeneratedDependencyValue>> {
        BTreeMap::from([
            (
                "cfg(not(target_arch = \"wasm32\"))".to_string(),
                GeneratedTargetSection {
                    dependencies: native_target_dependencies(ctx),
                },
            ),
            (
                "cfg(target_arch = \"wasm32\")".to_string(),
                GeneratedTargetSection {
                    dependencies: wasm_target_dependencies(ctx),
                },
            ),
        ])
    }

    #[allow(
        clippy::too_many_lines,
        reason = "linear enumeration of native target dependencies reads clearest as one list"
    )]
    fn native_target_dependencies(
        ctx: &TemplateContext,
    ) -> BTreeMap<String, GeneratedDependencyValue> {
        let mut hydrolysis_features = vec!["winit"];
        hydrolysis_features.extend(ctx.webview_backend_feature());
        let mut dependencies: BTreeMap<String, GeneratedDependencyValue> = BTreeMap::from([
            (
                "hydrolysis".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "hydrolysis",
                            HYDROLYSIS_VERSION,
                            &hydrolysis_features,
                            Some(NativeBackendDependencyPathKind::BackendsSubdir(
                                "hydrolysis",
                            )),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
            (
                "pollster".to_string(),
                GeneratedDependencyValue::simple("0.4"),
            ),
            (
                "waterui-core".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "waterui-core",
                            WATERUI_CORE_VERSION,
                            &[],
                            Some(NativeBackendDependencyPathKind::WorkspaceSubdir("core")),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
            (
                "waterui-preview".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "waterui-preview",
                            PREVIEW_VERSION,
                            &[],
                            Some(NativeBackendDependencyPathKind::WorkspaceSubdir(
                                "components/devtools/preview/runtime",
                            )),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
            (
                "waterui-preview-protocol".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "waterui-preview-protocol",
                            PREVIEW_PROTOCOL_VERSION,
                            &[],
                            Some(NativeBackendDependencyPathKind::WorkspaceSubdir(
                                "components/devtools/preview/protocol",
                            )),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
            (
                "serde_json".to_string(),
                GeneratedDependencyValue::simple("1"),
            ),
            (
                "waterui-testing".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "waterui-testing",
                            WATERUI_VERSION,
                            &[],
                            Some(NativeBackendDependencyPathKind::WorkspaceSubdir("testing")),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
            (
                "hydrolysis-m3".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "hydrolysis-m3",
                            HYDROLYSIS_M3_VERSION,
                            &[],
                            Some(NativeBackendDependencyPathKind::BackendsSubdir(
                                "hydrolysis_m3",
                            )),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
        ]);
        // The CEF subprocess helper is a second binary in this crate, and it is
        // the one process that must not start WaterUI at all: it dispatches
        // straight into Chromium. The engine crate is the application's choice,
        // so the helper only exists — and this dependency only appears — when
        // the application's own graph links it.
        if requires_cef(ctx) {
            dependencies.insert(
                "waterui-browser-cef".to_string(),
                GeneratedDependencyValue::detailed(super::generated_dependency_from_spec(
                    ctx,
                    NativeBackendDependencySpec::new(
                        "waterui-browser-cef",
                        WATERUI_BROWSER_CEF_VERSION,
                        &[],
                        Some(NativeBackendDependencyPathKind::WorkspaceSubdir(
                            "components/platform/browser-cef",
                        )),
                    ),
                )),
            );
        }
        dependencies
    }

    fn wasm_target_dependencies(
        ctx: &TemplateContext,
    ) -> BTreeMap<String, GeneratedDependencyValue> {
        BTreeMap::from([
            (
                "hydrolysis".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "hydrolysis",
                            HYDROLYSIS_VERSION,
                            &["web"],
                            Some(NativeBackendDependencyPathKind::BackendsSubdir(
                                "hydrolysis",
                            )),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
            (
                "wasm-bindgen".to_string(),
                GeneratedDependencyValue::simple("0.2"),
            ),
            (
                "hydrolysis-m3".to_string(),
                GeneratedDependencyValue::detailed(
                    super::generated_dependency_from_spec(
                        ctx,
                        NativeBackendDependencySpec::new(
                            "hydrolysis-m3",
                            HYDROLYSIS_M3_VERSION,
                            &[],
                            Some(NativeBackendDependencyPathKind::BackendsSubdir(
                                "hydrolysis_m3",
                            )),
                        ),
                    )
                    .with_default_features(false),
                ),
            ),
        ])
    }
}

/// ESP32 firmware harness templates.
pub mod esp32 {
    use super::{Path, TemplateContext, TemplateNamespace, embedded, io, scaffold_dir};

    /// Write all ESP32 harness templates to the given directory.
    ///
    /// The generated `Cargo.toml` and `src/main.rs` are rendered from the
    /// template context (including `ctx.esp32` harness parameters); the
    /// remaining files (toolchain pin, cargo config, sdkconfig, partition
    /// table, build script) are static.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        scaffold_dir(TemplateNamespace::Esp32, &embedded::ESP32, base_dir, ctx).await
    }
}

/// Copies the `[patch]` tables governing the app's own build into a generated
/// companion manifest.
///
/// The companion crate is its own workspace root inside the build cache, and
/// Cargo only honours `[patch]` from the root of the workspace being built.
/// Without this, an app whose workspace patches a crate — say, a fork carrying
/// an urgent upstream fix — silently builds the unpatched version whenever the
/// build goes through a companion crate. Path patches are rebased onto
/// absolute paths because the companion lives outside the app tree.
async fn propagate_workspace_patches(
    manifest: &mut cargo_toml::Manifest<()>,
    project_root: &Path,
) -> io::Result<()> {
    let project_root = project_root.to_path_buf();
    let patches = smol::unblock(move || collect_workspace_patches(&project_root)).await?;
    manifest.patch = patches;
    Ok(())
}

/// Reads the `[patch]` tables from the workspace root that governs a build
/// rooted at `project_root`, with path patches made absolute.
fn collect_workspace_patches(project_root: &Path) -> io::Result<cargo_toml::PatchSet> {
    let Some((workspace_dir, source)) = find_workspace_manifest(project_root)? else {
        return Ok(cargo_toml::PatchSet::default());
    };

    let mut patches = source.patch;
    for deps in patches.values_mut() {
        for dependency in deps.values_mut() {
            if let cargo_toml::Dependency::Detailed(detail) = dependency
                && let Some(path) = detail.path.take()
            {
                detail.path = Some(workspace_dir.join(path).to_string_lossy().into_owned());
            }
        }
    }
    Ok(patches)
}

/// Finds the manifest Cargo would treat as the workspace root for a package at
/// `project_root`: the nearest ancestor manifest with a `[workspace]` section,
/// or the package's own manifest when it is standalone.
fn find_workspace_manifest(
    project_root: &Path,
) -> io::Result<Option<(PathBuf, cargo_toml::Manifest)>> {
    let mut fallback = None;
    for dir in project_root.ancestors() {
        let manifest_path = dir.join("Cargo.toml");
        if !manifest_path.is_file() {
            continue;
        }
        let manifest = cargo_toml::Manifest::from_path(&manifest_path)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
        if manifest.workspace.is_some() {
            return Ok(Some((dir.to_path_buf(), manifest)));
        }
        if fallback.is_none() && dir == project_root {
            fallback = Some((dir.to_path_buf(), manifest));
        }
    }
    Ok(fallback)
}

/// Native FFI companion crate templates.
pub mod ffi {
    use cargo_toml::{Dependency, DependencyDetail, Manifest, Package, Product, Workspace};

    use super::{
        NativeBackendDependencyPathKind, Path, TemplateContext, TemplateNamespace,
        WATERUI_FFI_VERSION, WATERUI_VERSION, cargo_semver, cargo_version_req,
        compute_native_backend_dependency_path, embedded, fs, generated_dev_profile, io,
        scaffold_dir, write_file_if_changed,
    };

    /// Write all FFI companion templates to the given directory.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        generate_cargo_toml(base_dir, ctx, package_name).await?;
        scaffold_dir(TemplateNamespace::Ffi, &embedded::FFI, base_dir, ctx).await
    }

    async fn generate_cargo_toml(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        let mut manifest = Manifest::<()>::default();
        let mut package = Package::new(package_name.to_string(), cargo_semver("0.1.0"));
        package.edition = cargo_toml::Inheritable::Set(cargo_toml::Edition::E2024);
        package.autobins = false;
        manifest.package = Some(package);
        manifest.profile = generated_dev_profile();

        // Apple links `lib<ffi>.a` and Android loads `lib<ffi>.so`, so the manifest
        // declares only that union; nothing ever consumes an `rlib` of this crate.
        // Each build then narrows further to the single crate type its platform
        // links, via `RustBuild::with_crate_type_override`.
        manifest.lib = Some(Product {
            crate_type: vec!["staticlib".to_string(), "cdylib".to_string()],
            ..Default::default()
        });
        if ctx.cef_runtime_enabled() {
            manifest.bin.push(Product {
                name: Some("waterui-cef-helper".to_string()),
                path: Some("src/bin/waterui-cef-helper.rs".to_string()),
                ..Default::default()
            });
        }

        manifest.dependencies.insert(
            ctx.crate_name.to_string(),
            Dependency::Detailed(Box::new(DependencyDetail {
                path: Some(ctx.project_root_relative_path()),
                ..Default::default()
            })),
        );

        manifest
            .features
            .insert("dev".to_string(), vec![format!("{}/dev", ctx.crate_name)]);

        let waterui_dependency = ctx.waterui_path.as_ref().map_or_else(
            || {
                Dependency::Detailed(Box::new(DependencyDetail {
                    version: Some(cargo_version_req(WATERUI_VERSION)),
                    default_features: false,
                    ..Default::default()
                }))
            },
            |waterui_path| {
                Dependency::Detailed(Box::new(DependencyDetail {
                    path: Some(compute_native_backend_dependency_path(
                        ctx,
                        waterui_path,
                        NativeBackendDependencyPathKind::WateruiRoot,
                    )),
                    default_features: false,
                    ..Default::default()
                }))
            },
        );
        manifest
            .dependencies
            .insert("waterui".to_string(), waterui_dependency);

        let ffi_dependency = ctx.waterui_path.as_ref().map_or_else(
            || {
                Dependency::Detailed(Box::new(DependencyDetail {
                    version: Some(cargo_version_req(WATERUI_FFI_VERSION)),
                    default_features: false,
                    ..Default::default()
                }))
            },
            |waterui_path| {
                Dependency::Detailed(Box::new(DependencyDetail {
                    path: Some(compute_native_backend_dependency_path(
                        ctx,
                        waterui_path,
                        NativeBackendDependencyPathKind::WorkspaceSubdir("ffi"),
                    )),
                    default_features: false,
                    ..Default::default()
                }))
            },
        );
        manifest
            .dependencies
            .insert("waterui-ffi".to_string(), ffi_dependency);

        // This crate roots the workspace that also holds preview modules. A preview
        // module is loaded into the support application and resolves its `WaterUI`
        // symbols against the runtime that application already has open, so the two
        // must come out of one Cargo resolution: Cargo derives `-C metadata` — which
        // it mangles into every symbol — per workspace, and two workspaces produce
        // runtimes whose symbols cannot resolve against each other even when their
        // dependency graphs are byte-for-byte identical.
        //
        // The members are whichever modules are on disk, listed by name rather than
        // by a `modules/*` glob: Cargo reads a glob that matches nothing as a
        // literal path and fails on it, and an ordinary application has no modules
        // at all.
        manifest.workspace = Some(Workspace {
            members: super::preview_module_members(base_dir).await?,
            ..Workspace::default()
        });

        if let Some(project_root) = &ctx.project_root_path {
            super::propagate_workspace_patches(&mut manifest, project_root).await?;
        }

        let toml_string = toml::to_string_pretty(&manifest)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
        fs::create_dir_all(base_dir).await?;
        write_file_if_changed(&base_dir.join("Cargo.toml"), toml_string.as_bytes()).await?;
        Ok(())
    }
}

/// The preview modules that live under a generated FFI crate, as member paths.
///
/// # Errors
///
/// Returns an error when the modules directory exists but cannot be read.
async fn preview_module_members(ffi_crate_dir: &Path) -> io::Result<Vec<String>> {
    use smol::stream::StreamExt as _;

    let modules_root = ffi_crate_dir.join(PREVIEW_MODULES_DIR);
    let mut entries = match fs::read_dir(&modules_root).await {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(error),
    };
    let mut members = Vec::new();
    while let Some(entry) = entries.next().await {
        let entry = entry?;
        if entry.path().join("Cargo.toml").is_file()
            && let Some(name) = entry.file_name().to_str()
        {
            members.push(format!("{PREVIEW_MODULES_DIR}/{name}"));
        }
    }
    members.sort();
    Ok(members)
}

/// Directory, relative to the generated FFI crate, that holds preview modules.
///
/// The FFI crate roots the workspace these modules join; see the workspace
/// declaration in `ffi::generate_cargo_toml` for why they must share one.
pub const PREVIEW_MODULES_DIR: &str = "modules";

/// Root-level templates (Cargo.toml, lib.rs, .gitignore).
pub mod root {
    use crate::templates::WATERUI_VERSION;

    use super::{
        GeneratedCargoManifest, GeneratedDependencyDetail, GeneratedTargetSection,
        GeneratedWorkspaceSection, Path, TemplateContext, TemplateNamespace, embedded, fs, io,
        render_scaffold_template, write_file_if_changed, write_generated_cargo_toml,
    };
    use std::collections::BTreeMap;

    /// Root template files, paired with their destination relative to the
    /// project root. The assets README is what makes the documented `assets!`
    /// workflow work out of the box: the planner walks the assets root
    /// recursively, so the directory has to exist before the first `assets!`
    /// call, and a tracked file is what keeps it present in git.
    static ROOT_TEMPLATES: &[(&str, &str)] = &[
        ("lib.rs.tpl", "src/lib.rs"),
        (".gitignore.tpl", ".gitignore"),
    ];

    /// Write root templates to the given directory.
    ///
    /// `assets_dir` is the project's assets root, relative to `base_dir`, and
    /// comes from the manifest so the scaffold and `Water.toml` cannot disagree.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(
        base_dir: &Path,
        ctx: &TemplateContext,
        assets_dir: &str,
    ) -> io::Result<()> {
        // Generate Cargo.toml programmatically using toml_edit
        generate_cargo_toml(base_dir, ctx).await?;

        let assets_readme = format!("{assets_dir}/README.md");
        // The WaterUI logo is the starting app icon; the planner picks up any
        // root-level `Icon.*` asset, so replacing the file rebrands the app.
        let assets_icon = format!("{assets_dir}/Icon.svg");
        let templates = ROOT_TEMPLATES
            .iter()
            .map(|(template, dest)| (*template, (*dest).to_string()))
            .chain(core::iter::once(("assets_readme.md.tpl", assets_readme)))
            .chain(core::iter::once(("icon.svg", assets_icon)));

        // Process remaining templates
        for (template_name, dest) in templates {
            if let Some(file) = embedded::ROOT.get_file(template_name) {
                let dest_path = base_dir.join(&dest);

                // Create parent directories
                if let Some(parent) = dest_path.parent() {
                    fs::create_dir_all(parent).await?;
                }

                let content = file
                    .contents_utf8()
                    .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))?;
                let rendered = render_scaffold_template(
                    TemplateNamespace::Root,
                    Path::new(template_name),
                    content,
                    ctx,
                )?;
                write_file_if_changed(&dest_path, rendered.as_bytes()).await?;
            }
        }
        Ok(())
    }

    /// Generate Cargo.toml programmatically using serde-compatible structs for type safety.
    async fn generate_cargo_toml(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        let waterui_dependency = waterui_dependency(ctx);
        let manifest = GeneratedCargoManifest {
            package: super::generated_package(ctx.crate_name.as_str(), vec![ctx.author.clone()]),
            lib: super::generated_lib(&["lib"]),
            bins: Vec::new(),
            profile: super::generated_dev_profile(),
            features: BTreeMap::from([(
                "dev".to_string(),
                vec!["waterui/dynamic_linking".to_string()],
            )]),
            dependencies: BTreeMap::from([("waterui".to_string(), waterui_dependency.clone())]),
            build_dependencies: BTreeMap::new(),
            target: native_target_section(waterui_dependency),
            workspace: GeneratedWorkspaceSection {},
            patch: cargo_toml::PatchSet::default(),
        };

        write_generated_cargo_toml(base_dir, super::render_generated_cargo_toml(&manifest)?).await
    }

    fn waterui_dependency(ctx: &TemplateContext) -> GeneratedDependencyDetail {
        ctx.waterui_path
            .as_ref()
            .map_or_else(
                || GeneratedDependencyDetail::version(WATERUI_VERSION),
                |waterui_path| GeneratedDependencyDetail::path(waterui_path),
            )
            .with_default_features(false)
    }

    fn native_target_section(
        waterui_dependency: GeneratedDependencyDetail,
    ) -> BTreeMap<String, GeneratedTargetSection<GeneratedDependencyDetail>> {
        // Desktop conveniences only: `media` pulls the GPU stack, which does
        // not exist on espidf targets, so firmware builds must fall through
        // to the bare default-features-off dependency for the scaffolded app
        // to cross-compile for ESP32 chips at all.
        BTreeMap::from([(
            "cfg(not(any(target_arch = \"wasm32\", target_os = \"espidf\")))".to_string(),
            GeneratedTargetSection {
                dependencies: BTreeMap::from([(
                    "waterui".to_string(),
                    waterui_dependency.with_features(&["assets", "media", "flow-markdown"]),
                )]),
            },
        )])
    }
}

/// Preview app templates.
pub mod preview {
    use crate::templates::{PREVIEW_VERSION, WATERUI_VERSION};

    use super::{
        Path, SupportDependencyDetail, SupportDependencyValue, TemplateContext, TemplateNamespace,
        dependency_path, dependency_version, embedded, io, scaffold_dir, write_support_cargo_toml,
    };

    /// Hash of embedded preview template files and the programmatically
    /// generated scaffold inputs (the dev profile written into every generated
    /// `Cargo.toml`), so a change to either regenerates cached support apps.
    #[must_use]
    pub fn template_fingerprint() -> String {
        use sha2::Digest as _;

        let mut hasher = sha2::Sha256::new();
        let mut dirs_to_process = vec![&embedded::PREVIEW];
        while let Some(current_dir) = dirs_to_process.pop() {
            for file in current_dir.files() {
                hasher.update(file.path().to_string_lossy().as_bytes());
                hasher.update(file.contents());
            }
            for subdir in current_dir.dirs() {
                dirs_to_process.push(subdir);
            }
        }
        hasher.update(super::generated_dev_profile_fingerprint().as_bytes());
        hex::encode(hasher.finalize())
    }

    /// Write preview app templates to the given directory.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        // Generate Cargo.toml programmatically
        generate_cargo_toml(base_dir, ctx).await?;

        // Scaffold remaining template files (lib.rs)
        scaffold_dir(
            TemplateNamespace::Preview,
            &embedded::PREVIEW,
            base_dir,
            ctx,
        )
        .await
    }

    /// Resolves the on-disk directory of a `waterui` workspace member crate from
    /// the workspace's own cargo metadata.
    ///
    /// The preview-support scaffold depends on internal `waterui` crates by path.
    /// Those paths must track the real crate location inside the workspace rather
    /// than a hardcoded relative path, which silently breaks when a crate moves
    /// (e.g. `waterui-preview` relocating from `components/preview` to
    /// `components/devtools/preview/runtime`): a stale path makes the scaffold's
    /// `cargo metadata` fail and aborts the whole preview build.
    pub(super) async fn resolve_workspace_member_dir(
        workspace_root: &Path,
        package_name: &str,
    ) -> io::Result<std::path::PathBuf> {
        let manifest = workspace_root.join("Cargo.toml");
        let metadata = smol::unblock(move || {
            cargo_metadata::MetadataCommand::new()
                .manifest_path(&manifest)
                .no_deps()
                .exec()
        })
        .await
        .map_err(io::Error::other)?;
        let member = metadata
            .packages
            .iter()
            .find(|package| package.name == package_name)
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::NotFound,
                    format!(
                        "`{package_name}` is not a member of the waterui workspace at {}",
                        workspace_root.display()
                    ),
                )
            })?;
        member
            .manifest_path
            .as_std_path()
            .parent()
            .map(Path::to_path_buf)
            .ok_or_else(|| {
                io::Error::other(format!(
                    "failed to derive crate directory for `{package_name}`"
                ))
            })
    }

    /// Generate preview app Cargo.toml programmatically.
    async fn generate_cargo_toml(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        use std::collections::BTreeMap;

        let mut dependencies = BTreeMap::new();

        if let Some(waterui_path) = &ctx.waterui_path {
            // Local path dependencies
            dependencies.insert(
                "waterui".to_string(),
                SupportDependencyValue::Detailed(SupportDependencyDetail {
                    package: None,
                    version: None,
                    path: Some(super::normalize_path_for_config(waterui_path)),
                    default_features: Some(false),
                    features: Vec::new(),
                }),
            );

            // Resolve `waterui-preview` from the workspace metadata so the path
            // tracks the crate if it is moved within the workspace.
            let preview_path =
                resolve_workspace_member_dir(waterui_path, "waterui-preview").await?;
            dependencies.insert(
                "waterui-preview".to_string(),
                dependency_path(&preview_path),
            );
        } else {
            // Registry dependencies
            dependencies.insert(
                "waterui".to_string(),
                SupportDependencyValue::Detailed(SupportDependencyDetail {
                    package: None,
                    version: Some(WATERUI_VERSION.to_string()),
                    path: None,
                    default_features: Some(false),
                    features: Vec::new(),
                }),
            );
            dependencies.insert(
                "waterui-preview".to_string(),
                dependency_version(PREVIEW_VERSION),
            );
        }
        let (app_crate_name, app_path) = ctx.preview_app_dependency.as_ref().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "Preview support runtime requires a user crate dependency",
            )
        })?;
        dependencies.insert(
            "waterui-preview-app".to_string(),
            SupportDependencyValue::Detailed(SupportDependencyDetail {
                package: Some(app_crate_name.to_string()),
                version: None,
                path: Some(super::normalize_path_for_config(app_path)),
                default_features: None,
                features: vec!["dev".to_string()],
            }),
        );
        if !ctx
            .preview_runtime_features
            .iter()
            .any(|feature| feature == "dynamic_linking")
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Preview support runtime features must include waterui/dynamic_linking",
            ));
        }
        let features = BTreeMap::from([(
            "dev".to_string(),
            ctx.preview_runtime_features
                .iter()
                .map(|feature| format!("waterui/{feature}"))
                .collect(),
        )]);
        write_support_cargo_toml(
            base_dir,
            ctx.crate_name.as_str(),
            features,
            dependencies,
            ctx.waterui_path.as_deref(),
        )
        .await
    }
}

/// Preview-only wrapper templates.
pub mod preview_ffi {
    use cargo_toml::{Dependency, DependencyDetail, Manifest, Package, Product};

    use super::{
        NativeBackendDependencyPathKind, PREVIEW_VERSION, Path, TemplateContext, TemplateNamespace,
        WATERUI_FFI_VERSION, cargo_semver, cargo_version_req,
        compute_native_backend_dependency_path, embedded, fs, io, scaffold_dir,
        write_file_if_changed,
    };

    /// Preview ABI exported to Apple support applications.
    pub const APPLE_ABI_FEATURE: &str = "apple-preview-abi";
    /// Preview ABI exported to Android support applications.
    pub const ANDROID_ABI_FEATURE: &str = "android-preview-abi";

    /// Write preview-only wrapper templates to the given directory.
    ///
    /// The crate is always a member of the support runtime's workspace rather
    /// than a workspace of its own, so the module and the runtime it is loaded
    /// into come out of a single Cargo resolution and agree on `-C metadata`.
    /// Profiles, `[patch]` entries and the lockfile therefore belong to that
    /// root and are deliberately absent here.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        generate_cargo_toml(base_dir, ctx, package_name).await?;
        scaffold_dir(
            TemplateNamespace::PreviewFfi,
            &embedded::PREVIEW_FFI,
            base_dir,
            ctx,
        )
        .await
    }

    async fn generate_cargo_toml(
        base_dir: &Path,
        ctx: &TemplateContext,
        package_name: &str,
    ) -> io::Result<()> {
        let mut manifest = Manifest::<()>::default();
        let mut package = Package::new(package_name.to_string(), cargo_semver("0.1.0"));
        package.edition = cargo_toml::Inheritable::Set(cargo_toml::Edition::E2024);
        manifest.package = Some(package);

        manifest.lib = Some(Product {
            crate_type: vec!["dylib".to_string()],
            ..Default::default()
        });

        manifest.dependencies.insert(
            ctx.crate_name.to_string(),
            Dependency::Detailed(Box::new(DependencyDetail {
                path: Some(ctx.project_root_relative_path()),
                features: vec!["dev".to_string()],
                ..Default::default()
            })),
        );

        let ffi_dependency = ctx.waterui_path.as_ref().map_or_else(
            || DependencyDetail {
                version: Some(cargo_version_req(WATERUI_FFI_VERSION)),
                optional: true,
                default_features: false,
                ..Default::default()
            },
            |waterui_path| DependencyDetail {
                path: Some(compute_native_backend_dependency_path(
                    ctx,
                    waterui_path,
                    NativeBackendDependencyPathKind::WorkspaceSubdir("ffi"),
                )),
                optional: true,
                default_features: false,
                ..Default::default()
            },
        );
        manifest.dependencies.insert(
            "waterui-ffi".to_string(),
            Dependency::Detailed(Box::new(ffi_dependency)),
        );

        let preview_dependency = if let Some(waterui_path) = &ctx.waterui_path {
            let waterui_root = Path::new(&compute_native_backend_dependency_path(
                ctx,
                waterui_path,
                NativeBackendDependencyPathKind::WateruiRoot,
            ))
            .to_path_buf();
            let waterui_root = if waterui_root.is_absolute() {
                waterui_root
            } else {
                base_dir.join(waterui_root)
            };
            let preview_path =
                super::preview::resolve_workspace_member_dir(&waterui_root, "waterui-preview")
                    .await?;
            DependencyDetail {
                path: Some(super::normalize_path_for_config(&preview_path)),
                optional: true,
                ..Default::default()
            }
        } else {
            DependencyDetail {
                version: Some(cargo_version_req(PREVIEW_VERSION)),
                optional: true,
                ..Default::default()
            }
        };
        manifest.dependencies.insert(
            "waterui-preview".to_string(),
            Dependency::Detailed(Box::new(preview_dependency)),
        );

        for (feature, ffi_feature) in [
            (APPLE_ABI_FEATURE, "waterui-ffi/c-api"),
            (ANDROID_ABI_FEATURE, "waterui-ffi/android-jni"),
        ] {
            manifest.features.insert(
                feature.to_string(),
                vec![
                    "dep:waterui-ffi".to_string(),
                    ffi_feature.to_string(),
                    "dep:waterui-preview".to_string(),
                ],
            );
        }

        let toml_string = toml::to_string_pretty(&manifest)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
        fs::create_dir_all(base_dir).await?;
        write_file_if_changed(&base_dir.join("Cargo.toml"), toml_string.as_bytes()).await?;
        Ok(())
    }
}

/// Inspector app templates.
pub mod inspector {
    use super::{
        Path, TemplateContext, TemplateNamespace, dependency_path, embedded, io, scaffold_dir,
        write_support_cargo_toml,
    };

    /// Hash of embedded inspector template files and the programmatically
    /// generated scaffold inputs (see `generated_dev_profile_fingerprint`).
    #[must_use]
    pub fn template_fingerprint() -> String {
        use sha2::Digest as _;

        let mut hasher = sha2::Sha256::new();
        let mut dirs_to_process = vec![&embedded::INSPECTOR];
        while let Some(current_dir) = dirs_to_process.pop() {
            for file in current_dir.files() {
                hasher.update(file.path().to_string_lossy().as_bytes());
                hasher.update(file.contents());
            }
            for subdir in current_dir.dirs() {
                dirs_to_process.push(subdir);
            }
        }
        hasher.update(super::generated_dev_profile_fingerprint().as_bytes());
        hex::encode(hasher.finalize())
    }

    /// Write inspector app templates to the given directory.
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    pub async fn scaffold(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        generate_cargo_toml(base_dir, ctx).await?;
        scaffold_dir(
            TemplateNamespace::Inspector,
            &embedded::INSPECTOR,
            base_dir,
            ctx,
        )
        .await
    }

    /// Path of the Inspector application crate inside a `WaterUI` checkout.
    ///
    /// The Inspector's user interface is a real crate rather than template
    /// text, so it is compiled, linted, and tested with the rest of the
    /// workspace. The scaffolded app is a shim that depends on it.
    const INSPECTOR_APP_CRATE: &str = "components/devtools/inspector/app";

    async fn generate_cargo_toml(base_dir: &Path, ctx: &TemplateContext) -> io::Result<()> {
        use std::collections::BTreeMap;

        let waterui_path = ctx.waterui_path.as_ref().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "Inspector support app requires a local waterui_path",
            )
        })?;

        let inspector_app_path = waterui_path.join(INSPECTOR_APP_CRATE);
        if !inspector_app_path.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "Inspector support app requires {} (missing {INSPECTOR_APP_CRATE})",
                    waterui_path.display()
                ),
            ));
        }

        let mut dependencies = BTreeMap::new();
        dependencies.insert("waterui".to_string(), dependency_path(waterui_path));
        dependencies.insert(
            "waterui-ffi".to_string(),
            dependency_path(&waterui_path.join("ffi")),
        );
        dependencies.insert(
            "waterui-inspector-app".to_string(),
            dependency_path(&inspector_app_path),
        );

        // The FFI scaffold generated alongside this app declares
        // `dev = ["<app>/dev"]`, so an app without a `dev` feature cannot be
        // resolved at all: cargo fails the whole metadata query before anything
        // is built. Every generated project carries this feature; the support
        // app is no different.
        let features = BTreeMap::from([(
            "dev".to_string(),
            vec!["waterui/dynamic_linking".to_string()],
        )]);

        write_support_cargo_toml(
            base_dir,
            ctx.crate_name.as_str(),
            features,
            dependencies,
            ctx.waterui_path.as_deref(),
        )
        .await
    }

    #[cfg(test)]
    mod tests {
        /// The scaffolder resolves the Inspector crate by path, so a move that
        /// nobody updates here breaks `water inspector` silently — which is
        /// exactly what happened when the crate moved under `devtools/`.
        #[test]
        fn the_inspector_app_crate_path_exists() {
            let repository = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .parent()
                .expect("the CLI crate lives inside the repository");
            let crate_path = repository.join(super::INSPECTOR_APP_CRATE);
            assert!(
                crate_path.join("Cargo.toml").is_file(),
                "inspector app crate is not at {}",
                crate_path.display()
            );
        }

        /// The FFI scaffold generated beside this app declares
        /// `dev = ["<app>/dev"]`. An app without that feature cannot be
        /// resolved at all — cargo fails the metadata query and `water
        /// inspector` dies before building anything, which is exactly what it
        /// did until this was noticed.
        #[test]
        fn the_generated_app_declares_the_feature_its_ffi_scaffold_requires() {
            let generated = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("src/project_model/templates.rs");
            let source = std::fs::read_to_string(generated).expect("the module is readable");
            let inspector = source
                .split("pub mod inspector {")
                .nth(1)
                .expect("the inspector template module exists");
            assert!(
                inspector.contains("\"dev\".to_string()"),
                "the inspector support app is generated without a `dev` feature"
            );
        }
    }
}

#[cfg(test)]
mod template_digest_tests {
    /// The digest must be stable across calls, or every invocation would
    /// invalidate the generated-crate cache and force a full rebuild.
    #[test]
    fn scaffold_template_digest_is_stable() {
        assert_eq!(
            super::scaffold_template_digest(),
            super::scaffold_template_digest()
        );
    }

    /// It must actually depend on template contents. A digest that ignored them
    /// would let a stale generated crate survive a CLI upgrade — the rot this
    /// exists to prevent.
    #[test]
    fn scaffold_template_digest_covers_template_contents() {
        let digest = super::scaffold_template_digest();
        assert_eq!(digest.len(), 16, "digest must be a 16-char hex prefix");

        let hydrolysis_preview = super::embedded::HYDROLYSIS
            .get_file("src/preview_runtime.rs.tpl")
            .expect("the hydrolysis preview runtime template must be embedded");
        assert!(
            !hydrolysis_preview.contents().is_empty(),
            "the template the digest is meant to track must be non-empty"
        );
    }
}