tonin 0.6.1

Opinionated Rust microservice framework. Kubernetes-native, mesh-secured, MCP-by-default.
Documentation
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
//! `tonin service new <name> --lang <rust|python|ts> [--type web|backend]`.
//!
//! Scaffold templates use plain `{{ var }}` substitution — no loops, no
//! conditionals. Done with `str::replace` (not a template engine) so the
//! syntax can't collide with TSX/JS object literals or anything else inside
//! the templates. The k8s renderer is a separate pipeline that does use
//! Tera, because cross-service network policies need real loops.

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

use crate::codegen::{plan::Plan, render};
use anyhow::{Context, Result, anyhow, bail};
use convert_case::{Case, Casing};
use include_dir::{Dir, include_dir};

use super::service::{ClientLang, Lang, ServiceType, StorageKind, WebMode};

static TEMPLATES: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates/service");

struct Vars {
    service_name: String,
    /// Snake-case form, suitable for Rust `use` paths and proto package
    /// names. `service-name` → `service_name`. Uses **heck**'s
    /// snake-case algorithm — which is the same one prost uses
    /// internally to generate module paths from proto `service` names.
    /// Matters for names with embedded digits: `s3svc` → `s3svc` (heck),
    /// not `s_3_svc` (convert_case::Snake).
    service_name_snake: String,
    /// Pascal-case form (`MyService`), used as the proto `service Name`
    /// and as the prefix of the generated client struct (`NameClient`).
    service_camel: String,
    /// Module path prost generates from the Pascal-case service name.
    /// For `MyService` → `my_service` (so the client lives at
    /// `proto::my_service_client::MyServiceClient`). Same heck snake
    /// algorithm as above.
    service_proto_module: String,
    language: String,
    service_type: String,
}

impl Vars {
    fn apply(&self, src: &str) -> String {
        src.replace("{{ service_proto_module }}", &self.service_proto_module)
            .replace("{{service_proto_module}}", &self.service_proto_module)
            .replace("{{ service_name_snake }}", &self.service_name_snake)
            .replace("{{service_name_snake}}", &self.service_name_snake)
            .replace("{{ service_name }}", &self.service_name)
            .replace("{{service_name}}", &self.service_name)
            .replace("{{ ServiceCamel }}", &self.service_camel)
            .replace("{{ServiceCamel}}", &self.service_camel)
            .replace("{{ language }}", &self.language)
            .replace("{{language}}", &self.language)
            .replace("{{ service_type }}", &self.service_type)
            .replace("{{service_type}}", &self.service_type)
    }
}

#[allow(clippy::too_many_arguments)] // each arg maps to a `tonin service new` CLI flag; bundling into a struct buys nothing here
pub fn run(
    name: &str,
    lang: Lang,
    st: ServiceType,
    wm: Option<WebMode>,
    no_workspace: bool,
    _template_repo: Option<&str>,
    flat: bool,
    with_jobs: &[String],
    with_storage: Option<StorageKind>,
    extra_clients: &[ClientLang],
) -> Result<()> {
    validate_name(name)?;
    for job in with_jobs {
        validate_name(job).with_context(|| format!("invalid --with-job name '{job}'"))?;
    }

    let dest = PathBuf::from(name);
    if dest.exists() {
        bail!(
            "{} already exists; pick another name or delete it first",
            dest.display()
        );
    }

    use heck::ToSnakeCase as _;
    let service_camel = name.to_case(Case::Pascal);
    let vars = Vars {
        service_name: name.to_string(),
        // heck::to_snake_case matches prost's internal snake-casing of
        // proto identifiers — so the proto package name we write here
        // matches the module path prost generates downstream.
        service_name_snake: name.to_snake_case(),
        service_proto_module: service_camel.to_snake_case(),
        service_camel,
        language: lang.as_str().to_string(),
        service_type: st.as_str().to_string(),
    };

    // Default: three-crate workspace layout (proto + server + rs).
    // Use --flat to get the old single-directory structure instead.
    if matches!(lang, Lang::Rust) && !flat {
        if dest.exists() {
            bail!(
                "{} already exists; pick another name or delete it first",
                dest.display()
            );
        }
        std::fs::create_dir_all(&dest).with_context(|| format!("creating {}", dest.display()))?;
        emit_workspace_layout(&dest, &vars, extra_clients)?;
        print_workspace_next_steps(name, extra_clients);
        return Ok(());
    }

    scaffold(&dest, lang, st, wm, &vars)?;
    write_service_toml(&dest, &vars, st, wm)?;
    if let Some(kind) = with_storage {
        emit_storage_block_in_micro_toml(&dest, kind)?;
    }
    if !with_jobs.is_empty() {
        match lang {
            Lang::Rust => emit_jobs(&dest, &vars, with_jobs)?,
            Lang::Python => emit_jobs_python(&dest, &vars, with_jobs)?,
            Lang::Ts => unreachable!("--with-job rejected for ts in service::run"),
        }
    }
    if let Some(kind) = with_storage {
        match lang {
            Lang::Rust => emit_storage_rust(&dest, &vars, kind)?,
            Lang::Python => emit_storage_python(&dest, &vars, kind)?,
            Lang::Ts => unreachable!("--with-storage rejected for ts in service::run"),
        }
    }
    for extra in extra_clients {
        emit_extra_client(&dest, &vars, *extra)?;
    }
    pregenerate_k8s(&dest)?;
    emit_claude_md(&dest, name, lang, st, wm)?;
    emit_gitignore(&dest)?;
    emit_docs_tree(&dest, name)?;

    if matches!(lang, Lang::Rust) && !no_workspace {
        maybe_add_to_workspace(&dest)?;
    }

    print_next_steps(name, lang, st, wm, with_jobs, with_storage, extra_clients);
    Ok(())
}

/// Append a `[storage]` block to the freshly-emitted tonin.toml so k8s
/// rendering + service-author docs reflect the chosen backend.
fn emit_storage_block_in_micro_toml(dest: &Path, kind: StorageKind) -> Result<()> {
    let path = dest.join("tonin.toml");
    let mut content =
        std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
    if !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str(&format!(
        "\n# Object storage. Secrets come from STORAGE_* env (see\n\
         # server/src/storage.rs or jobs/<name>.py for the full list).\n\
         [storage]\n\
         kind = \"{kind_str}\"\n",
        kind_str = kind.as_str()
    ));
    std::fs::write(&path, content).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

/// Emit `server/src/storage.rs` + add `opendal` dep + wire into main.rs.
/// The trait lives in tonin-core; this file is the user-owned default
/// impl. Users can hand-edit or replace it with their own
/// `StorageProvider` implementation without breaking the framework
/// contract.
fn emit_storage_rust(dest: &Path, vars: &Vars, kind: StorageKind) -> Result<()> {
    let storage_path = dest.join("server/src/storage.rs");
    std::fs::write(&storage_path, render_storage_rs_rust(kind))
        .with_context(|| format!("writing {}", storage_path.display()))?;

    // Add `pub mod storage;` to the server lib.rs.
    let lib_path = dest.join("server/src/lib.rs");
    let mut lib = std::fs::read_to_string(&lib_path)
        .with_context(|| format!("reading {}", lib_path.display()))?;
    if !lib.contains("pub mod storage") {
        // Insert after the existing `pub mod auth;` line if present.
        if lib.contains("pub mod auth;") {
            let insertion = "pub mod auth;\npub mod storage;";
            lib = lib.replacen("pub mod auth;", insertion, 1);
        } else {
            lib.push_str("\npub mod storage;\n");
        }
        std::fs::write(&lib_path, &lib)?;
    }

    // Add opendal dep with the matching feature to server/Cargo.toml.
    let cargo_path = dest.join("server/Cargo.toml");
    let mut cargo = std::fs::read_to_string(&cargo_path)
        .with_context(|| format!("reading {}", cargo_path.display()))?;
    let dep_line = format!(
        "opendal = {{ version = \"0.57\", default-features = false, features = [\"{feat}\"] }}\n",
        feat = kind.opendal_feature()
    );
    if !cargo.contains("opendal") {
        // Insert just after the `[dependencies]` header. Falls back to
        // appending at end if the section can't be found (shouldn't
        // happen with our templates).
        if let Some(idx) = cargo.find("[dependencies]") {
            // Move past the line.
            let after_header = idx + "[dependencies]".len();
            // Find next newline.
            let nl = cargo[after_header..]
                .find('\n')
                .map(|n| after_header + n + 1)
                .unwrap_or(after_header);
            cargo.insert_str(nl, &dep_line);
        } else {
            cargo.push_str(&dep_line);
        }
        std::fs::write(&cargo_path, &cargo)?;
    }

    // Wire State::with_storage(...) into main.rs.
    let main_path = dest.join("server/src/main.rs");
    let mut main_src = std::fs::read_to_string(&main_path)
        .with_context(|| format!("reading {}", main_path.display()))?;
    let needle = "let state = State::from_env().await?;";
    let replacement = format!(
        "let state = State::from_env().await?\n        \
         .with_storage({snake}_server::storage::OpendalStorage::from_env().await?)\n        \
         .await?;",
        snake = vars.service_name_snake
    );
    if main_src.contains(needle) {
        main_src = main_src.replacen(needle, &replacement, 1);
        std::fs::write(&main_path, &main_src)?;
    }

    eprintln!(
        "✓ emitted Rust storage wiring ({kind})",
        kind = kind.as_str()
    );
    Ok(())
}

/// Python equivalent: emit `<svc>_server/storage.py` + add opendal to
/// pyproject.toml + wire into the server bootstrap. (The Python
/// scaffold restructure to 3-folder lives in a follow-up task; for
/// now we touch what exists.)
/// Emit `server/src/<svc>_server/storage.py`, add `opendal` to the
/// server's pyproject `[project.dependencies]`, and wire
/// `state.with_storage(...)` into `main.py`. Mirrors `emit_storage_rust`
/// for the 3-folder Python layout.
fn emit_storage_python(dest: &Path, vars: &Vars, kind: StorageKind) -> Result<()> {
    let snake = &vars.service_name_snake;
    let pkg_dir = dest.join("server/src").join(format!("{snake}_server"));
    std::fs::create_dir_all(&pkg_dir).with_context(|| format!("creating {}", pkg_dir.display()))?;

    let storage_py_path = pkg_dir.join("storage.py");
    std::fs::write(&storage_py_path, render_storage_py(kind))
        .with_context(|| format!("writing {}", storage_py_path.display()))?;

    // Add `opendal>=0.45` to server/pyproject.toml's [project.dependencies]
    // array. The scaffold pyproject lists deps with one item per line in
    // a multi-line array — we splice in a new line before the closing
    // bracket of that array.
    let pyproject_path = dest.join("server/pyproject.toml");
    let mut text = std::fs::read_to_string(&pyproject_path)
        .with_context(|| format!("reading {}", pyproject_path.display()))?;
    if !text.contains("opendal") {
        // Find `dependencies = [` then the matching `]`.
        if let Some(start) = text.find("dependencies = [") {
            let from = start + "dependencies = [".len();
            if let Some(rel_end) = text[from..].find(']') {
                let end = from + rel_end;
                text.insert_str(end, "  \"opendal>=0.45\",\n");
                std::fs::write(&pyproject_path, &text)?;
            }
        }
    }

    // Wire `state = (await State.from_env()).with_storage(...)` into
    // main.py. Replace the existing `state = await tonin.State.from_env()`
    // line with the chained version.
    let main_path = pkg_dir.join("main.py");
    let mut main_src = std::fs::read_to_string(&main_path)
        .with_context(|| format!("reading {}", main_path.display()))?;
    let needle = "state = await tonin.State.from_env()";
    let replacement = format!(
        "state = await tonin.State.from_env()\n    \
         from {snake}_server.storage import OpendalStorage\n    \
         state = await state.with_storage(await OpendalStorage.from_env())",
    );
    if main_src.contains(needle) {
        main_src = main_src.replacen(needle, &replacement, 1);
        std::fs::write(&main_path, &main_src)?;
    }

    eprintln!(
        "✓ emitted Python storage module ({kind})",
        kind = kind.as_str()
    );
    Ok(())
}

/// Generate the `storage.rs` file the scaffold ships when --with-storage is used.
///
/// The trait lives in tonin-core; this is a concrete impl users own.
fn render_storage_rs_rust(kind: StorageKind) -> String {
    let kind_str = kind.as_str();
    let builder_block = match kind {
        StorageKind::S3 => {
            r#"
        // opendal 0.57 builder methods consume + return Self.
        let mut builder = opendal::services::S3::default()
            .bucket(&env("STORAGE_BUCKET")?);
        if let Ok(region) = std::env::var("STORAGE_REGION") {
            builder = builder.region(&region);
        }
        if let Ok(endpoint) = std::env::var("STORAGE_ENDPOINT") {
            builder = builder.endpoint(&endpoint);
        }
        if let Ok(ak) = std::env::var("STORAGE_ACCESS_KEY") {
            builder = builder.access_key_id(&ak);
        }
        if let Ok(sk) = std::env::var("STORAGE_SECRET_KEY") {
            builder = builder.secret_access_key(&sk);
        }
        let op = opendal::Operator::new(builder)
            .map_err(|e| Error::Config(format!("opendal S3 init: {e}")))?
            .finish();
"#
        }
        StorageKind::Gcs => {
            r#"
        let mut builder = opendal::services::Gcs::default()
            .bucket(&env("STORAGE_BUCKET")?);
        if let Ok(cred) = std::env::var("STORAGE_CREDENTIAL_PATH") {
            builder = builder.credential_path(&cred);
        }
        let op = opendal::Operator::new(builder)
            .map_err(|e| Error::Config(format!("opendal GCS init: {e}")))?
            .finish();
"#
        }
        StorageKind::Azure => {
            r#"
        let mut builder = opendal::services::Azblob::default()
            .container(&env("STORAGE_CONTAINER")?);
        if let Ok(acc) = std::env::var("STORAGE_ACCOUNT") {
            builder = builder.account_name(&acc);
        }
        if let Ok(key) = std::env::var("STORAGE_ACCESS_KEY") {
            builder = builder.account_key(&key);
        }
        let op = opendal::Operator::new(builder)
            .map_err(|e| Error::Config(format!("opendal Azblob init: {e}")))?
            .finish();
"#
        }
        StorageKind::Local => {
            r#"
        let builder = opendal::services::Fs::default()
            .root(&env("STORAGE_ROOT")?);
        let op = opendal::Operator::new(builder)
            .map_err(|e| Error::Config(format!("opendal Fs init: {e}")))?
            .finish();
"#
        }
    };

    format!(
        r#"//! Object-storage wiring (opendal-backed).
//!
//! Default `StorageProvider` impl for this service. The trait lives in
//! `tonin::state::StorageProvider`; everything below is owned by you
//! and safe to edit. To swap out opendal for a different SDK or to
//! layer in retries / logging, replace this file and update `main.rs`
//! to call `state.with_storage(YourImpl)` instead.
//!
//! Activation: scaffolded via `tonin service new --with-storage {kind_str}`.
//!
//! The boot probe runs `op.list("/").limit(1)` — cheap connectivity
//! check that catches missing bucket / wrong creds / network issues
//! before the service starts serving traffic.

use std::sync::Arc;

use async_trait::async_trait;
use futures::StreamExt;
use tonin::core::error::{{Error, Result}};
use tonin::core::state::StorageProvider;
use opendal::Operator;

/// Wraps an `opendal::Operator`. Cheap to clone (opendal Operator is
/// internally `Arc`-backed).
#[derive(Clone)]
pub struct OpendalStorage {{
    op: Operator,
}}

impl OpendalStorage {{
    /// Construct directly from a pre-built Operator. Use this when you
    /// want full control over the builder (e.g. layered retries).
    pub fn from_operator(op: Operator) -> Self {{
        Self {{ op }}
    }}

    /// Build from env (`STORAGE_*`). Probe is run later by
    /// `State::with_storage`.
    pub async fn from_env() -> Result<Self> {{
{builder_block}
        Ok(Self {{ op }})
    }}

    /// Borrow the underlying Operator for app code that wants the full
    /// opendal API (writes, reads, presigned URLs, etc.).
    pub fn operator(&self) -> &Operator {{
        &self.op
    }}
}}

#[async_trait]
impl StorageProvider for OpendalStorage {{
    async fn probe(&self) -> Result<()> {{
        // LIST limit 1 — cheap, no writes, verifies we can reach the bucket
        // and our creds work. Errors propagate as Config so the service
        // fails to start rather than 5xx-ing later.
        let mut lister = self.op.lister_with("/").limit(1).await
            .map_err(|e| Error::Config(format!("storage probe failed: {{e}}")))?;
        // Drain at most one entry, then stop. We don't care what's in
        // the bucket; we only care that the call succeeded.
        if let Some(item) = lister.next().await {{
            item.map_err(|e| Error::Config(format!("storage probe entry: {{e}}")))?;
        }}
        Ok(())
    }}

    fn system(&self) -> &'static str {{
        "{kind_str}"
    }}
}}

/// Convenience: bubble up a clear error when a required env var is missing.
fn env(name: &str) -> Result<String> {{
    std::env::var(name).map_err(|_| {{
        Error::Config(format!("{{name}} unset (required for --with-storage {kind_str})"))
    }})
}}

// Silence Arc<dyn StorageProvider> handle indirection when the user
// wants to share storage across spawned tasks.
#[allow(dead_code)]
fn _share_as_arc(s: OpendalStorage) -> Arc<dyn StorageProvider> {{
    Arc::new(s)
}}
"#,
    )
}

fn render_storage_py(kind: StorageKind) -> String {
    let kind_str = kind.as_str();
    let scheme = match kind {
        StorageKind::S3 => "s3",
        StorageKind::Gcs => "gcs",
        StorageKind::Azure => "azblob",
        StorageKind::Local => "fs",
    };
    format!(
        r#""""Object-storage wiring (opendal-backed).

Default storage helper for this service. Scaffolded via
``tonin service new --with-storage {kind_str}``. Owned by you — feel
free to swap opendal for a different SDK or add retry layers.

Boot probe: ``op.list("/", limit=1)`` — cheap connectivity check that
catches missing bucket / wrong creds before serving traffic.
"""
from __future__ import annotations

import logging
import os
from dataclasses import dataclass

logger = logging.getLogger(__name__)


def _env(name: str) -> str:
    v = os.environ.get(name)
    if not v:
        raise RuntimeError(f"{{name}} unset (required for --with-storage {kind_str})")
    return v


@dataclass(slots=True)
class OpendalStorage:
    """Wraps :class:`opendal.AsyncOperator`. All ops are awaited."""

    op: "object"  # opendal.AsyncOperator — typed as object to avoid hard import

    @classmethod
    async def from_env(cls) -> "OpendalStorage":
        import opendal

        kwargs: dict[str, str] = {{}}
        kind = "{scheme}"

        if kind == "s3":
            kwargs["bucket"] = _env("STORAGE_BUCKET")
            if (v := os.environ.get("STORAGE_REGION")):
                kwargs["region"] = v
            if (v := os.environ.get("STORAGE_ENDPOINT")):
                kwargs["endpoint"] = v
            if (v := os.environ.get("STORAGE_ACCESS_KEY")):
                kwargs["access_key_id"] = v
            if (v := os.environ.get("STORAGE_SECRET_KEY")):
                kwargs["secret_access_key"] = v
        elif kind == "gcs":
            kwargs["bucket"] = _env("STORAGE_BUCKET")
            if (v := os.environ.get("STORAGE_CREDENTIAL_PATH")):
                kwargs["credential_path"] = v
        elif kind == "azblob":
            kwargs["container"] = _env("STORAGE_CONTAINER")
            if (v := os.environ.get("STORAGE_ACCOUNT")):
                kwargs["account_name"] = v
            if (v := os.environ.get("STORAGE_ACCESS_KEY")):
                kwargs["account_key"] = v
        elif kind == "fs":
            kwargs["root"] = _env("STORAGE_ROOT")

        op = opendal.AsyncOperator(kind, **kwargs)
        instance = cls(op=op)
        await instance.probe()
        return instance

    async def probe(self) -> None:
        """LIST limit 1. Raises if storage is unreachable."""
        try:
            lister = await self.op.list("/", limit=1)
            async for _ in lister:
                break
        except Exception as e:
            raise RuntimeError(f"storage probe failed: {{e}}") from e
        logger.info("storage probe ok system=%s", "{kind_str}")

    def operator(self) -> "object":
        """Return the underlying opendal AsyncOperator."""
        return self.op
"#,
    )
}

/// Emit `server/src/bin/<job>.rs` per job and append `[[bin]]` entries
/// to `server/Cargo.toml`. Rust-only (the CLI bails earlier if any
/// non-Rust language is paired with `--with-job`).
fn emit_jobs(dest: &Path, vars: &Vars, jobs: &[String]) -> Result<()> {
    let bin_dir = dest.join("server/src/bin");
    std::fs::create_dir_all(&bin_dir).with_context(|| format!("creating {}", bin_dir.display()))?;

    for job in jobs {
        let body = render_job_bin(&vars.service_name, job);
        std::fs::write(bin_dir.join(format!("{job}.rs")), body)
            .with_context(|| format!("writing job binary {job}.rs"))?;
    }

    // Append `[[bin]]` entries to server/Cargo.toml.
    let cargo_path = dest.join("server/Cargo.toml");
    let mut cargo = std::fs::read_to_string(&cargo_path)
        .with_context(|| format!("reading {}", cargo_path.display()))?;
    if !cargo.ends_with('\n') {
        cargo.push('\n');
    }
    cargo.push_str("\n# Background-job binaries. Each one runs to completion (queue\n");
    cargo.push_str("# consumer, scheduled task) rather than serving gRPC.\n");
    for job in jobs {
        cargo.push_str(&format!(
            "[[bin]]\nname = \"{}-{job}\"\npath = \"src/bin/{job}.rs\"\n\n",
            vars.service_name
        ));
    }
    std::fs::write(&cargo_path, cargo)
        .with_context(|| format!("writing {}", cargo_path.display()))?;

    eprintln!(
        "✓ emitted {} background-job binar{}",
        jobs.len(),
        if jobs.len() == 1 { "y" } else { "ies" }
    );
    Ok(())
}

/// Rust source for a single job binary. Kept inline (rather than a
/// .tmpl) because it needs a per-job `{{ job_name }}` substitution
/// that the normal scaffold walker doesn't carry.
fn render_job_bin(service_name: &str, job_name: &str) -> String {
    format!(
        r#"//! `{service_name}-{job_name}` — background-job binary.
//!
//! Bootstraps the same way every micro job does: OTel init, service-
//! identity AuthCtx via `tonin::auth::service_token()`, and pre-wired
//! State (Postgres + Redis from env). No gRPC server is started.
//!
//! Run locally:
//!     cargo run --bin {service_name}-{job_name}
//!
//! In production this becomes a Kubernetes Job (or CronJob) that points
//! at the same image as the main server but overrides the entrypoint to
//! `/usr/local/bin/{service_name}-{job_name}`.

use tonin::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {{
    let ctx = tonin::job::bootstrap("{service_name}-{job_name}").await?;

    tracing::info!(
        target: "{service_name}::{job_name}",
        subject = %ctx.auth.subject,
        has_pg = ctx.state.has_pg(),
        has_redis = ctx.state.has_redis(),
        "job starting",
    );

    // -------------------------------------------------------------
    // Replace this block with your actual job logic.
    //
    // - For queue consumers: loop on a fetch-and-process pattern.
    // - For scheduled work: do the work and return.
    // - For outbound calls to other services, propagate `ctx.auth`:
    //
    //     let mut req = tonic::Request::new(SomeRequest {{ ... }});
    //     ctx.auth.propagate(&mut req);
    //     downstream_client.some_rpc(req).await?;
    // -------------------------------------------------------------

    tracing::info!(target: "{service_name}::{job_name}", "job done");
    Ok(())
}}
"#,
    )
}

/// Emit `server/src/<svc>_server/jobs/<job>.py` per job, plus a `jobs/__init__.py`
/// if needed, plus `[project.scripts]` entries in server/pyproject.toml.
/// Python equivalent of [`emit_jobs`].
fn emit_jobs_python(dest: &Path, vars: &Vars, jobs: &[String]) -> Result<()> {
    let snake = &vars.service_name_snake;
    let pkg_dir = dest
        .join("server/src")
        .join(format!("{snake}_server"))
        .join("jobs");
    std::fs::create_dir_all(&pkg_dir).with_context(|| format!("creating {}", pkg_dir.display()))?;

    // jobs/__init__.py marker
    let init_path = pkg_dir.join("__init__.py");
    if !init_path.exists() {
        std::fs::write(
            &init_path,
            "\"\"\"Background jobs for this service. Each module is runnable via `python -m`.\"\"\"\n",
        )?;
    }

    for job in jobs {
        let body = render_job_py(&vars.service_name, snake, job);
        std::fs::write(pkg_dir.join(format!("{job}.py")), body)
            .with_context(|| format!("writing job {job}.py"))?;
    }

    // Append `[project.scripts]` entries to server/pyproject.toml. The
    // pyproject already has one entry (the main server). We append
    // one console-script per job so `<svc>-<job>` becomes a uv-runnable
    // command after `uv sync`.
    let pyproject_path = dest.join("server/pyproject.toml");
    let mut content = std::fs::read_to_string(&pyproject_path)
        .with_context(|| format!("reading {}", pyproject_path.display()))?;
    let script_lines: String = jobs
        .iter()
        .map(|job| {
            format!(
                "\"{svc}-{job}\" = \"{snake}_server.jobs.{job}:run\"\n",
                svc = vars.service_name,
            )
        })
        .collect();

    // Insert into the existing [project.scripts] block. The scaffold
    // emits exactly one entry (`<svc> = "<svc>_server.main:run"`); we
    // append our lines right after it.
    if let Some(idx) = content.find("[project.scripts]") {
        // Find the next blank-line or section header after the block.
        let block_start = idx + "[project.scripts]".len();
        let rest = &content[block_start..];
        // Find next section (line beginning with `[`) or EOF.
        let mut insertion = block_start;
        for (i, line) in rest.split_inclusive('\n').enumerate() {
            insertion += line.len();
            if i == 0 {
                continue; // skip the header line itself
            }
            if line.starts_with('[') {
                // section header — back up by the line length to
                // insert *before* it.
                insertion -= line.len();
                break;
            }
        }
        content.insert_str(insertion, &script_lines);
    } else {
        // No [project.scripts] yet — append a fresh block at the end.
        if !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str("\n[project.scripts]\n");
        content.push_str(&script_lines);
    }
    std::fs::write(&pyproject_path, content)?;

    eprintln!(
        "✓ emitted {} Python background-job module{}",
        jobs.len(),
        if jobs.len() == 1 { "" } else { "s" }
    );
    Ok(())
}

/// Python source for a single job binary. Same shape as `render_job_bin`
/// but async-by-default and built on tonin.job.bootstrap.
fn render_job_py(service_name: &str, service_snake: &str, job_name: &str) -> String {
    format!(
        r#""""`{service_name}-{job_name}` — background-job entry point.

Bootstraps the same way every micro Python job does:
  1. OTel telemetry init via `tonin.job.bootstrap`
  2. Service-identity AuthCtx via `tonin.auth.service_token` (HTTP mint)
  3. State (asyncpg + redis.asyncio, lazily from env)

Async-by-default — there is no sync code path. asyncio.run owns the
event loop; everything inside is `await`-ed.

Run locally::

    uv run {service_name}-{job_name}

In production this becomes a Kubernetes Job (or CronJob) referencing
the same container image but with an overridden entrypoint:
``["python", "-m", "{service_snake}_server.jobs.{job_name}"]``.
"""

from __future__ import annotations

import asyncio
import logging

import tonin

logger = logging.getLogger(__name__)


async def main() -> None:
    ctx = await tonin.job.bootstrap("{service_name}-{job_name}")

    logger.info(
        "job starting subject=%s has_pg=%s has_redis=%s",
        ctx.auth.subject,
        ctx.state.has_pg(),
        ctx.state.has_redis(),
    )

    # ----------------------------------------------------------------
    # Replace this block with your actual job logic.
    #
    # - For queue consumers: loop on a fetch-and-process pattern.
    # - For scheduled work: do the work and return.
    # - For outbound calls, propagate ctx.auth into request metadata:
    #
    #     metadata: list[tuple[str, str]] = []
    #     ctx.auth.propagate(metadata)
    #     reply = await stub.SomeRpc(SomeRequest(...), metadata=metadata)
    # ----------------------------------------------------------------

    logger.info("job done")
    await ctx.state.close()


def run() -> None:
    """Sync entry point so pyproject.toml's `[project.scripts]` can wire it."""
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())


if __name__ == "__main__":
    run()
"#,
    )
}

fn emit_claude_md(
    dest: &Path,
    name: &str,
    lang: Lang,
    st: ServiceType,
    wm: Option<WebMode>,
) -> Result<()> {
    let lang_label = match lang {
        Lang::Rust => "Rust",
        Lang::Python => "Python (uv-managed)",
        Lang::Ts => match wm {
            Some(WebMode::Bff) => "TypeScript / Next.js BFF",
            _ => "TypeScript / Vite SPA",
        },
    };
    let st_label = st.as_str();
    let body = format!(
        "# {name}

Service scaffolded by `tonin service new`.

> **Coding agents: read `AGENTS.md` first**, then `docs/README.md`.
> This file is just the quick reference card.

## Quick facts for coding agents

- **Language:** {lang}
- **Type:** {kind}
- **Framework:** `tonin` (the `tonin` framework)
- **Observability:** OTLP traces wired via `Service::new`
- **Config:** see `tonin.toml` for declared deps (database, cache, mesh, etc.)
- **Manifests:** k8s YAML is generated; do not hand-edit. Re-run `tonin k8s generate`.

## How to develop

```sh
# Generate / regenerate k8s manifests after editing tonin.toml
tonin k8s generate

# Validate against a real cluster (--dry-run=server)
tonin k8s validate

# Apply
tonin k8s apply
```

## Living documentation

This service uses the `docs/` convention. Before starting any feature:

- `AGENTS.md` — what an agent must do at start + finish
- `docs/README.md` — full convention
- `docs/roadmap.md` — what's done, active, planned
- `docs/capabilities/` — current state, one .md per capability
- `docs/plans/<feature>/` — `PRD.md` + `TechSpec.md` for in-flight work
- `docs/plans/archive/` — completed plans

## Anti-patterns

- Don't import implementation crates directly. Use the `tonin`
  prelude and let `Service::new` install telemetry + propagation.
- Don't hand-write k8s YAML — re-run `tonin k8s generate`.
- Don't commit `db-secret.yaml` with real values. Use `kubectl create
  secret` or an `ExternalSecret` resource instead.
- Don't write code without a PRD + TechSpec in `docs/plans/<feature>/`.
",
        name = name,
        lang = lang_label,
        kind = st_label,
    );
    std::fs::write(dest.join("CLAUDE.md"), body)?;
    Ok(())
}

fn emit_gitignore(dest: &Path) -> Result<()> {
    std::fs::write(
        dest.join(".gitignore"),
        crate::codegen::default_rust_gitignore(),
    )?;
    Ok(())
}

fn emit_docs_tree(dest: &Path, name: &str) -> Result<()> {
    for (rel, contents) in crate::codegen::default_docs_tree(name) {
        let path = dest.join(&rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&path, contents).with_context(|| format!("writing {}", path.display()))?;
    }
    Ok(())
}

fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() {
        bail!("name cannot be empty");
    }
    if name.contains('/') || name.contains('\\') {
        bail!("name cannot contain path separators");
    }
    let ok = name
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
    if !ok || !name.starts_with(|c: char| c.is_ascii_lowercase()) {
        bail!("name must be kebab-case starting with a lowercase letter (got '{name}')");
    }
    Ok(())
}

fn scaffold(
    dest: &Path,
    lang: Lang,
    st: ServiceType,
    wm: Option<WebMode>,
    vars: &Vars,
) -> Result<()> {
    std::fs::create_dir_all(dest).with_context(|| format!("creating {}", dest.display()))?;

    let lang_dir_path = match (lang, st, wm) {
        (Lang::Ts, ServiceType::Web, Some(WebMode::Spa)) => "ts/web-spa".to_string(),
        (Lang::Ts, ServiceType::Web, Some(WebMode::Bff)) => "ts/web-bff".to_string(),
        (Lang::Ts, ServiceType::Web, None) => "ts/web-spa".to_string(), // safety; shouldn't happen
        (Lang::Ts, ServiceType::Backend, _) => "ts/backend".to_string(),
        _ => lang.as_str().to_string(),
    };
    let lang_dir = TEMPLATES
        .get_dir(&lang_dir_path)
        .ok_or_else(|| anyhow!("no templates at {lang_dir_path}"))?;
    let shared_dir = TEMPLATES
        .get_dir("_shared")
        .ok_or_else(|| anyhow!("missing _shared templates"))?;

    let proto_src = read_shared_file(shared_dir, "proto.tmpl")?;
    // Proto file is named after `service_name_snake` so it doubles as a
    // valid Python module name (kebab-case isn't legal in Python imports).
    let proto_out = dest
        .join("proto")
        .join(format!("{}.proto", vars.service_name_snake));
    write_file(&proto_out, &vars.apply(&proto_src))?;

    walk_and_render(lang_dir, lang_dir, dest, vars)?;

    // Ensure migrations/ exists so the Dockerfile's `COPY migrations` works
    // for every scaffolded service (Rust/Python only; web services don't
    // run migrations). A placeholder .gitkeep keeps the empty dir in git.
    if !matches!(st, ServiceType::Web) {
        let migrations_dir = dest.join("migrations");
        std::fs::create_dir_all(&migrations_dir)
            .with_context(|| format!("creating {}", migrations_dir.display()))?;
        write_file(
            &migrations_dir.join(".gitkeep"),
            "# Place sqlx/refinery migration files here.\n",
        )?;
    }

    Ok(())
}

fn walk_and_render(root: &Dir<'_>, cur: &Dir<'_>, dest: &Path, vars: &Vars) -> Result<()> {
    for f in cur.files() {
        let fname = f.path().file_name().unwrap().to_string_lossy();
        if !fname.ends_with(".tmpl") {
            continue;
        }
        let rel = f.path().strip_prefix(root.path()).unwrap();
        let mut out_rel = rel.to_path_buf();
        let stem = out_rel
            .file_name()
            .unwrap()
            .to_string_lossy()
            .trim_end_matches(".tmpl")
            .to_string();
        out_rel.set_file_name(stem);
        // Substitute template vars in path components too. Lets the
        // Python scaffold use directory names like
        //   server/src/{{ service_name_snake }}_server/
        // and have them resolve to the actual package name. The same
        // Vars::apply that processes file content also processes the
        // path, so any var the user puts in either place works.
        let rendered_path_str = vars.apply(&out_rel.to_string_lossy());
        let out_path = dest.join(PathBuf::from(rendered_path_str));
        let src = std::str::from_utf8(f.contents()).expect("template is utf8");
        write_file(&out_path, &vars.apply(src))?;
    }
    for d in cur.dirs() {
        walk_and_render(root, d, dest, vars)?;
    }
    Ok(())
}

fn read_shared_file(dir: &Dir<'_>, name: &str) -> Result<String> {
    let path = format!("{}/{}", dir.path().display(), name);
    let f = dir
        .get_file(&path)
        .ok_or_else(|| anyhow!("missing template {path}"))?;
    Ok(std::str::from_utf8(f.contents())?.to_string())
}

fn write_file(out: &Path, contents: &str) -> Result<()> {
    if let Some(parent) = out.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(out, contents).with_context(|| format!("writing {}", out.display()))?;
    Ok(())
}

/// `tonin.toml` differs slightly per service shape (web disables MCP,
/// adds `expose = "ingress"`, and records web_mode). Written in code instead
/// of a template so we don't need conditional template logic for one file.
fn write_service_toml(
    dest: &Path,
    vars: &Vars,
    st: ServiceType,
    wm: Option<WebMode>,
) -> Result<()> {
    let (mcp_sidecar, expose_line) = match st {
        ServiceType::Web => (false, "expose      = \"ingress\"\n"),
        ServiceType::Backend => (true, ""),
    };
    let web_mode_line = wm
        .map(|m| format!("web_mode = \"{}\"\n", m.as_str()))
        .unwrap_or_default();
    let body = format!(
        "# tonin.toml — single source of truth for this service.
# `schema` declares the TOML format version this file is written against.
# v1 is backward-compatible: a CLI that knows v2 (when it ships) will still
# read v1 files without changes. Run `tonin service migrate` (when shipped)
# to opt in to a newer schema. Removing this field is fine — the CLI
# defaults to the current schema when it's missing.
schema = \"v1\"

[service]
name     = \"{name}\"
version  = \"0.1.0\"
language = \"{lang}\"
type     = \"{stype}\"
{web_mode}codec    = \"prost\"  # tonic-build is what runs today; buffa codegen plugin is planned

[deploy]
replicas    = 1
mesh        = \"cilium\"   # cilium | istio | linkerd | none
mcp_sidecar = {mcp}
namespace   = \"default\"
{expose}
[resources]
cpu    = \"100m\"
memory = \"128Mi\"

[autoscale]
max_replicas = 3

# Add callees here. Format: <service_name> = \"<namespace>\".
# Network policies are auto-derived from this graph (and its inverse).
[depends_on]
",
        name = vars.service_name,
        lang = vars.language,
        stype = vars.service_type,
        web_mode = web_mode_line,
        mcp = mcp_sidecar,
        expose = expose_line,
    );
    write_file(&dest.join("tonin.toml"), &body)
}

/// Emit an additional client SDK as a sibling folder beside the server's
/// own client. Reuses the per-lang client templates that already power
/// the matching `--lang` scaffolds — so a Rust server can ship a
/// Python client SDK using the exact same template that
/// `--lang python` would generate (just the client side).
fn emit_extra_client(dest: &Path, vars: &Vars, client: ClientLang) -> Result<()> {
    let (template_path, out_subdir) = match client {
        ClientLang::Rust => ("rust/client-rust", "client-rust"),
        ClientLang::Python => ("python/client-python", "client-python"),
        ClientLang::Ts => ("ts/client-ts", "client-ts"),
    };
    let dir = TEMPLATES.get_dir(template_path).ok_or_else(|| {
        anyhow!("no template directory for client-lang {client:?} at {template_path}")
    })?;

    // walk_and_render computes output paths relative to the template
    // root. Since we want output under `<dest>/<out_subdir>/...`, we
    // pass a dest path that already includes the subdir.
    let out_root = dest.join(out_subdir);
    walk_and_render(dir, dir, &out_root, vars)?;

    eprintln!("✓ emitted {} client SDK at {out_subdir}/", client.as_str());
    Ok(())
}

fn pregenerate_k8s(dest: &Path) -> Result<()> {
    let toml = dest.join("tonin.toml");
    let plan = Plan::load(&toml).context("loading freshly-scaffolded tonin.toml")?;
    let files = render::render(&plan).context("rendering k8s manifests")?;
    let k8s_dir = dest.join("k8s");
    std::fs::create_dir_all(&k8s_dir)?;
    for f in &files {
        std::fs::write(k8s_dir.join(&f.path), &f.contents)?;
    }
    eprintln!(
        "✓ pre-generated {} k8s files in {}/k8s/",
        files.len(),
        dest.display()
    );
    Ok(())
}

fn maybe_add_to_workspace(dest: &Path) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let Some(ws_root) = find_workspace_root(&cwd) else {
        return Ok(());
    };
    let ws_toml = ws_root.join("Cargo.toml");

    // The scaffolded service is a 3-folder layout: `server/` and
    // `client-rust/` are each independent Cargo crates. To integrate
    // with a parent workspace we add BOTH as members.
    let dest_abs = dest.canonicalize().unwrap_or_else(|_| cwd.join(dest));
    let rel = dest_abs
        .strip_prefix(&ws_root)
        .ok()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|| dest.display().to_string());
    let server_member = format!("{rel}/server");
    let client_member = format!("{rel}/client-rust");

    let prompt = format!(
        "Detected Cargo workspace at {}.\n  Add '{server_member}' and '{client_member}' as members? [Y/n] ",
        ws_root.display(),
    );
    if !dialoguer::Confirm::new()
        .with_prompt(prompt)
        .default(true)
        .interact()
        .unwrap_or(false)
    {
        eprintln!("skipped workspace integration");
        return Ok(());
    }

    let text = std::fs::read_to_string(&ws_toml)?;
    let mut doc: toml_edit::DocumentMut = text.parse().context("parsing workspace Cargo.toml")?;
    let members = doc
        .get_mut("workspace")
        .and_then(|w| w.as_table_mut())
        .and_then(|t| t.get_mut("members"))
        .and_then(|m| m.as_array_mut())
        .ok_or_else(|| anyhow!("[workspace] members not found in {}", ws_toml.display()))?;
    for m in [&server_member, &client_member] {
        if !members.iter().any(|v| v.as_str() == Some(m.as_str())) {
            members.push(m.clone());
        }
    }
    std::fs::write(&ws_toml, doc.to_string())?;
    eprintln!(
        "✓ added '{server_member}' and '{client_member}' to workspace members in {}",
        ws_toml.display()
    );
    Ok(())
}

fn find_workspace_root(start: &Path) -> Option<PathBuf> {
    let mut cur = Some(start.to_path_buf());
    while let Some(p) = cur {
        let candidate = p.join("Cargo.toml");
        if candidate.exists()
            && let Ok(text) = std::fs::read_to_string(&candidate)
            && let Ok(doc) = text.parse::<toml_edit::DocumentMut>()
            && doc.get("workspace").is_some()
        {
            return Some(p);
        }
        cur = p.parent().map(Path::to_path_buf);
    }
    None
}

fn print_next_steps(
    name: &str,
    lang: Lang,
    st: ServiceType,
    wm: Option<WebMode>,
    jobs: &[String],
    storage: Option<StorageKind>,
    extra_clients: &[ClientLang],
) {
    let wm_label = wm.map(|m| format!(",{}", m.as_str())).unwrap_or_default();
    eprintln!();
    eprintln!(
        "✓ created service '{name}' (lang={}, type={}{wm_label})",
        lang.as_str(),
        st.as_str()
    );
    eprintln!();
    eprintln!("next steps:");
    eprintln!("  cd {name}");
    match (lang, st, wm) {
        (Lang::Rust, _, _) => {
            eprintln!("  cargo build                  # compile the stub server");
            eprintln!("  tonin k8s validate        # check generated YAML against your cluster");
        }
        (Lang::Python, _, _) => {
            eprintln!("  (cd client-python && bash codegen.sh)   # generate client stubs");
            eprintln!("  (cd server        && bash codegen.sh)   # generate server stubs");
            eprintln!("  cd server && uv sync                    # creates .venv");
            eprintln!("  uv run pytest                           # e2e tests");
            eprintln!("  uv run {name}                            # start the server on :50051");
        }
        (Lang::Ts, ServiceType::Web, Some(WebMode::Spa)) => {
            eprintln!("  npm install");
            eprintln!("  npm run gen                  # codegen from proto/");
            eprintln!("  npm run dev                  # Vite dev server on :5173");
        }
        (Lang::Ts, ServiceType::Web, Some(WebMode::Bff)) => {
            eprintln!("  npm install");
            eprintln!("  npm run gen                  # codegen from proto/");
            eprintln!("  npm run dev                  # Next.js dev server on :3000");
        }
        (Lang::Ts, ServiceType::Backend, _) | (Lang::Ts, _, None) => {
            eprintln!("  npm install");
            eprintln!("  npm run gen");
            eprintln!("  npm run dev                  # tsx watch on :50051");
        }
    }
    eprintln!("  tonin k8s apply            # deploy to current kubectl context");
    if !jobs.is_empty() {
        eprintln!();
        eprintln!("background jobs:");
        for job in jobs {
            match lang {
                Lang::Rust => eprintln!("  cargo run --bin {name}-{job}"),
                Lang::Python => eprintln!("  uv run {name}-{job}"),
                Lang::Ts => {}
            }
        }
    }
    if let Some(kind) = storage {
        eprintln!();
        eprintln!("storage ({}):", kind.as_str());
        match kind {
            StorageKind::S3 => {
                eprintln!("  export STORAGE_BUCKET=...                # required");
                eprintln!("  export STORAGE_REGION=us-west-2");
                eprintln!("  export STORAGE_ENDPOINT=http://localhost:9000   # MinIO etc.");
                eprintln!("  export STORAGE_ACCESS_KEY=... STORAGE_SECRET_KEY=...");
            }
            StorageKind::Gcs => {
                eprintln!("  export STORAGE_BUCKET=...                # required");
                eprintln!("  export STORAGE_CREDENTIAL_PATH=/path/to/key.json");
            }
            StorageKind::Azure => {
                eprintln!("  export STORAGE_CONTAINER=...             # required");
                eprintln!("  export STORAGE_ACCOUNT=... STORAGE_ACCESS_KEY=...");
            }
            StorageKind::Local => {
                eprintln!("  export STORAGE_ROOT=./.data              # required");
            }
        }
        eprintln!("  # Boot probe: LIST limit 1. Misconfig → service refuses to start.");
    }
    if !extra_clients.is_empty() {
        eprintln!();
        eprintln!("extra client SDKs:");
        for cl in extra_clients {
            match cl {
                ClientLang::Python => {
                    eprintln!("  (cd client-python && bash codegen.sh)   # regenerate stubs");
                }
                ClientLang::Ts => {
                    eprintln!("  (cd client-ts && npm install && npm run gen)");
                }
                ClientLang::Rust => {
                    eprintln!("  (cd client-rust && cargo build)");
                }
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────
// Workspace layout scaffold (--workspace-layout)
// ─────────────────────────────────────────────────────────────────────────

/// Scaffold the workspace layout: <name>-proto, <name>-server, <name>-rs,
/// plus optional language clients (<name>-py, <name>-ts).
fn emit_workspace_layout(dest: &Path, vars: &Vars, extras: &[ClientLang]) -> Result<()> {
    let name = &vars.service_name;
    let snake = &vars.service_name_snake;
    let camel = &vars.service_camel;
    let proto_mod = &vars.service_proto_module;

    // Proto content from the shared template.
    let shared = TEMPLATES
        .get_dir("_shared")
        .ok_or_else(|| anyhow!("missing _shared templates"))?;
    let proto_content = vars.apply(&read_shared_file(shared, "proto.tmpl")?);

    // ── workspace root ──────────────────────────────────────────────────
    write_file(&dest.join("Cargo.toml"), &ws_cargo_toml(name))?;
    write_file(&dest.join(".cargo/config.toml"), &ws_cargo_config(name))?;
    write_file(&dest.join("CLAUDE.md"), &ws_claude_md(name, snake, camel))?;
    write_file(&dest.join("AGENTS.md"), &ws_agents_md(name))?;
    write_file(&dest.join(".gitignore"), &ws_gitignore())?;

    // ── <name>-proto ─────────────────────────────────────────────────────
    let proto_dir = dest.join(format!("{name}-proto"));
    write_file(&proto_dir.join("Cargo.toml"), &proto_cargo_toml(name))?;
    write_file(&proto_dir.join("build.rs"), &proto_build_rs(snake))?;
    write_file(
        &proto_dir.join(format!("proto/{snake}.proto")),
        &proto_content,
    )?;
    write_file(&proto_dir.join("src/lib.rs"), &proto_lib_rs(snake))?;
    write_file(
        &proto_dir.join("CLAUDE.md"),
        &sub_claude_md(name, "proto", snake, camel, proto_mod),
    )?;
    write_file(&proto_dir.join("AGENTS.md"), "@CLAUDE.md\n")?;
    write_file(&proto_dir.join(".gitignore"), "/target/\n")?;

    // ── <name>-server ────────────────────────────────────────────────────
    let server_dir = dest.join(format!("{name}-server"));
    write_file(&server_dir.join("Cargo.toml"), &server_cargo_toml(name))?;
    write_file(&server_dir.join("tonin.toml"), &server_tonin_toml(name))?;
    write_file(
        &server_dir.join("src/main.rs"),
        &server_main_rs(name, snake, camel, proto_mod),
    )?;
    write_file(&server_dir.join("src/lib.rs"), &server_lib_rs(camel))?;
    write_file(
        &server_dir.join("src/service.rs"),
        &server_service_rs(snake, camel, proto_mod),
    )?;
    write_file(
        &server_dir.join("migrations/.gitkeep"),
        "# sqlx migration files go here.\n",
    )?;
    write_file(
        &server_dir.join("tests/contract_e2e_test.rs"),
        &server_contract_test(snake, camel, proto_mod),
    )?;
    write_file(
        &server_dir.join("CLAUDE.md"),
        &sub_claude_md(name, "server", snake, camel, proto_mod),
    )?;
    write_file(&server_dir.join("AGENTS.md"), "@CLAUDE.md\n")?;
    write_file(&server_dir.join(".gitignore"), &server_gitignore())?;

    // ── <name>-rs ────────────────────────────────────────────────────────
    let rs_dir = dest.join(format!("{name}-rs"));
    write_file(&rs_dir.join("Cargo.toml"), &rs_cargo_toml(name))?;
    write_file(
        &rs_dir.join("src/lib.rs"),
        &rs_lib_rs(name, snake, camel, proto_mod),
    )?;
    write_file(
        &rs_dir.join("CLAUDE.md"),
        &sub_claude_md(name, "rs", snake, camel, proto_mod),
    )?;
    write_file(&rs_dir.join("AGENTS.md"), "@CLAUDE.md\n")?;
    write_file(&rs_dir.join(".gitignore"), "/target/\n")?;

    // ── Makefiles ────────────────────────────────────────────────────────
    write_file(&dest.join("Makefile"), &ws_makefile(name))?;
    write_file(
        &dest.join(format!("{name}-proto/Makefile")),
        &proto_makefile(name),
    )?;
    write_file(
        &dest.join(format!("{name}-server/Makefile")),
        &server_makefile(name),
    )?;
    write_file(
        &dest.join(format!("{name}-rs/Makefile")),
        &rs_makefile(name),
    )?;

    // ── GitHub Actions CI ─────────────────────────────────────────────
    let gh_dir = dest.join(".github/workflows");
    std::fs::create_dir_all(&gh_dir).with_context(|| format!("creating {}", gh_dir.display()))?;
    write_file(&gh_dir.join("ci.yml"), &ws_github_ci_yml(name))?;

    // ── E2E blackbox test crate ───────────────────────────────────────
    let e2e_dir = dest.join(format!("{name}-e2e"));
    std::fs::create_dir_all(e2e_dir.join("tests/common"))
        .with_context(|| format!("creating {name}-e2e/tests/common/"))?;
    write_file(&e2e_dir.join("Cargo.toml"), &e2e_cargo_toml(name))?;
    write_file(&e2e_dir.join("Makefile"), &e2e_makefile(name))?;
    write_file(&e2e_dir.join("tests/common/mod.rs"), &e2e_common_mod(name))?;
    write_file(&e2e_dir.join("tests/contract.rs"), &e2e_contract_test(name))?;

    // Pre-generate k8s manifests from the server's tonin.toml.
    pregenerate_k8s(&server_dir)?;

    // Optional language clients: <name>-py, <name>-ts, etc.
    for &client in extras {
        emit_workspace_client(dest, vars, client)?;
    }

    let extra_labels: Vec<&str> = extras
        .iter()
        .map(|c| match c {
            ClientLang::Python => "greeter-py",
            ClientLang::Ts => "greeter-ts",
            ClientLang::Rust => "",
        })
        .filter(|s| !s.is_empty())
        .collect();
    let extra_str = if extra_labels.is_empty() {
        String::new()
    } else {
        format!(
            " / {}",
            extras
                .iter()
                .filter(|&&c| !matches!(c, ClientLang::Rust))
                .map(|c| format!(
                    "{name}-{}",
                    if matches!(c, ClientLang::Python) {
                        "py"
                    } else {
                        "ts"
                    }
                ))
                .collect::<Vec<_>>()
                .join(" / ")
        )
    };
    eprintln!("✓ workspace: {name}-proto / {name}-server / {name}-rs{extra_str}");
    Ok(())
}

/// Render a language client into the workspace as `<name>-py` or `<name>-ts`.
/// Skips Rust (already covered by `<name>-rs`).
fn emit_workspace_client(dest: &Path, vars: &Vars, client: ClientLang) -> Result<()> {
    let (template_path, suffix) = match client {
        ClientLang::Python => ("python/client-python", "py"),
        ClientLang::Ts => ("ts/client-ts", "ts"),
        ClientLang::Rust => return Ok(()), // already emitted as <name>-rs
    };

    let dir = TEMPLATES
        .get_dir(template_path)
        .ok_or_else(|| anyhow!("no template at {template_path}"))?;

    let name = &vars.service_name;
    let out_dir = dest.join(format!("{name}-{suffix}"));
    walk_and_render(dir, dir, &out_dir, vars)?;

    // Patch the package name from `<name>-client` → `<name>-{suffix}` so
    // the directory name and the published package name align.
    match client {
        ClientLang::Python => patch_file(
            &out_dir.join("pyproject.toml"),
            &format!("{name}-client"),
            &format!("{name}-py"),
        )?,
        ClientLang::Ts => patch_file(
            &out_dir.join("package.json"),
            &format!("\"name\": \"{name}-client\""),
            &format!("\"name\": \"{name}-ts\""),
        )?,
        ClientLang::Rust => {}
    }

    // CLAUDE.md / AGENTS.md / .gitignore
    write_file(
        &out_dir.join("CLAUDE.md"),
        &ws_client_claude_md(name, suffix, vars),
    )?;
    write_file(&out_dir.join("AGENTS.md"), "@CLAUDE.md\n")?;
    write_file(&out_dir.join(".gitignore"), &ws_client_gitignore(client))?;

    eprintln!("✓ emitted {suffix} client → {name}-{suffix}/");
    Ok(())
}

fn patch_file(path: &Path, from: &str, to: &str) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let content =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    std::fs::write(path, content.replace(from, to))
        .with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

// ── file content helpers ────────────────────────────────────────────────

fn ws_cargo_toml(name: &str) -> String {
    format!(
        r#"[workspace]
resolver = "2"
members = [
    "{name}-proto",
    "{name}-server",
    "{name}-rs",
    "{name}-e2e",
]

[workspace.package]
version  = "0.1.0"
edition  = "2024"
license  = "LicenseRef-Commercial"

[workspace.dependencies]
{name}-proto = {{ path = "{name}-proto" }}
{name}-rs    = {{ path = "{name}-rs" }}
tonin        = "0.4"
tonin-client = "0.4"
tonic        = "0.12"
prost        = "0.13"
prost-types  = "0.13"
tokio        = {{ version = "1", features = ["full"] }}
async-trait  = "0.1"
tracing      = "0.1"
thiserror    = "2"
tokio-stream = {{ version = "0.1", features = ["net"] }}
anyhow       = "1"
testcontainers         = "0.27"
testcontainers-modules = {{ version = "0.15", features = ["postgres", "redis"] }}
sqlx = {{ version = "0.8", features = ["postgres", "runtime-tokio-native-tls", "macros"] }}
"#
    )
}

fn ws_cargo_config(name: &str) -> String {
    format!(
        r#"[build]
target-dir = "/tmp/{name}-target"
"#
    )
}

fn ws_claude_md(name: &str, snake: &str, camel: &str) -> String {
    format!(
        r#"# {name} — Claude guidance

Cargo workspace scaffolded by `tonin service new`. Read this file first,
then the crate-level CLAUDE.md for the specific code you're touching.

## Crate map

| Crate | Role | Published |
|-------|------|-----------|
| `{name}-proto` | gRPC contract (`{snake}.v1`) — source of truth for the wire format | Yes |
| `{name}-server` | tonin gRPC binary (`{camel}` service) | Binary only |
| `{name}-rs` | Rust client library for callers | Yes |

Extra clients (if scaffolded): `{name}-py` (Python), `{name}-ts` (TypeScript).

## Key commands

```bash
cargo build && cargo test --workspace
cargo clippy --workspace -- -D warnings
cd {name}-server && tonin k8s generate   # regenerate k8s/ manifests
```

## Versioning policy

| Layer | Scheme | Breaking change rule |
|-------|--------|----------------------|
| Proto API | `{snake}.v1` package; bump to `v2` only on wire break | Field renumber, type change, removal |
| DB schema | Sequential `0001_*.sql`; files immutable once merged | Any destructive change |
| Rust crates | Semver — MAJOR tracks proto MAJOR | Any non-backward-compatible API change |
| Python pkg | Semver — same MAJOR as Rust | Same |
| npm pkg | Semver — same MAJOR as Rust | Same |

## Backward compatibility — non-negotiable

### Proto
- **Safe:** add field (new number), add enum value, add RPC, rename Rust binding
- **UNSAFE — never without bumping to v2:**
  - Renumber a field (wire breaking)
  - Change a field's type
  - Remove a field — instead add `reserved 3;` and `reserved "old_name";`

### Database migrations
- **Safe:** `ADD COLUMN` with `DEFAULT`, `CREATE INDEX CONCURRENTLY`, `CREATE TABLE`
- **UNSAFE — use two-step deploy:**
  - `DROP COLUMN` → stop using it in code (deploy), then drop in a later migration
  - `RENAME COLUMN` → add new + backfill + drop old (three separate deploys)
  - `ALTER COLUMN TYPE` → add new column, migrate data, drop old (three deploys)
- Migration files are **immutable once merged** — never edit a committed migration

## Workspace-level rules
- `edition = "2024"`, `license = "LicenseRef-Commercial"` on all crates (inherited via workspace)
- Cargo target dir: `/tmp/{name}-target` (`.cargo/config.toml`) — never commit `/target/`
- Never hand-edit `k8s/*.yaml` — always regenerate with `tonin k8s generate`
- `k8s/secrets.yaml` and `k8s/db-secret.yaml` are auto-gitignored; never commit with real values
"#
    )
}

fn ws_agents_md(name: &str) -> String {
    format!(
        r#"@CLAUDE.md

# {name} — Agent instructions

> Universal instructions for any AI agent (Claude Code, Cursor, Windsurf, Copilot…).
> Full detail in `CLAUDE.md` (auto-loaded above).

## Essential commands

```bash
cargo build && cargo test --workspace
cargo clippy --workspace -- -D warnings
cd {name}-server && tonin k8s generate
```

## Non-negotiable rules

1. **Proto field numbers are immutable** — never renumber; add `reserved N;` instead of removing.
2. **DB migrations are immutable once merged** — never edit a committed `.sql` file.
3. **Only additive changes** to proto and DB schema without a version bump.
4. **Never hand-edit** generated `k8s/*.yaml` — always re-run `tonin k8s generate`.
5. **Never commit** `k8s/secrets.yaml` or `k8s/db-secret.yaml` with real values.
6. All crates: `edition = "2024"`, `license = "LicenseRef-Commercial"`.
7. Backward-compat breakage requires a proto package version bump (`v1` → `v2`).
"#
    )
}

fn ws_gitignore() -> String {
    r#"/target/
Cargo.lock

.DS_Store
Thumbs.db
.idea/
.vscode/
*.swp
*.swo
.env
.env.*
!.env.example
"#
    .to_string()
}

fn proto_cargo_toml(name: &str) -> String {
    format!(
        r#"[package]
name        = "{name}-proto"
description = "Generated gRPC types for {name} ({name}.v1)"
version.workspace = true
edition.workspace = true
license.workspace = true

[dependencies]
tonic       = {{ workspace = true }}
prost       = {{ workspace = true }}
prost-types = {{ workspace = true }}

[build-dependencies]
tonic-build = "0.12"
"#
    )
}

fn proto_build_rs(snake: &str) -> String {
    format!(
        r#"fn main() -> Result<(), Box<dyn std::error::Error>> {{
    if std::env::var("TONIN_SKIP_PROTOC").is_ok() {{
        return Ok(());
    }}
    let wkt = std::env::var("PROTOC_INCLUDE").ok();
    let mut includes: Vec<&str> = vec!["proto"];
    let wkt_owned;
    if let Some(ref w) = wkt {{
        wkt_owned = w.clone();
        includes.push(&wkt_owned);
    }}
    tonic_build::configure().compile_protos(&["proto/{snake}.proto"], &includes)?;
    Ok(())
}}
"#
    )
}

fn proto_lib_rs(snake: &str) -> String {
    format!("tonic::include_proto!(\"{snake}.v1\");\n")
}

fn server_cargo_toml(name: &str) -> String {
    format!(
        r#"[package]
name    = "{name}-server"
version.workspace = true
edition.workspace = true
license.workspace = true

[[bin]]
name = "{name}"
path = "src/main.rs"

[lib]
path = "src/lib.rs"

[dependencies]
{name}-proto = {{ workspace = true }}
tonin        = {{ workspace = true }}
tonic        = {{ workspace = true }}
prost        = {{ workspace = true }}
prost-types  = {{ workspace = true }}
tokio        = {{ workspace = true }}
async-trait  = {{ workspace = true }}
tracing      = {{ workspace = true }}
thiserror    = {{ workspace = true }}

[dev-dependencies]
tokio-stream = {{ workspace = true }}
"#
    )
}

fn server_tonin_toml(name: &str) -> String {
    format!(
        r#"schema = "v1"

[service]
name    = "{name}"
version = "0.1.0"
codec   = "prost"

[deploy]
replicas    = 1
mesh        = "cilium"
mcp_sidecar = true
namespace   = "default"

[resources]
cpu    = "100m"
memory = "128Mi"

[autoscale]
max_replicas = 3

[database]
engine = "postgres"

[cache]
engine = "redis"

# Services allowed to call this one (ingress allowlist for CiliumNetworkPolicy).
# Format: <service-name> = "<namespace>"
[callers]
# gateway = "default"
"#
    )
}

fn server_main_rs(name: &str, snake: &str, camel: &str, proto_mod: &str) -> String {
    format!(
        r#"use {snake}_proto::{proto_mod}_server::{camel}Server;
use {snake}_server::{camel}Service;
use tonin::prelude::*;

#[tokio::main]
async fn main() -> tonin::Result<()> {{
    Service::new("{name}")
        .handler({camel}Server::new({camel}Service::default()))
        .run()
        .await
}}
"#
    )
}

fn server_lib_rs(camel: &str) -> String {
    format!(
        r#"pub mod service;
pub use service::{camel}Service;
"#
    )
}

fn server_service_rs(snake: &str, camel: &str, proto_mod: &str) -> String {
    format!(
        r#"use tonic::{{Request, Response, Status}};
use {snake}_proto::{{{proto_mod}_server::{camel}, HelloReply, HelloRequest}};

/// `{camel}` gRPC service — stub implementation.
/// Replace each `unimplemented` return with real logic.
#[derive(Debug, Default)]
pub struct {camel}Service;

#[tonic::async_trait]
impl {camel} for {camel}Service {{
    async fn say_hello(
        &self,
        _req: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {{
        Err(Status::unimplemented("stub: implement say_hello"))
    }}
}}
"#
    )
}

fn server_contract_test(snake: &str, camel: &str, proto_mod: &str) -> String {
    format!(
        r#"//! Contract tests — verifies all RPCs are reachable.
//! Starts an in-process tonic server; all stubs return UNIMPLEMENTED.

use std::time::Duration;
use {snake}_proto::{{{proto_mod}_client::{camel}Client, {proto_mod}_server::{camel}Server, HelloRequest}};
use {snake}_server::{camel}Service;
use tokio::net::TcpListener;
use tokio_stream::wrappers::TcpListenerStream;

async fn start_server() -> String {{
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {{
        tonic::transport::Server::builder()
            .add_service({camel}Server::new({camel}Service::default()))
            .serve_with_incoming(TcpListenerStream::new(listener))
            .await
            .unwrap();
    }});
    tokio::time::sleep(Duration::from_millis(50)).await;
    format!("http://{{addr}}")
}}

#[tokio::test]
async fn test_say_hello_stub_returns_unimplemented() {{
    let uri = start_server().await;
    let mut client = {camel}Client::connect(uri).await.unwrap();
    let err = client
        .say_hello(HelloRequest {{ name: "test".into() }})
        .await
        .unwrap_err();
    assert_eq!(err.code(), tonic::Code::Unimplemented);
}}
"#
    )
}

fn server_gitignore() -> String {
    r#"/target/
.env
.env.*
!.env.example

# tonin: generated secret manifests — never commit plaintext values
k8s/secrets.yaml
k8s/db-secret.yaml
"#
    .to_string()
}

fn rs_cargo_toml(name: &str) -> String {
    format!(
        r#"[package]
name        = "{name}-rs"
description = "Rust client for the {name} service — pre-wired with tonin-client coalescing"
version.workspace = true
edition.workspace = true
license.workspace = true

[dependencies]
{name}-proto = {{ workspace = true }}
tonin-client = {{ workspace = true }}
tonic        = {{ workspace = true }}
tokio        = {{ workspace = true }}
tracing      = {{ workspace = true }}
"#
    )
}

fn rs_lib_rs(name: &str, snake: &str, camel: &str, proto_mod: &str) -> String {
    format!(
        r#"//! Rust client for the {name} service.
//!
//! ```no_run
//! use {snake}_rs::{camel}Client;
//! use tonic::transport::Endpoint;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {{
//! let ep = Endpoint::from_static("http://{name}.default.svc.cluster.local:50051");
//! let client = {camel}Client::connect(ep).await?;
//! // client.inner.say_hello(...).await?;
//! # Ok(())
//! # }}
//! ```

pub use {snake}_proto as proto;

use {snake}_proto::{proto_mod}_client::{camel}Client as Raw{camel}Client;
use tonin_client::client::CoalescingClient;
use tonic::transport::Channel;

/// Pre-wired {camel} service client with singleflight coalescing (default-on).
/// Wrap in `Arc` to share cheaply across tasks.
pub struct {camel}Client {{
    channel: Channel,
}}

impl {camel}Client {{
    /// Connect to the {name} service.
    pub async fn connect(
        endpoint: tonic::transport::Endpoint,
    ) -> Result<Self, tonic::transport::Error> {{
        let channel = endpoint.connect().await?;
        Ok(Self {{ channel }})
    }}

    /// Returns the gRPC client wrapped in `CoalescingClient`.
    pub fn inner(&self) -> CoalescingClient<Raw{camel}Client<Channel>> {{
        CoalescingClient::new(Raw{camel}Client::new(self.channel.clone()))
    }}
}}
"#
    )
}

fn sub_claude_md(
    name: &str,
    crate_kind: &str,
    snake: &str,
    camel: &str,
    proto_mod: &str,
) -> String {
    let header = format!("@../CLAUDE.md\n\n# {name}-{crate_kind} — Claude guidance\n");
    let body = match crate_kind {
        "proto" => format!(
            r#"
Contract crate. One proto file → generated Rust types consumed by every other crate.

## Commands

```bash
cargo build -p {name}-proto          # runs tonic-build codegen
TONIN_SKIP_PROTOC=1 cargo check      # skip codegen when protoc unavailable
```

## Proto versioning — backward compatibility

Package `{snake}.v1`. Bump to `v2` only when a wire-breaking change is unavoidable.

### Safe (additive — no version bump needed)
```proto
// Add a new field — always use a fresh number, never reuse a deleted one
string new_field = 5;

// Add a new RPC
rpc NewMethod (NewRequest) returns (NewResponse);

// Add a new enum value
enum Status {{ UNKNOWN = 0; ACTIVE = 1; NEW_VALUE = 2; }}
```

### Unsafe — requires `v2` package
```proto
// NEVER do any of these in v1:
// - Renumber: string name = 1; → string name = 2;   (wire breaking)
// - Change type: string id = 1; → int64 id = 1;     (wire breaking)
// - Remove a field without reserving its number
```

### Deprecating a field (safe alternative to removal)
```proto
string old_field = 3 [deprecated = true];
// After all clients have migrated:
reserved 3;
reserved "old_field";
```

## Rust codegen paths

| Proto element | Generated Rust |
|---------------|----------------|
| `service {camel}` | `{proto_mod}_server::{camel}` (trait) + `{proto_mod}_server::{camel}Server` (wrapper) |
| `service {camel}` | `{proto_mod}_client::{camel}Client` (tonic client) |
| `message HelloRequest` | `{snake}_proto::HelloRequest` |
| `google.protobuf.Timestamp` | `prost_types::Timestamp` |
| `google.protobuf.Empty` RPC return | `()` in tonic trait |
"#
        ),
        "server" => format!(
            r#"
tonin gRPC binary. Handlers start as stubs (`UNIMPLEMENTED`); fill in real logic milestone by milestone.

## Commands

```bash
cargo build -p {name}-server
cargo test --test contract_e2e_test   # in-process gRPC, no Docker needed
cargo test -p {name}-server           # all tests including unit tests
tonin k8s generate                    # regenerate k8s/*.yaml + update .gitignore
```

## Rust / tonin coding standards

- **Async-first.** All I/O is async. Never block a tokio thread (`std::fs`, `std::net`, CPU loops).
  Use `tokio::fs`, `tokio::net`, or `tokio::task::spawn_blocking` for blocking work.
- **No panics in handler code.** Return `Result<Response<T>, Status>`. Map errors:
  ```rust
  .map_err(|e| Status::internal(format!("db error: {{e}}")))?
  ```
- **No locks across `.await`.** Clone data out of a `Mutex`/`RwLock` before awaiting.
- **`#[tonic::async_trait]`** on every `impl {camel} for {camel}Service` block.
- **clippy pedantic** — `cargo clippy -- -D warnings` must be clean before merging.

## Implementing a stub handler

```rust
// Before: stub
async fn say_hello(&self, _req: Request<HelloRequest>) -> Result<Response<HelloReply>, Status> {{
    Err(Status::unimplemented("stub"))
}}

// After: real implementation
async fn say_hello(&self, req: Request<HelloRequest>) -> Result<Response<HelloReply>, Status> {{
    let inner = req.into_inner();
    // 1. validate input
    // 2. call service layer (inject via self.state)
    // 3. return response
    Ok(Response::new(HelloReply {{ message: format!("hello {{}}", inner.name) }}))
}}
```

## Test rules

| Scope | Location | Infrastructure |
|-------|----------|----------------|
| Handler logic, error paths | Inline `#[cfg(test)] mod tests {{}}` | Mock deps |
| All RPCs reachable | `tests/contract_e2e_test.rs` | In-process tonic server |
| Migrations apply cleanly | `tests/migrations_test.rs` (add when ready) | testcontainers Postgres |
| Tenant isolation | E2E (add when authz is live) | Real DB |

Test naming: `test_<function>_<scenario>_<expected>`.

## DB migration safety

Files in `migrations/` are **immutable once merged**. Never edit a committed file.

```sql
-- SAFE: always provide a DEFAULT so existing rows are not broken
ALTER TABLE foo ADD COLUMN bar TEXT NOT NULL DEFAULT '';

-- SAFE: non-blocking index creation
CREATE INDEX CONCURRENTLY idx_foo_bar ON foo(bar);

-- UNSAFE: dropping a column requires two deploys
-- Deploy 1: stop reading/writing the column in code
-- Deploy 2: ALTER TABLE foo DROP COLUMN bar;  (new migration file)
```
"#
        ),
        "rs" => format!(
            r#"
Rust client library. Any service calling `{name}` depends on this crate only —
never import `{name}-proto` or `tonic` directly in callers.

## Usage

```rust
use {snake}_rs::{camel}Client;
use tonic::transport::Endpoint;

// Construct once; wrap in Arc to share across tasks.
let ep = Endpoint::from_static("http://{name}.default.svc.cluster.local:50051");
let client = std::sync::Arc::new({camel}Client::connect(ep).await?);

// Each call returns a CoalescingClient-wrapped tonic client.
let mut c = client.inner();
let reply = c.say_hello({snake}_proto::HelloRequest {{ name: "world".into() }}).await?;
```

## Rust standards for this crate

- **Thin wrapper only.** No business logic, no DB access, no inbound auth middleware.
- **Error propagation.** Return `Result<T, tonic::Status>` — never swallow errors.
- **No retry logic.** The mesh (Cilium/Istio) handles retries. `CoalescingClient` handles
  deduplication. Adding retry here creates double-retry bugs.
- **`Arc<{camel}Client>`** — the `{camel}Client` struct holds a `Channel` (internally ref-counted),
  so wrapping in `Arc` is the canonical share-across-tasks pattern.

## Adding a convenience method

```rust
impl {camel}Client {{
    /// One-line helper that hides the inner() unwrap from callers.
    pub async fn say_hello(&self, name: impl Into<String>) -> Result<{snake}_proto::HelloReply, tonic::Status> {{
        self.inner()
            .say_hello({snake}_proto::HelloRequest {{ name: name.into() }})
            .await
            .map(|r| r.into_inner())
    }}
}}
```

Keep helpers thin — no caching, no validation, no retry.
"#
        ),
        _ => String::new(),
    };
    format!("{header}{body}")
}

fn ws_client_claude_md(name: &str, suffix: &str, vars: &Vars) -> String {
    let camel = &vars.service_camel;
    let snake = &vars.service_name_snake;
    match suffix {
        "py" => format!(
            r#"@../CLAUDE.md

# {name}-py — Claude guidance

Python gRPC client for the `{name}` service.

## Commands

```bash
bash codegen.sh          # regenerate _pb/ stubs from ../{name}-proto/proto/
uv sync                  # install / sync deps
uv run python -c "from {snake}_client import {camel}Stub"   # smoke-test import
```

**Do not commit `src/{snake}_client/_pb/`** — it is gitignored and regenerated by `codegen.sh`.
Run `codegen.sh` whenever `../{name}-proto/proto/{snake}.proto` changes.

## Usage

```python
from __future__ import annotations
import grpc.aio
from {snake}_client import {camel}Stub, HelloRequest, AuthCtx

async def call(token: str) -> None:
    async with grpc.aio.insecure_channel("{name}.default.svc.cluster.local:50051") as ch:
        stub = {camel}Stub(ch)
        metadata: list[tuple[str, str]] = []
        AuthCtx.from_bearer(token).propagate(metadata)
        reply = await stub.SayHello(HelloRequest(name="world"), metadata=metadata)
        print(reply.message)
```

## Python coding standards

- **Type hints everywhere.** Every function signature must be fully annotated.
  `from __future__ import annotations` at the top of every file.
- **`grpc.aio` only** — never use synchronous `grpc` in async contexts.
- **`async with` for channels** — always close channels when done; use context managers.
- **Explicit error handling.** Catch `grpc.aio.AioRpcError`, check `.code()`,
  never swallow errors with bare `except Exception: pass`.
- **No business logic here.** This crate is a thin client wrapper only.

## Versioning

Package name: `{name}-py`. Semver tracks the server MAJOR version.
When the proto bumps to `v2`, this package bumps to `2.0.0`.

## Proto stubs versioning

`_pb/` stubs are derived from `{name}-proto`. When the proto adds a field or RPC:
1. The field/RPC is automatically available after re-running `codegen.sh`.
2. Old stubs still work (protobuf backward compatibility) — unknown fields are ignored.
3. Removing or renumbering a field in proto → update this client at the same time.
"#
        ),
        "ts" => format!(
            r#"@../CLAUDE.md

# {name}-ts — Claude guidance

TypeScript gRPC client for the `{name}` service (Node + grpc-web compatible).

## Commands

```bash
npm install              # install deps
npm run gen              # regenerate src/gen/ from ../{name}-proto/proto/
npm run build            # compile TypeScript → dist/
```

**Do not commit `src/gen/`** — it is gitignored and regenerated by `npm run gen`.
Run `npm run gen` whenever `../{name}-proto/proto/{snake}.proto` changes.

## Usage (Node / server-side)

```typescript
import {{ credentials, ServiceError }} from "@grpc/grpc-js";
import {{ {camel}Client }} from "./{snake}";  // from src/gen/

const client = new {camel}Client(
  "{name}.default.svc.cluster.local:50051",
  credentials.createInsecure(),
);

client.sayHello({{ name: "world" }}, (err: ServiceError | null, res) => {{
  if (err) throw err;
  console.log(res.message);
}});
```

## TypeScript coding standards

- **Strict mode.** `tsconfig.json` sets `strict: true` — never disable it.
  No `any`, no `@ts-ignore`, no `as unknown as T`.
- **`undefined` over `null`.** Use optional chaining (`?.`) and nullish coalescing (`??`).
- **Explicit return types** on all exported functions and class methods.
- **`async`/`await` over callbacks** — wrap grpc callbacks in promises:
  ```typescript
  const reply = await new Promise<HelloReply>((resolve, reject) =>
    client.sayHello({{ name: "world" }}, (err, res) => err ? reject(err) : resolve(res))
  );
  ```
- **ESM modules** (`"type": "module"` in package.json). Always use `.js` extensions
  in import paths even when importing `.ts` files (tsc/Node ESM requirement).
- **No business logic here.** This package is a thin client wrapper only.

## Versioning

Package name: `{name}-ts`. Semver tracks the server MAJOR version.
When the proto bumps to `v2`, this package bumps to `2.0.0`.

## Proto stubs versioning

`src/gen/` is derived from `{name}-proto` via `buf`. When the proto adds a field or RPC:
1. Run `npm run gen` — new fields/RPCs appear automatically.
2. Old code still compiles (protobuf adds fields, never removes in a compatible change).
3. If a field is removed from proto → update this client in the same PR.
"#
        ),
        _ => format!("@../CLAUDE.md\n\n# {name}-{suffix}\n"),
    }
}

fn ws_client_gitignore(client: ClientLang) -> String {
    match client {
        ClientLang::Python => r#"# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
.venv/

# Generated proto stubs — regenerate with codegen.sh
src/*/_pb/
"#
        .to_string(),
        ClientLang::Ts => r#"# Node / TypeScript
node_modules/
dist/

# Generated proto stubs — regenerate with npm run gen
src/gen/
"#
        .to_string(),
        ClientLang::Rust => String::new(),
    }
}

fn ws_makefile(name: &str) -> String {
    format!(
        ".DEFAULT_GOAL := help\n\
         \n\
         .PHONY: help install build check fmt fmt-check lint test test-e2e e2e ci k8s-generate clean \\\n\
         \t\tproto server rs\n\
         \n\
         # ── help ─────────────────────────────────────────────────────────────────────\n\
         help:\n\
         \t@grep -E '^[a-zA-Z_-]+:.*?##' $(MAKEFILE_LIST) | \\\n\
         \t  awk 'BEGIN {{FS = \":.*?## \"}}; {{printf \"  %-18s %s\\n\", $$1, $$2}}'\n\
         \n\
         # ── setup ─────────────────────────────────────────────────────────────────────\n\
         install: ## Verify required tools are installed (cargo, uv, npm)\n\
         \t@command -v cargo >/dev/null 2>&1 || (echo \"cargo not found\" && exit 1)\n\
         \t@command -v uv >/dev/null 2>&1 || (echo \"uv not found. Install: pip install uv\" && exit 1)\n\
         \t@command -v npm >/dev/null 2>&1 || (echo \"npm not found. Install Node.js from nodejs.org\" && exit 1)\n\
         \t@echo \"✓ All required tools found: cargo, uv, npm\"\n\
         \n\
         # ── workspace-wide ────────────────────────────────────────────────────────────\n\
         build: ## Build all crates (debug)\n\
         \tcargo build --workspace\n\
         \n\
         check: ## Type-check all crates + all targets\n\
         \tcargo check --workspace --all-targets\n\
         \n\
         fmt: ## Format all code\n\
         \tcargo fmt --all\n\
         \n\
         fmt-check: ## Check formatting (CI)\n\
         \tcargo fmt --all -- --check\n\
         \n\
         lint: ## Clippy -D warnings across workspace\n\
         \tcargo clippy --workspace --all-targets -- -D warnings\n\
         \n\
         test: ## Unit + contract tests (no Docker required)\n\
         \tcargo nextest run --workspace\n\
         \n\
         test-e2e: ## Run all E2E tests in {name}-e2e/ (requires Docker)\n\
         \t$(MAKE) -C {name}-e2e test\n\
         \n\
         e2e: ## Run all E2E tests in {name}-e2e/ (requires Docker)\n\
         \t$(MAKE) -C {name}-e2e test\n\
         \n\
         ci: fmt-check lint test ## Full CI gate (fmt + lint + nextest)\n\
         \n\
         k8s-generate: ## Regenerate k8s manifests from tonin.toml\n\
         \t$(MAKE) -C {name}-server k8s-generate\n\
         \n\
         clean: ## Remove build artifacts\n\
         \tcargo clean\n\
         \n\
         # ── per-crate delegates ───────────────────────────────────────────────────────\n\
         proto: ## Run ci in {name}-proto/\n\
         \t$(MAKE) -C {name}-proto ci\n\
         \n\
         server: ## Run ci in {name}-server/\n\
         \t$(MAKE) -C {name}-server ci\n\
         \n\
         rs: ## Run ci in {name}-rs/\n\
         \t$(MAKE) -C {name}-rs ci\n"
    )
}

fn proto_makefile(name: &str) -> String {
    format!(
        ".DEFAULT_GOAL := help\n\
         \n\
         .PHONY: help build check fmt fmt-check lint ci\n\
         \n\
         help:\n\
         \t@grep -E '^[a-zA-Z_-]+:.*?##' $(MAKEFILE_LIST) | \\\n\
         \t  awk 'BEGIN {{FS = \":.*?## \"}}; {{printf \"  %-16s %s\\n\", $$1, $$2}}'\n\
         \n\
         build: ## Compile {name}-proto (runs protoc)\n\
         \tcargo build -p {name}-proto\n\
         \n\
         check: ## Type-check without codegen\n\
         \tTONIN_SKIP_PROTOC=1 cargo check -p {name}-proto\n\
         \n\
         fmt: ## Format\n\
         \tcargo fmt -p {name}-proto\n\
         \n\
         fmt-check: ## Check formatting (CI)\n\
         \tcargo fmt -p {name}-proto -- --check\n\
         \n\
         lint: ## Clippy\n\
         \tcargo clippy -p {name}-proto -- -D warnings\n\
         \n\
         ci: fmt-check lint build ## fmt + lint + build\n"
    )
}

fn server_makefile(name: &str) -> String {
    format!(
        ".DEFAULT_GOAL := help\n\
         \n\
         .PHONY: help build check fmt fmt-check lint test test-contract test-migrations \\\n\
         \t\tk8s-generate migrate ci\n\
         \n\
         help:\n\
         \t@grep -E '^[a-zA-Z_-]+:.*?##' $(MAKEFILE_LIST) | \\\n\
         \t  awk 'BEGIN {{FS = \":.*?## \"}}; {{printf \"  %-20s %s\\n\", $$1, $$2}}'\n\
         \n\
         build: ## Build {name}-server binary\n\
         \tcargo build -p {name}-server\n\
         \n\
         check: ## Type-check all targets\n\
         \tcargo check -p {name}-server --all-targets\n\
         \n\
         fmt: ## Format\n\
         \tcargo fmt -p {name}-server\n\
         \n\
         fmt-check: ## Check formatting (CI)\n\
         \tcargo fmt -p {name}-server -- --check\n\
         \n\
         lint: ## Clippy -D warnings\n\
         \tcargo clippy -p {name}-server -- -D warnings\n\
         \n\
         test: ## All tests (contract only — no Docker)\n\
         \tcargo nextest run --test contract_e2e_test\n\
         \n\
         test-contract: ## In-process gRPC contract smoke tests\n\
         \tcargo nextest run --test contract_e2e_test\n\
         \n\
         test-migrations: ## Migrations test (requires Docker / Rancher Desktop)\n\
         \tcargo nextest run --test migrations_test\n\
         \n\
         k8s-generate: ## Regenerate k8s manifests via tonin\n\
         \ttonin k8s generate\n\
         \n\
         migrate: ## Apply migrations to DATABASE_URL (dev/local)\n\
         \tsqlx migrate run --source migrations\n\
         \n\
         ci: fmt-check lint test ## fmt + lint + nextest\n"
    )
}

fn rs_makefile(name: &str) -> String {
    format!(
        ".DEFAULT_GOAL := help\n\
         \n\
         .PHONY: help build check fmt fmt-check lint test ci\n\
         \n\
         help:\n\
         \t@grep -E '^[a-zA-Z_-]+:.*?##' $(MAKEFILE_LIST) | \\\n\
         \t  awk 'BEGIN {{FS = \":.*?## \"}}; {{printf \"  %-16s %s\\n\", $$1, $$2}}'\n\
         \n\
         build: ## Build {name}-rs\n\
         \tcargo build -p {name}-rs\n\
         \n\
         check: ## Type-check all targets\n\
         \tcargo check -p {name}-rs --all-targets\n\
         \n\
         fmt: ## Format\n\
         \tcargo fmt -p {name}-rs\n\
         \n\
         fmt-check: ## Check formatting (CI)\n\
         \tcargo fmt -p {name}-rs -- --check\n\
         \n\
         lint: ## Clippy -D warnings\n\
         \tcargo clippy -p {name}-rs -- -D warnings\n\
         \n\
         test: ## Unit + doc tests\n\
         \tcargo nextest run -p {name}-rs\n\
         \n\
         ci: fmt-check lint test ## fmt + lint + nextest\n"
    )
}

fn ws_github_ci_yml(name: &str) -> String {
    format!(
        "name: CI\n\
         \n\
         on:\n\
         \
           push:\n\
         \
             branches: [main]\n\
         \
           pull_request:\n\
         \
             branches: [main]\n\
         \n\
         env:\n\
         \
           CARGO_TERM_COLOR: always\n\
         \
           PROTOC_INCLUDE: /usr/local/include\n\
         \
           RUSTFLAGS: \"-D warnings\"\n\
         \n\
         jobs:\n\
         \
           ci:\n\
         \
             name: fmt · lint · test\n\
         \
             runs-on: ubuntu-latest\n\
         \
             steps:\n\
         \
               - uses: actions/checkout@v4\n\
         \n\
         \
               - name: Install Rust toolchain\n\
         \
                 uses: dtolnay/rust-toolchain@stable\n\
         \
                 with:\n\
         \
                   components: rustfmt, clippy\n\
         \n\
         \
               - name: Install protoc\n\
         \
                 uses: arduino/setup-protoc@v3\n\
         \
                 with:\n\
         \
                   repo-token: ${{{{ secrets.GITHUB_TOKEN }}}}\n\
         \n\
         \
               - name: Cache cargo registry + target\n\
         \
                 uses: actions/cache@v4\n\
         \
                 with:\n\
         \
                   path: |\n\
         \
                     ~/.cargo/registry\n\
         \
                     ~/.cargo/git\n\
         \
                     /tmp/{name}-target\n\
         \
                   key: ${{{{ runner.os }}}}-cargo-${{{{ hashFiles('**/Cargo.lock') }}}}\n\
         \
                   restore-keys: ${{{{ runner.os }}}}-cargo-\n\
         \n\
         \
               - name: Check formatting\n\
         \
                 run: make fmt-check\n\
         \n\
         \
               - name: Lint\n\
         \
                 run: make lint\n\
         \n\
         \
               - name: Test (no Docker)\n\
         \
                 run: make test\n\
         \n\
           migrations:\n\
         \
             name: migrations test\n\
         \
             runs-on: ubuntu-latest\n\
         \
             services:\n\
         \
               postgres:\n\
         \
                 image: postgres:17\n\
         \
                 env:\n\
         \
                   POSTGRES_USER: postgres\n\
         \
                   POSTGRES_PASSWORD: postgres\n\
         \
                   POSTGRES_DB: {name}_test\n\
         \
                 ports: [\"5432:5432\"]\n\
         \
                 options: >-\n\
         \
                   --health-cmd pg_isready\n\
         \
                   --health-interval 5s\n\
         \
                   --health-timeout 5s\n\
         \
                   --health-retries 10\n\
         \
             steps:\n\
         \
               - uses: actions/checkout@v4\n\
         \n\
         \
               - name: Install Rust toolchain\n\
         \
                 uses: dtolnay/rust-toolchain@stable\n\
         \n\
         \
               - name: Install protoc\n\
         \
                 uses: arduino/setup-protoc@v3\n\
         \
                 with:\n\
         \
                   repo-token: ${{{{ secrets.GITHUB_TOKEN }}}}\n\
         \n\
         \
               - name: Cache cargo\n\
         \
                 uses: actions/cache@v4\n\
         \
                 with:\n\
         \
                   path: |\n\
         \
                     ~/.cargo/registry\n\
         \
                     ~/.cargo/git\n\
         \
                     /tmp/{name}-target\n\
         \
                   key: ${{{{ runner.os }}}}-cargo-${{{{ hashFiles('**/Cargo.lock') }}}}\n\
         \
                   restore-keys: ${{{{ runner.os }}}}-cargo-\n\
         \n\
         \
               - name: Run migrations test\n\
         \
                 env:\n\
         \
                   DATABASE_URL: postgres://postgres:postgres@localhost:5432/{name}_test\n\
         \
                   DOCKER_HOST: unix:///var/run/docker.sock\n\
         \
                 run: make test-e2e\n"
    )
}

// ─────────────────────────────────────────────────────────────────────────
// E2E crate content helpers
// ─────────────────────────────────────────────────────────────────────────

fn e2e_cargo_toml(name: &str) -> String {
    format!(
        r#"[package]
name    = "{name}-e2e"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false

# No src/ — this package contains only integration tests in tests/.
# Each file under tests/ is a separate test binary that starts a real
# server against testcontainer Postgres + Redis and connects via {name}-rs.

[dev-dependencies]
{name}-proto  = {{ workspace = true }}
{name}-rs     = {{ workspace = true }}
{name}-server = {{ path = "../{name}-server" }}
tonic           = {{ workspace = true }}
tokio           = {{ workspace = true }}
tokio-stream    = {{ workspace = true }}
testcontainers         = {{ workspace = true }}
testcontainers-modules = {{ workspace = true }}
sqlx    = {{ workspace = true }}
anyhow  = {{ workspace = true }}
"#
    )
}

fn e2e_makefile(name: &str) -> String {
    format!(
        ".DEFAULT_GOAL := help\n\
         \n\
         .PHONY: help check test ci\n\
         \n\
         help:\n\
         \t@grep -E '^[a-zA-Z_-]+:.*?##' $(MAKEFILE_LIST) | \\\n\
         \t  awk 'BEGIN {{FS = \":.*?## \"}}; {{printf \"  %-18s %s\\n\", $$1, $$2}}'\n\
         \n\
         check: ## Type-check without Docker\n\
         \tcargo check -p {name}-e2e --tests\n\
         \n\
         test: ## All E2E tests (requires Docker)\n\
         \tcargo test -p {name}-e2e\n\
         \n\
         ci: test ## E2E CI gate (requires Docker)\n"
    )
}

fn e2e_common_mod(name: &str) -> String {
    let snake = name.replace('-', "_");
    let camel = {
        use convert_case::{Case, Casing};
        name.to_case(Case::Pascal)
    };
    format!(
        r#"//! Shared E2E harness: testcontainer Postgres + Redis + in-process {name} server.
//!
//! Include in each test file with:
//!   #[path = "common/mod.rs"] mod common;

use std::net::TcpListener;
use testcontainers::{{ContainerAsync, ImageExt, runners::AsyncRunner}};
use testcontainers_modules::{{postgres::Postgres, redis::Redis}};
use tokio_stream::wrappers::TcpListenerStream;
use tonic::transport::Endpoint;

use {snake}_proto::{snake}_server::{camel}Server;
use {snake}_server::{camel}Service;
use {snake}_rs::{camel}Client;

/// Full E2E fixture: Postgres + Redis containers + real in-process server + connected client.
///
/// Keep the returned `E2EHarness` alive for the duration of the test — dropping it stops
/// the containers.
pub struct E2EHarness {{
    pub client: {camel}Client,
    pub db_url: String,
    pub redis_url: String,
    _pg: ContainerAsync<Postgres>,
    _redis: ContainerAsync<Redis>,
}}

impl E2EHarness {{
    pub async fn start() -> anyhow::Result<Self> {{
        // Start containers
        let pg = Postgres::default()
            .with_db_name("{snake}_e2e")
            .with_user("postgres")
            .with_password("postgres")
            .start()
            .await?;
        let redis = Redis::default().start().await?;

        let pg_port = pg.get_host_port_ipv4(5432).await?;
        let redis_port = redis.get_host_port_ipv4(6379).await?;

        let db_url = format!("postgres://postgres:postgres@127.0.0.1:{{pg_port}}/{snake}_e2e");
        let redis_url = format!("redis://127.0.0.1:{{redis_port}}");

        // Apply migrations from the server crate (path relative to this crate's manifest)
        let migrations = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../{name}-server/migrations");
        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(2)
            .connect(&db_url)
            .await?;
        sqlx::migrate::Migrator::new(migrations)
            .await?
            .run(&pool)
            .await?;

        // Bind a random port; start the tonic server in a background task
        let listener = TcpListener::bind("127.0.0.1:0")?;
        let addr = listener.local_addr()?;
        let incoming =
            TcpListenerStream::new(tokio::net::TcpListener::from_std(listener)?);

        // TODO(M2/M3): pass db_url + redis_url into service constructors via State
        let _db = db_url.clone();
        let _redis = redis_url.clone();

        tokio::spawn(async move {{
            tonic::transport::Server::builder()
                .add_service({camel}Server::new({camel}Service::default()))
                .serve_with_incoming(incoming)
                .await
                .expect("e2e server panicked");
        }});

        // Connect via {name}-rs (the public client crate)
        let endpoint = Endpoint::from_shared(format!("http://{{addr}}"))?;
        let client = {camel}Client::connect(endpoint).await?;

        Ok(Self {{
            client,
            db_url,
            redis_url,
            _pg: pg,
            _redis: redis,
        }})
    }}
}}

/// Returns true if Docker is reachable.
/// Set DOCKER_HOST=unix:///home/<user>/.rd/docker.sock for Rancher Desktop.
pub fn docker_available() -> bool {{
    let sock = std::env::var("DOCKER_HOST")
        .unwrap_or_else(|_| "unix:///var/run/docker.sock".to_string());
    let path = sock.strip_prefix("unix://").unwrap_or(&sock);
    std::path::Path::new(path).exists()
}}

/// Macro: skip the test with a message when Docker is not available.
#[macro_export]
macro_rules! require_docker {{
    () => {{
        if !common::docker_available() {{
            eprintln!("skip: Docker not available — set DOCKER_HOST or start Docker");
            return Ok(());
        }}
    }};
}}
"#,
    )
}

fn e2e_contract_test(name: &str) -> String {
    let snake = name.replace('-', "_");
    let camel = {
        use convert_case::{Case, Casing};
        name.to_case(Case::Pascal)
    };
    format!(
        r#"//! Contract smoke test — verifies the server is reachable and the gRPC
//! transport works end-to-end. Individual service-specific test files
//! (e.g. tests/service.rs) are added as each RPC is implemented.
//!
//! This file just checks "server up + client connects + any RPC call
//! returns a gRPC status (not a connection/transport error)".

#[path = "common/mod.rs"]
mod common;

use {snake}_proto::HelloRequest;

type Result = anyhow::Result<()>;

#[tokio::test]
async fn test_{snake}_e2e_server_reachable() -> Result {{
    require_docker!();
    let h = common::E2EHarness::start().await?;

    // The harness already connected the client in E2EHarness::start().
    // Any connection-level failure (port unreachable, TLS) would have
    // panicked there. Call say_hello via the CoalescingClient — the stub
    // returns UNIMPLEMENTED which is a valid gRPC status, confirming the
    // server is up and the transport layer is healthy.
    //
    // CoalescingClient::inner is the raw tonic-generated client; calling
    // it directly avoids needing a convenience wrapper on {camel}Client.
    let coalescing = h.client.inner();
    let status = coalescing
        .inner
        .say_hello(HelloRequest {{ name: "smoke".into() }})
        .await
        .unwrap_err();

    // Any gRPC status code is acceptable here — the important thing is that
    // we did NOT get a transport error (which would be tonic::Code::Unknown
    // with a "connection refused" or "transport error" message).
    assert_ne!(
        status.code(),
        tonic::Code::Unknown,
        "transport error — is the server running? {{status}}",
    );
    Ok(())
}}
"#,
    )
}

fn print_workspace_next_steps(name: &str, extras: &[ClientLang]) {
    eprintln!();
    eprintln!("next steps:");
    eprintln!("  cd {name}");
    eprintln!("  cargo build --workspace          # compiles Rust crates");
    eprintln!("  cargo test --workspace           # contract test should pass");
    eprintln!("  cd {name}-server && tonin k8s generate   # regenerate k8s/");
    for client in extras {
        match client {
            ClientLang::Python => {
                eprintln!("  (cd {name}-py && bash codegen.sh)   # generate Python stubs")
            }
            ClientLang::Ts => {
                eprintln!("  (cd {name}-ts && npm install && npm run gen)  # generate TS stubs")
            }
            ClientLang::Rust => {}
        }
    }
    eprintln!();
    eprintln!("scaffold:");
    eprintln!("  {name}-proto/   ← proto contract + generated types");
    eprintln!("  {name}-server/  ← tonin gRPC binary (stubs, fill in real logic)");
    eprintln!("  {name}-rs/      ← Rust client library for callers");
    for client in extras {
        match client {
            ClientLang::Python => {
                eprintln!("  {name}-py/      ← Python client (gRPC stubs + tonin_client)")
            }
            ClientLang::Ts => {
                eprintln!("  {name}-ts/      ← TypeScript client (buf-generated stubs)")
            }
            ClientLang::Rust => {}
        }
    }
}