sz-rust-cli 1.4.0

SZ-Rust 命令行工具:项目脚手架、数据库迁移、调度器管理
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-2026 SZ-Rust Team
//
//! `make:*` 代码生成命令 — 对齐 PHP `think\console\command\make\*`
//!
//! ## PHP 对齐
//!
//! PHP `Make::execute()` 流程:
//! 1. `getArgument('name')` 获取类名
//! 2. `getClassName(name)` 处理 `@` 分隔应用名 + `/` 转 `\`
//! 3. `getPathName(className)` 剥离 `app\` 前缀 + `/` 替换 + `.php` 后缀
//! 4. 检查文件存在 → `mkdir` → `file_put_contents(buildClass())`
//! 5. `buildClass(name)` 读取 stub,替换占位符
//!
//! Rust 端对齐上述流程,但生成 `.rs` 文件而非 `.php` 文件。

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

use clap::Subcommand;

use crate::error::CliError;
use crate::stubs::{self, render_template};

/// `make` 子命令枚举
///
/// 对齐 PHP `think make:*` 命令组。
#[derive(Subcommand, Debug)]
pub enum MakeCommand {
    /// 生成 Model(对齐 `php think make:model User`)
    #[command(name = "model")]
    Model {
        /// 类名(如 `User` 或 `admin/User`)
        name: String,
    },

    /// 生成 Controller(对齐 `php think make:controller User`)
    #[command(name = "controller")]
    Controller {
        /// 类名
        name: String,
        /// 生成 API 风格控制器(5 方法,无 create/edit)
        #[arg(long)]
        api: bool,
        /// 生成空控制器
        #[arg(long)]
        plain: bool,
    },

    /// 生成迁移文件(对齐 Phinx `make:migration`)
    #[command(name = "migration")]
    Migration {
        /// 迁移名称(如 `create_users`)
        name: String,
        /// 迁移目录(默认 `migrations`)
        #[arg(short = 'p', long, default_value = "migrations")]
        path: String,
    },

    /// 生成填充文件(对齐 PHP `make:seeder`)
    ///
    /// 在 `seeds/` 目录下生成 `<name>.sql` 文件骨架。
    #[command(name = "seeder")]
    Seeder {
        /// 填充文件名称(如 `001_users_seed`)
        name: String,
        /// 填充目录(默认 `seeds`)
        #[arg(short = 'p', long, default_value = "seeds")]
        path: String,
    },

    /// 生成 Guard(sz-rust 自研,无 PHP 对应)
    #[command(name = "guard")]
    Guard {
        /// Guard 名称(如 `Admin`)
        name: String,
    },

    /// 生成验证器(对齐 PHP `make:validate`)
    ///
    /// 在 `app/validate/` 目录下生成 `<Name>.rs` 验证器骨架。
    #[command(name = "validate")]
    Validate {
        /// 验证器类名(如 `User` 或 `admin/User`)
        name: String,
    },

    /// 生成事件类(对齐 PHP `make:event`)
    ///
    /// 在 `app/event/` 目录下生成 `<Name>.rs` 事件骨架,包含事件名与负载构造方法。
    #[command(name = "event")]
    Event {
        /// 事件类名(如 `UserLogin` 或 `admin/UserLogin`)
        name: String,
    },

    /// 生成监听器(对齐 PHP `make:listener`)
    ///
    /// 在 `app/listener/` 目录下生成 `<Name>.rs` 监听器骨架,实现 `Listener` trait。
    #[command(name = "listener")]
    Listener {
        /// 监听器类名(如 `SendWelcomeEmail`)
        name: String,
        /// 监听的事件名(可选,默认使用类名)
        #[arg(long)]
        event: Option<String>,
    },

    /// 生成自定义命令(对齐 PHP `make:command`)
    ///
    /// 在 `app/command/` 目录下生成 `<Name>.rs` 命令骨架,实现 `Command` trait。
    #[command(name = "command")]
    Command {
        /// 命令类名(如 `SyncData`)
        name: String,
    },

    /// 生成服务类(对齐 PHP `make:service`)
    ///
    /// 在 `app/service/` 目录下生成 `<Name>.rs` 服务骨架,可注入容器。
    #[command(name = "service")]
    Service {
        /// 服务类名(如 `UserService`)
        name: String,
    },

    /// 生成中间件(sz-rust 自研,对齐 NestJS `make:middleware`)
    ///
    /// 在 `app/middleware/` 目录下生成 `<Name>.rs` 中间件骨架,
    /// 实现 `SzMiddleware` trait,可注册到中间件链。
    #[command(name = "middleware")]
    Middleware {
        /// 中间件类名(如 `CorsMiddleware` 或 `admin/RateLimit`)
        name: String,
    },

    /// 生成脚手架(Model + Controller + Migration)
    #[command(name = "scaffold")]
    Scaffold {
        /// 资源名称(如 `User`)
        name: String,
    },

    /// 生成插件骨架(P1-T3 插件模板库)
    ///
    /// 基于 Tera 模板引擎生成完整插件结构,含 Model、Controller、Service、
    /// Repository、Migration、Routes、Manifest、Tests。
    /// 生成后自动执行 `cargo check` 验证,失败时回滚已写入文件。
    #[command(name = "plugin")]
    Plugin {
        /// 模板类型(如 `crud` 或 `master-slave`)
        #[arg(long)]
        template: String,
        /// 插件名称(如 `user-management`)
        #[arg(long)]
        name: String,
        /// 表名(可选,默认取插件名 snake_case)
        #[arg(long)]
        table: Option<String>,
        /// 字段定义(如 `id:i32:pk,name:String,age:i32`)
        #[arg(long)]
        fields: Option<String>,
        /// 强制覆盖已存在目录
        #[arg(long)]
        force: bool,
        /// 输出目录(可选,默认 `plugins/<name>/`)
        #[arg(long)]
        output: Option<String>,
        /// 主表名(主从模板专用)
        #[arg(long)]
        master: Option<String>,
        /// 从表名(主从模板专用)
        #[arg(long)]
        slave: Option<String>,
        /// 主表字段定义(主从模板专用)
        #[arg(long)]
        master_fields: Option<String>,
        /// 从表字段定义(主从模板专用)
        #[arg(long)]
        slave_fields: Option<String>,
        /// 外键字段名(主从模板专用)
        #[arg(long)]
        foreign_key: Option<String>,
    },

    /// 生成前端代码(P4-T1 前端代码生成)
    ///
    /// 根据 ORM 模型自动生成 Vue/React 组件、路由、权限、API 客户端。
    /// 对齐 Laravel Artisan `make:frontend` 风格。
    #[command(name = "frontend")]
    Frontend {
        /// 要生成的模型名(可多次指定)
        #[arg(long = "model")]
        models: Vec<String>,
        /// 模型目录(默认 `src/model/`)
        #[arg(long = "model-dir", default_value = "src/model/")]
        model_dir: String,
        /// 前端框架(vue / react)
        #[arg(long, default_value = "vue")]
        framework: String,
        /// UI 组件库(element_plus / ant_design_vue)
        #[arg(long = "ui", default_value = "element_plus")]
        ui: String,
        /// 输出目录(默认 `./frontend/`)
        #[arg(long, default_value = "./frontend/")]
        output: String,
        /// 自定义模板目录
        #[arg(long = "template-dir")]
        template_dir: Option<String>,
        /// 覆盖策略(skip / overwrite / merge)
        #[arg(long = "override", default_value = "skip")]
        override_strategy: String,
        /// 生成测试骨架
        #[arg(long = "with-tests")]
        with_tests: bool,
        /// 生成请求拦截器
        #[arg(long = "with-interceptors")]
        with_interceptors: bool,
        /// 懒加载路由(默认 true)
        #[arg(long = "lazy-load", default_value_t = true)]
        lazy_load: bool,
        /// 强制覆盖非空输出目录
        #[arg(long)]
        force: bool,
    },

    /// 生成 OpenAPI 3.0 文档(对齐 PHP `make:openapi`)
    ///
    /// 从路由定义自动生成 OpenAPI 3.0 JSON 文档。
    #[command(name = "openapi")]
    Openapi {
        /// 输出文件路径(默认 `openapi.json`)
        #[arg(short = 'o', long, default_value = "openapi.json")]
        output: String,
        /// API 标题
        #[arg(long, default_value = "SZ-Rust API")]
        title: String,
        /// API 版本
        #[arg(long, default_value = "1.0.0")]
        version: String,
        /// 强制覆盖已存在文件
        #[arg(long)]
        force: bool,
    },
}

/// 执行 make 子命令
pub async fn execute(cmd: &MakeCommand) -> Result<(), CliError> {
    match cmd {
        MakeCommand::Model { name } => execute_make_model(name),
        MakeCommand::Controller { name, api, plain } => execute_make_controller(name, *api, *plain),
        MakeCommand::Migration { name, path } => execute_make_migration(name, path),
        MakeCommand::Seeder { name, path } => execute_make_seeder(name, path),
        MakeCommand::Guard { name } => execute_make_guard(name),
        MakeCommand::Validate { name } => execute_make_validate(name),
        MakeCommand::Event { name } => execute_make_event(name),
        MakeCommand::Listener { name, event } => execute_make_listener(name, event.as_deref()),
        MakeCommand::Command { name } => execute_make_command(name),
        MakeCommand::Service { name } => execute_make_service(name),
        MakeCommand::Middleware { name } => execute_make_middleware(name),
        MakeCommand::Scaffold { name } => execute_make_scaffold(name),
        MakeCommand::Plugin {
            template,
            name,
            table,
            fields,
            force,
            output,
            master,
            slave,
            master_fields,
            slave_fields,
            foreign_key,
        } => {
            execute_make_plugin(crate::context_builder::PluginCommandArgs {
                template: template.clone(),
                name: name.clone(),
                table: table.clone(),
                fields: fields.clone(),
                force: *force,
                output: output.clone(),
                master: master.clone(),
                slave: slave.clone(),
                master_fields: master_fields.clone(),
                slave_fields: slave_fields.clone(),
                foreign_key: foreign_key.clone(),
            })
            .await
        }
        MakeCommand::Frontend {
            models,
            model_dir,
            framework,
            ui,
            output,
            template_dir,
            override_strategy,
            with_tests,
            with_interceptors,
            lazy_load,
            force,
        } => {
            execute_make_frontend(
                models,
                model_dir,
                framework,
                ui,
                output,
                template_dir.as_deref(),
                override_strategy,
                *with_tests,
                *with_interceptors,
                *lazy_load,
                *force,
            )
            .await
        }
        MakeCommand::Openapi {
            output,
            title,
            version,
            force,
        } => execute_make_openapi(output, title, version, *force).await,
    }
}

/// 生成 Model 文件
///
/// 对齐 PHP `make:model`:读取 `model.stub`,替换占位符,写入 `app/model/{name}.rs`。
fn execute_make_model(name: &str) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "model");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    let table_name = class_to_snake(&class_name);
    let content = render_template(
        stubs::MODEL_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
            ("{%table_name%}", &table_name),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Model created: {}", file_path.display());
    Ok(())
}

/// 生成 Controller 文件
///
/// 对齐 PHP `make:controller`:根据 `--api` / `--plain` 选择不同 stub。
fn execute_make_controller(name: &str, api: bool, plain: bool) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "controller");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    let route = class_to_snake(&class_name);

    let template = if plain {
        stubs::CONTROLLER_PLAIN_STUB
    } else if api {
        stubs::CONTROLLER_API_STUB
    } else {
        stubs::CONTROLLER_STUB
    };

    let content = render_template(
        template,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
            ("{%route%}", &route),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Controller created: {}", file_path.display());
    Ok(())
}

/// 生成迁移文件
///
/// 对齐 Phinx 风格:生成 `{timestamp}_{name}_up.sql` 和 `{timestamp}_{name}_down.sql`。
fn execute_make_migration(name: &str, path: &str) -> Result<(), CliError> {
    let dir = Path::new(path);
    std::fs::create_dir_all(dir)?;

    let timestamp = chrono::Utc::now().format("%Y%m%d%H%M%S").to_string();
    let table_name = name_to_table(name);

    let up_file = dir.join(format!("{}_{}_up.sql", timestamp, name));
    let down_file = dir.join(format!("{}_{}_down.sql", timestamp, name));

    check_file_exists(&up_file)?;
    check_file_exists(&down_file)?;

    let up_content = render_template(
        stubs::MIGRATION_UP_STUB,
        &[
            ("{%name%}", name),
            ("{%timestamp%}", &timestamp),
            ("{%table_name%}", &table_name),
        ],
    );
    let down_content = render_template(
        stubs::MIGRATION_DOWN_STUB,
        &[
            ("{%name%}", name),
            ("{%timestamp%}", &timestamp),
            ("{%table_name%}", &table_name),
        ],
    );

    write_file(&up_file, &up_content)?;
    write_file(&down_file, &down_content)?;
    println!(
        "Migration created: {} & {}",
        up_file.display(),
        down_file.display()
    );
    Ok(())
}

/// 生成填充文件
///
/// 对齐 PHP `make:seeder`:在 `seeds/` 目录下生成 `<name>.sql` 文件骨架。
fn execute_make_seeder(name: &str, path: &str) -> Result<(), CliError> {
    let dir = Path::new(path);
    std::fs::create_dir_all(dir)?;

    let file_path = dir.join(format!("{}.sql", name));
    check_file_exists(&file_path)?;

    let timestamp = chrono::Utc::now()
        .format("%Y-%m-%d %H:%M:%S UTC")
        .to_string();
    let content = render_template(
        stubs::SEED_STUB,
        &[("{%name%}", name), ("{%timestamp%}", &timestamp)],
    );

    write_file(&file_path, &content)?;
    println!("Seeder created: {}", file_path.display());
    Ok(())
}

/// 生成 Guard 文件(sz-rust 自研)
fn execute_make_guard(name: &str) -> Result<(), CliError> {
    let (class_name, _module_path, file_path) = resolve_target(name, "guard");
    check_file_exists(&file_path)?;

    let content = format!(
        "//! Guard: {class_name}\n//!\n//! 由 `sz-rust make:guard` 生成。\n//!\n//! 对齐 NestJS Guard + Spring Security 模式。\n\nuse sz_rust_core::guard::Guard;\nuse sz_rust_core::request::Request;\n\n/// {class_name} Guard\npub struct {class_name};\n\nimpl Guard for {class_name} {{\n    async fn can_activate(&self, _req: &Request) -> bool {{\n        // 在此实现鉴权逻辑\n        true\n    }}\n}}\n"
    );

    write_file(&file_path, &content)?;
    println!("Guard created: {}", file_path.display());
    Ok(())
}

/// 生成验证器文件
///
/// 对齐 PHP `make:validate`:在 `app/validate/` 目录下生成 `<Name>.rs` 验证器骨架,
/// 包含 `Validate` 结构体初始化与常见规则示例。
fn execute_make_validate(name: &str) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "validate");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    let content = render_template(
        stubs::VALIDATE_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Validator created: {}", file_path.display());
    Ok(())
}

/// 生成事件类文件
///
/// 对齐 PHP `make:event`:读取 `event.stub`,替换占位符,写入 `app/event/{name}.rs`。
fn execute_make_event(name: &str) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "event");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    // 事件名默认使用类名(对齐 PHP `make:event` 默认行为)
    let event_name = class_name.clone();
    let content = render_template(
        stubs::EVENT_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
            ("{%event_name%}", &event_name),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Event created: {}", file_path.display());
    Ok(())
}

/// 生成监听器文件
///
/// 对齐 PHP `make:listener`:读取 `listener.stub`,替换占位符,写入 `app/listener/{name}.rs`。
/// 若未指定 `--event`,事件名默认使用监听器类名。
fn execute_make_listener(name: &str, event: Option<&str>) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "listener");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    // 事件名:优先使用 --event 参数,否则默认使用类名
    let event_name = event.unwrap_or(&class_name).to_string();
    let content = render_template(
        stubs::LISTENER_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
            ("{%event_name%}", &event_name),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Listener created: {}", file_path.display());
    Ok(())
}

/// 生成自定义命令文件
///
/// 对齐 PHP `make:command`:读取 `command.stub`,替换占位符,写入 `app/command/{name}.rs`。
/// 命令名默认为类名的 snake_case 形式(如 `SyncData` → `sync_data`)。
fn execute_make_command(name: &str) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "command");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    // 命令名:snake_case(类名)(对齐 PHP `make:command` 默认行为)
    let command_name = class_to_snake(&class_name);
    let content = render_template(
        stubs::COMMAND_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
            ("{%command_name%}", &command_name),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Command created: {}", file_path.display());
    Ok(())
}

/// 生成服务类文件
///
/// 对齐 PHP `make:service`:读取 `service.stub`,替换占位符,写入 `app/service/{name}.rs`。
fn execute_make_service(name: &str) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "service");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    let content = render_template(
        stubs::SERVICE_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Service created: {}", file_path.display());
    Ok(())
}

/// 生成中间件文件(sz-rust 自研)
///
/// 在 `app/middleware/` 目录下生成 `<Name>.rs` 中间件骨架,
/// 实现 `SzMiddleware` trait,可注册到中间件链。
fn execute_make_middleware(name: &str) -> Result<(), CliError> {
    let (class_name, module_path, file_path) = resolve_target(name, "middleware");
    check_file_exists(&file_path)?;

    let namespace = format!("app::{}", module_path);
    let content = render_template(
        stubs::MIDDLEWARE_STUB,
        &[
            ("{%className%}", &class_name),
            ("{%namespace%}", &namespace),
        ],
    );

    write_file(&file_path, &content)?;
    println!("Middleware created: {}", file_path.display());
    Ok(())
}

/// 生成脚手架(Model + Controller + Migration)
fn execute_make_scaffold(name: &str) -> Result<(), CliError> {
    println!("Scaffolding for: {}", name);
    execute_make_model(name)?;
    execute_make_controller(name, false, false)?;
    execute_make_migration(&class_to_snake(name), "migrations")?;
    println!("Scaffold complete.");
    Ok(())
}

// ============================================================================
// 辅助函数(对齐 PHP Make 基类方法)
// ============================================================================

/// 解析目标(类名 + 模块路径 + 文件路径)
///
/// 对齐 PHP `Make::getClassName()` + `getPathName()`:
///
/// - `User` → (`User`, `model`, `app/model/User.rs`)
/// - `admin/User` → (`User`, `controller::admin`, `app/controller/admin/User.rs`)
/// - `admin@User` → (`User`, `admin::model`, `app/admin/model/User.rs`)
fn resolve_target(name: &str, layer: &str) -> (String, String, PathBuf) {
    // 处理 @ 分隔应用名(对齐 PHP getClassName)
    let (app, class_part) = if let Some(idx) = name.find('@') {
        (&name[..idx], &name[idx + 1..])
    } else {
        ("", name)
    };

    // 处理 / 分隔子目录(对齐 PHP / → \)
    let segments: Vec<&str> = class_part.split('/').collect();
    let class_name = segments.last().unwrap_or(&"").to_string();

    // 构建模块路径
    let parent_segments: Vec<&str> = if segments.len() > 1 {
        segments[..segments.len() - 1].to_vec()
    } else {
        Vec::new()
    };

    let module_path = if app.is_empty() {
        if parent_segments.is_empty() {
            layer.to_string()
        } else {
            format!("{}::{}", layer, parent_segments.join("::"))
        }
    } else if parent_segments.is_empty() {
        format!("{}::{}", app, layer)
    } else {
        format!("{}::{}::{}", app, layer, parent_segments.join("::"))
    };

    // 构建文件路径(对齐 PHP getPathName:app\ → app/ + / 替换)
    let mut path = PathBuf::from("app");
    if !app.is_empty() {
        path.push(app);
    }
    // 添加层目录
    path.push(layer);
    // 添加子目录
    for seg in &parent_segments {
        path.push(seg);
    }
    // 添加文件名
    path.push(format!("{}.rs", class_name));

    (class_name, module_path, path)
}

/// 检查文件是否已存在
///
/// 对齐 PHP `Make::execute()` 中 `already exists!` 提示。
fn check_file_exists(path: &Path) -> Result<(), CliError> {
    if path.exists() {
        return Err(CliError::FileExists(path.display().to_string()));
    }
    Ok(())
}

/// 写入文件(自动创建父目录)
///
/// 对齐 PHP `mkdir` + `file_put_contents`。
fn write_file(path: &Path, content: &str) -> Result<(), CliError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, content)?;
    Ok(())
}

/// 类名转 snake_case 表名
///
/// `User` → `user`,`OrderItem` → `order_item`
fn class_to_snake(s: &str) -> String {
    let mut result = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() && i > 0 {
            result.push('_');
        }
        result.push(ch.to_lowercase().next().unwrap_or(ch));
    }
    result
}

/// 迁移名转表名
///
/// `create_users` → `users`,`add_index_to_orders` → `orders`
fn name_to_table(name: &str) -> String {
    // 简单提取:create_xxx → xxx
    if let Some(rest) = name.strip_prefix("create_") {
        return rest.to_string();
    }
    if let Some(rest) = name.strip_prefix("add_") {
        // add_index_to_orders → orders
        if let Some(to_pos) = rest.find("_to_") {
            return rest[to_pos + 4..].to_string();
        }
        return rest.to_string();
    }
    name.to_string()
}

/// `make:plugin` 命令主流程(P1-T3)
///
/// 状态机:Validate → LoadTemplates → BuildContext → Render → WriteFiles
/// 后续 Batch D 将追加 CargoCheck → Rollback 分支。
pub async fn execute_make_plugin(
    args: crate::context_builder::PluginCommandArgs,
) -> Result<(), CliError> {
    use crate::context_builder::TemplateContextBuilder;
    use crate::template_engine::TemplateEngine;
    use crate::validator::InputValidator;

    InputValidator::validate_plugin_name(&args.name)?;

    if let Some(ref table) = args.table {
        InputValidator::validate_table_name(table)?;
    }
    if let Some(ref fields) = args.fields {
        InputValidator::validate_fields(fields)?;
    }
    if let Some(ref master) = args.master {
        InputValidator::validate_table_name(master)?;
    }
    if let Some(ref slave) = args.slave {
        InputValidator::validate_table_name(slave)?;
    }

    let template_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("templates");
    let engine = TemplateEngine::init(&template_dir).await?;

    engine.validate_template_type(&args.template)?;

    let is_master_slave = args.template == "master-slave";

    let ctx = if is_master_slave {
        TemplateContextBuilder::new(args.clone()).build_master_slave()?
    } else {
        TemplateContextBuilder::new(args.clone()).build()?
    };

    let output_dir = args
        .output
        .as_ref()
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("plugins").join(&args.name));

    if output_dir.exists() && !args.force {
        return Err(CliError::DirExists(output_dir));
    }

    let template_files: &[(&str, &str)] = match args.template.as_str() {
        "master-slave" => &[
            (
                "plugin-master-slave/master_model.rs.tera",
                "src/master_model.rs",
            ),
            (
                "plugin-master-slave/slave_model.rs.tera",
                "src/slave_model.rs",
            ),
            (
                "plugin-master-slave/master_controller.rs.tera",
                "src/master_controller.rs",
            ),
            (
                "plugin-master-slave/slave_controller.rs.tera",
                "src/slave_controller.rs",
            ),
            (
                "plugin-master-slave/cascade_service.rs.tera",
                "src/cascade_service.rs",
            ),
            (
                "plugin-master-slave/datasource_config.rs.tera",
                "src/datasource_config.rs",
            ),
            (
                "plugin-master-slave/migration.sql.tera",
                "migrations/master_slave.sql",
            ),
            ("plugin-master-slave/manifest.json.tera", "manifest.json"),
        ],
        "workflow" => &[
            ("plugin-workflow/model.rs.tera", "src/model.rs"),
            ("plugin-workflow/controller.rs.tera", "src/controller.rs"),
            ("plugin-workflow/routes.rs.tera", "src/routes.rs"),
            ("plugin-workflow/migration.sql.tera", "migrations/table.sql"),
            ("plugin-workflow/manifest.json.tera", "manifest.json"),
            ("plugin-workflow/tests.rs.tera", "tests/workflow_test.rs"),
        ],
        "report" => &[
            ("plugin-report/model.rs.tera", "src/model.rs"),
            ("plugin-report/controller.rs.tera", "src/controller.rs"),
            ("plugin-report/routes.rs.tera", "src/routes.rs"),
            ("plugin-report/migration.sql.tera", "migrations/table.sql"),
            ("plugin-report/manifest.json.tera", "manifest.json"),
            ("plugin-report/tests.rs.tera", "tests/report_test.rs"),
        ],
        _ => &[
            ("plugin-crud/model.rs.tera", "src/model.rs"),
            ("plugin-crud/controller.rs.tera", "src/controller.rs"),
            ("plugin-crud/service.rs.tera", "src/service.rs"),
            ("plugin-crud/repository.rs.tera", "src/repository.rs"),
            ("plugin-crud/migration.sql.tera", "migrations/table.sql"),
            ("plugin-crud/routes.rs.tera", "src/routes.rs"),
            ("plugin-crud/manifest.json.tera", "manifest.json"),
            ("plugin-crud/tests.rs.tera", "tests/crud_test.rs"),
        ],
    };

    let mut rendered_files: Vec<(PathBuf, String)> = Vec::new();
    for (template_name, output_path) in template_files {
        let content = engine.render(template_name, &ctx)?;
        rendered_files.push((output_dir.join(output_path), content));
    }

    let safety_files: Vec<(String, String)> = rendered_files
        .iter()
        .map(|(p, c)| (p.display().to_string(), c.clone()))
        .collect();
    let violations = crate::safety_validator::SafetyValidator::validate_files(&safety_files);
    if !violations.is_empty() {
        let report = crate::safety_validator::SafetyValidator::format_report(&violations);
        eprintln!("{report}");
        return Err(CliError::Generic(format!(
            "安全检查失败:{} 个违规项,已阻止生成",
            violations.len()
        )));
    }

    if output_dir.exists() && args.force {
        tokio::fs::remove_dir_all(&output_dir).await?;
    }

    for (file_path, content) in &rendered_files {
        if let Some(parent) = file_path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(file_path, content).await?;
    }

    let written_paths: Vec<std::path::PathBuf> =
        rendered_files.iter().map(|(p, _)| p.clone()).collect();

    let check_result = crate::cargo_checker::CargoChecker::check(&output_dir).await;
    match check_result {
        Ok(result) if result.success => {
            println!(
                "Plugin '{}' created successfully at: {}",
                args.name,
                output_dir.display()
            );
            println!("Files generated:");
            for (file_path, _) in &rendered_files {
                println!("  - {}", file_path.display());
            }
            println!("cargo check: PASSED");
            Ok(())
        }
        Ok(result) => {
            eprintln!("cargo check: FAILED");
            eprintln!("Compilation errors:");
            for err in &result.errors {
                eprintln!("  {err}");
            }

            let failures = crate::cargo_checker::CargoChecker::rollback(&written_paths).await;
            if !failures.is_empty() {
                eprintln!(
                    "Warning: {} files could not be removed during rollback",
                    failures.len()
                );
            }

            Err(CliError::CompileFailed(result.errors))
        }
        Err(e) => {
            eprintln!("cargo check could not be executed: {e}");
            eprintln!("Rolling back generated files...");

            let failures = crate::cargo_checker::CargoChecker::rollback(&written_paths).await;
            if !failures.is_empty() {
                eprintln!(
                    "Warning: {} files could not be removed during rollback",
                    failures.len()
                );
            }

            Err(e)
        }
    }
}

/// 执行前端代码生成(P4-T1)
///
/// 将 CLI 参数转换为 `GenerationConfig`,调用 `CodegenService::generate`,
/// 输出结构化报告到 stdout。
#[allow(clippy::too_many_arguments)]
async fn execute_make_frontend(
    models: &[String],
    model_dir: &str,
    framework: &str,
    ui: &str,
    output: &str,
    template_dir: Option<&str>,
    override_strategy: &str,
    with_tests: bool,
    with_interceptors: bool,
    lazy_load: bool,
    force: bool,
) -> Result<(), CliError> {
    use sz_rust_frontend_codegen::{
        CodegenService, Framework, GenerationConfig, OverrideStrategy, UiLibrary,
    };

    let fw = match framework.to_lowercase().as_str() {
        "vue" => Framework::Vue,
        "react" => Framework::React,
        other => {
            return Err(CliError::Generic(format!(
                "不支持的前端框架: {other}(可选: vue, react)"
            )));
        }
    };

    let ui_lib = match ui.to_lowercase().as_str() {
        "element_plus" | "element-plus" => UiLibrary::ElementPlus,
        "ant_design_vue" | "ant-design-vue" => UiLibrary::AntDesignVue,
        other => {
            return Err(CliError::Generic(format!(
                "不支持的 UI 库: {other}(可选: element_plus, ant_design_vue)"
            )));
        }
    };

    let strategy = match override_strategy.to_lowercase().as_str() {
        "skip" => OverrideStrategy::Skip,
        "overwrite" => OverrideStrategy::Overwrite,
        "merge" => OverrideStrategy::Merge,
        other => {
            return Err(CliError::Generic(format!(
                "不支持的覆盖策略: {other}(可选: skip, overwrite, merge)"
            )));
        }
    };

    let config = GenerationConfig {
        models: models.to_vec(),
        model_dir: PathBuf::from(model_dir),
        framework: fw,
        ui_library: ui_lib,
        output_dir: PathBuf::from(output),
        template_dir: template_dir.map(PathBuf::from),
        override_strategy: strategy,
        with_tests,
        with_interceptors,
        lazy_load,
        force,
    };

    let service = CodegenService::new();
    let report = service
        .generate(config)
        .await
        .map_err(|e| CliError::Generic(e.to_string()))?;
    println!("{}", report.format_cli());
    Ok(())
}

// ============================================================================
// T033: make:openapi — OpenAPI 3.0 文档生成
// ============================================================================

/// 生成 OpenAPI 3.0 JSON 文档
async fn execute_make_openapi(
    output: &str,
    title: &str,
    version: &str,
    force: bool,
) -> Result<(), CliError> {
    let output_path = PathBuf::from(output);
    check_file_exists_with_force(&output_path, force)?;

    let spec = generate_openapi_spec(title, version);
    let json = serde_json::to_string_pretty(&spec)
        .map_err(|e| CliError::Generation(format!("OpenAPI serialize failed: {e}")))?;

    write_file(&output_path, &json)?;
    println!("OpenAPI spec created: {}", output_path.display());

    run_post_generation_check()?;
    Ok(())
}

/// OpenAPI 3.0 规范
#[derive(Debug, serde::Serialize)]
struct OpenApiSpec {
    openapi: String,
    info: OpenApiInfo,
    paths: serde_json::Value,
    components: serde_json::Value,
}

#[derive(Debug, serde::Serialize)]
struct OpenApiInfo {
    title: String,
    version: String,
    description: String,
}

/// 生成 OpenAPI 规范(从路由定义)
fn generate_openapi_spec(title: &str, version: &str) -> OpenApiSpec {
    OpenApiSpec {
        openapi: "3.0.3".to_string(),
        info: OpenApiInfo {
            title: title.to_string(),
            version: version.to_string(),
            description: "Generated by sz-rust make:openapi".to_string(),
        },
        paths: serde_json::json!({
            "/health": {
                "get": {
                    "summary": "Health check",
                    "responses": {
                        "200": {"description": "Service healthy"}
                    }
                }
            }
        }),
        components: serde_json::json!({
            "schemas": {},
            "securitySchemes": {
                "bearerAuth": {
                    "type": "http",
                    "scheme": "bearer"
                }
            }
        }),
    }
}

// ============================================================================
// T034: --force 标志 + 生成后校验
// ============================================================================

/// 检查文件是否存在,--force 时允许覆盖
fn check_file_exists_with_force(path: &Path, force: bool) -> Result<(), CliError> {
    if path.exists() && !force {
        return Err(CliError::FileExists(path.display().to_string()));
    }
    Ok(())
}

/// 生成后校验:cargo fmt + cargo check + cargo clippy
fn run_post_generation_check() -> Result<(), CliError> {
    let fmt_result = std::process::Command::new("cargo")
        .args(["fmt", "--check"])
        .output();

    if let Ok(output) = fmt_result {
        if !output.status.success() {
            eprintln!("⚠️  cargo fmt --check failed, run `cargo fmt` to fix");
        }
    }

    let check_result = std::process::Command::new("cargo").args(["check"]).output();

    if let Ok(output) = check_result {
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(CliError::Generation(format!(
                "cargo check failed after generation:\n{stderr}"
            )));
        }
    }

    let clippy_result = std::process::Command::new("cargo")
        .args(["clippy", "-D", "warnings"])
        .output();

    if let Ok(output) = clippy_result {
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!("⚠️  cargo clippy found warnings:\n{stderr}");
            eprintln!("   Run `cargo clippy --fix` to auto-fix.");
        }
    }

    Ok(())
}

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

    /// RAII 守卫:在作用域结束时恢复原始工作目录。
    ///
    /// 即使测试 panic 也能保证恢复,避免污染后续测试。
    /// 配合 `super::super::test_support::acquire_global_lock()` 使用,
    /// 确保与 optimize 模块测试的 set_current_dir 互斥。
    struct CwdGuard {
        original: Option<PathBuf>,
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl CwdGuard {
        /// 切换到 `new_dir` 并返回守卫。守卫 drop 时恢复原目录。
        fn switch(new_dir: &Path) -> std::io::Result<Self> {
            let lock = super::super::test_support::acquire_global_lock();
            let original = std::env::current_dir().ok();
            std::env::set_current_dir(new_dir)?;
            Ok(Self {
                original,
                _lock: lock,
            })
        }
    }

    impl Drop for CwdGuard {
        fn drop(&mut self) {
            if let Some(ref orig) = self.original {
                let _ = std::env::set_current_dir(orig);
            }
        }
    }

    #[test]
    fn test_resolve_target_simple_model() {
        let (class, module, path) = resolve_target("User", "model");
        assert_eq!(class, "User");
        assert_eq!(module, "model");
        assert_eq!(path, PathBuf::from("app/model/User.rs"));
    }

    #[test]
    fn test_resolve_target_nested_controller() {
        let (class, module, path) = resolve_target("admin/User", "controller");
        assert_eq!(class, "User");
        assert_eq!(module, "controller::admin");
        assert_eq!(path, PathBuf::from("app/controller/admin/User.rs"));
    }

    #[test]
    fn test_resolve_target_with_app() {
        let (class, module, _path) = resolve_target("admin@User", "model");
        assert_eq!(class, "User");
        assert_eq!(module, "admin::model");
    }

    #[test]
    fn test_class_to_snake() {
        assert_eq!(class_to_snake("User"), "user");
        assert_eq!(class_to_snake("OrderItem"), "order_item");
        assert_eq!(class_to_snake("API"), "a_p_i");
    }

    #[test]
    fn test_name_to_table_create() {
        assert_eq!(name_to_table("create_users"), "users");
        assert_eq!(name_to_table("create_orders"), "orders");
    }

    #[test]
    fn test_name_to_table_add() {
        assert_eq!(name_to_table("add_index_to_orders"), "orders");
        assert_eq!(name_to_table("add_status"), "status");
    }

    #[test]
    fn test_name_to_table_other() {
        assert_eq!(name_to_table("custom_migration"), "custom_migration");
    }

    #[test]
    fn test_check_file_exists_nonexistent() {
        let result = check_file_exists(Path::new("/nonexistent/path/file.txt"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_check_file_exists_existing() {
        // 使用临时文件确保文件确实存在
        let temp = tempfile::NamedTempFile::new().unwrap();
        let result = check_file_exists(temp.path());
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_write_and_read_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("test_file.txt");

        write_file(&file_path, "test content").unwrap();
        assert_eq!(std::fs::read_to_string(&file_path).unwrap(), "test content");
    }

    #[test]
    fn test_execute_make_migration_creates_files() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().to_str().unwrap();

        execute_make_migration("create_test_table", path).unwrap();

        let entries: Vec<_> = std::fs::read_dir(path).unwrap().collect();
        assert_eq!(entries.len(), 2); // up + down

        let mut has_up = false;
        let mut has_down = false;
        for entry in entries {
            let name = entry.unwrap().file_name();
            let name = name.to_string_lossy();
            if name.ends_with("_up.sql") {
                has_up = true;
            }
            if name.ends_with("_down.sql") {
                has_down = true;
            }
        }
        assert!(has_up);
        assert!(has_down);
    }

    #[test]
    fn test_execute_make_model_in_temp() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_model("TestUser").unwrap();

        let model_path = temp_dir.path().join("app/model/TestUser.rs");
        assert!(model_path.exists());

        let content = std::fs::read_to_string(&model_path).unwrap();
        assert!(content.contains("TestUser"));
        assert!(content.contains("test_user"));
    }

    #[test]
    fn test_execute_make_seeder_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().to_str().unwrap();

        execute_make_seeder("001_test_seed", path).unwrap();

        let seed_path = Path::new(path).join("001_test_seed.sql");
        assert!(seed_path.exists());

        let content = std::fs::read_to_string(&seed_path).unwrap();
        assert!(content.contains("001_test_seed"));
        assert!(content.contains("-- Seed:"));
        // 渲染后不应残留占位符
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_seeder_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().to_str().unwrap();

        // 第一次创建应成功
        execute_make_seeder("001_dup_seed", path).unwrap();
        // 第二次创建同名文件应失败
        let result = execute_make_seeder("001_dup_seed", path);
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_seeder_creates_directory() {
        let temp_dir = tempfile::tempdir().unwrap();
        let nested = temp_dir.path().join("nested").join("seeds");
        let path = nested.to_str().unwrap();

        // 目录不存在时应自动创建
        execute_make_seeder("001_seed", path).unwrap();
        assert!(nested.exists());
    }

    #[tokio::test]
    async fn test_make_validate_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        // 通过顶层 execute 入口调用 make validate(验证命令分发正常)
        let cmd = MakeCommand::Validate {
            name: "Order".to_string(),
        };
        execute(&cmd).await.unwrap();

        let validate_path = temp_dir.path().join("app/validate/Order.rs");
        assert!(validate_path.exists());

        let content = std::fs::read_to_string(&validate_path).unwrap();
        // 验证器 struct 与 Validate 引用
        assert!(content.contains("pub struct OrderValidate;"));
        assert!(content.contains("use sz_rust_core::validate::Validate"));
        assert!(content.contains("app::validate"));
        // 渲染后不应残留占位符
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_validate_stub_contains_required_elements() {
        // 验证 stub 模板包含必要元素:struct 定义、Validate 引用、占位符
        assert!(stubs::VALIDATE_STUB.contains("pub struct {%className%}Validate;"));
        assert!(stubs::VALIDATE_STUB.contains("use sz_rust_core::validate::Validate"));
        assert!(stubs::VALIDATE_STUB.contains("impl {%className%}Validate"));
        assert!(stubs::VALIDATE_STUB.contains("pub fn new() -> Validate"));
        assert!(stubs::VALIDATE_STUB.contains("{%className%}"));
        assert!(stubs::VALIDATE_STUB.contains("{%namespace%}"));
    }

    #[test]
    fn test_execute_make_validate_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_validate("User").unwrap();

        let validate_path = temp_dir.path().join("app/validate/User.rs");
        assert!(validate_path.exists());

        let content = std::fs::read_to_string(&validate_path).unwrap();
        assert!(content.contains("UserValidate"));
        assert!(content.contains("use sz_rust_core::validate::Validate"));
        assert!(content.contains("app::validate"));
        // 渲染后不应残留占位符
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_validate_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        // 第一次创建应成功
        execute_make_validate("User").unwrap();
        // 第二次创建同名文件应失败
        let result = execute_make_validate("User");
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_validate_nested_path() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        // 嵌套路径:admin/User → app/validate/admin/User.rs
        execute_make_validate("admin/User").unwrap();

        let validate_path = temp_dir.path().join("app/validate/admin/User.rs");
        assert!(validate_path.exists());

        let content = std::fs::read_to_string(&validate_path).unwrap();
        assert!(content.contains("UserValidate"));
        assert!(content.contains("app::validate::admin"));
    }

    // ---------- make event/listener/command/service 测试 ----------

    #[test]
    fn test_execute_make_event_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_event("UserLogin").unwrap();

        let event_path = temp_dir.path().join("app/event/UserLogin.rs");
        assert!(event_path.exists());

        let content = std::fs::read_to_string(&event_path).unwrap();
        assert!(content.contains("pub struct UserLogin;"));
        assert!(content.contains("app::event"));
        assert!(content.contains("UserLogin"));
        assert!(content.contains("use serde_json::Value"));
        // 渲染后不应残留占位符
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_event_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_event("UserLogin").unwrap();
        let result = execute_make_event("UserLogin");
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_event_nested_path() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_event("admin/UserLogin").unwrap();

        let event_path = temp_dir.path().join("app/event/admin/UserLogin.rs");
        assert!(event_path.exists());

        let content = std::fs::read_to_string(&event_path).unwrap();
        assert!(content.contains("app::event::admin"));
    }

    #[test]
    fn test_execute_make_listener_default_event_name() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        // 未指定 --event,事件名默认使用类名
        execute_make_listener("SendWelcomeEmail", None).unwrap();

        let listener_path = temp_dir.path().join("app/listener/SendWelcomeEmail.rs");
        assert!(listener_path.exists());

        let content = std::fs::read_to_string(&listener_path).unwrap();
        assert!(content.contains("pub struct SendWelcomeEmail;"));
        assert!(content.contains("app::listener"));
        assert!(content.contains("use sz_rust_core::event::{EventError, Listener}"));
        assert!(content.contains("impl Listener for SendWelcomeEmail"));
        // 默认事件名 = 类名
        assert!(content.contains(r#""SendWelcomeEmail""#));
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_listener_custom_event_name() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        // 指定 --event UserLogin
        execute_make_listener("SendWelcomeEmail", Some("UserLogin")).unwrap();

        let listener_path = temp_dir.path().join("app/listener/SendWelcomeEmail.rs");
        assert!(listener_path.exists());

        let content = std::fs::read_to_string(&listener_path).unwrap();
        assert!(content.contains(r#""UserLogin""#));
        assert!(!content.contains(r#""SendWelcomeEmail""#));
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_listener_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_listener("SendWelcomeEmail", None).unwrap();
        let result = execute_make_listener("SendWelcomeEmail", None);
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_command_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_command("SyncData").unwrap();

        let command_path = temp_dir.path().join("app/command/SyncData.rs");
        assert!(command_path.exists());

        let content = std::fs::read_to_string(&command_path).unwrap();
        assert!(content.contains("pub struct SyncData;"));
        assert!(content.contains("app::command"));
        assert!(content.contains("use sz_rust_cli::console::{Command, CommandSignature}"));
        assert!(content.contains("impl Command for SyncData"));
        // 命令名应为 snake_case:sync_data
        assert!(content.contains(r#""sync_data""#));
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_command_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_command("SyncData").unwrap();
        let result = execute_make_command("SyncData");
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_command_nested_path() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_command("admin/SyncData").unwrap();

        let command_path = temp_dir.path().join("app/command/admin/SyncData.rs");
        assert!(command_path.exists());

        let content = std::fs::read_to_string(&command_path).unwrap();
        assert!(content.contains("app::command::admin"));
    }

    #[test]
    fn test_execute_make_service_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_service("UserService").unwrap();

        let service_path = temp_dir.path().join("app/service/UserService.rs");
        assert!(service_path.exists());

        let content = std::fs::read_to_string(&service_path).unwrap();
        assert!(content.contains("pub struct UserService;"));
        assert!(content.contains("app::service"));
        assert!(content.contains("impl Default for UserService"));
        assert!(content.contains("pub fn new() -> Self"));
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_service_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_service("UserService").unwrap();
        let result = execute_make_service("UserService");
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_service_nested_path() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_service("admin/UserService").unwrap();

        let service_path = temp_dir.path().join("app/service/admin/UserService.rs");
        assert!(service_path.exists());

        let content = std::fs::read_to_string(&service_path).unwrap();
        assert!(content.contains("app::service::admin"));
    }

    // ---------- make controller/guard/middleware/scaffold 测试 ----------

    #[test]
    fn test_execute_make_controller_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_controller("User", false, false).unwrap();

        let controller_path = temp_dir.path().join("app/controller/User.rs");
        assert!(controller_path.exists());

        let content = std::fs::read_to_string(&controller_path).unwrap();
        assert!(content.contains("User"));
        assert!(content.contains("app::controller"));
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_controller_api() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_controller("User", true, false).unwrap();

        let controller_path = temp_dir.path().join("app/controller/User.rs");
        assert!(controller_path.exists());

        let content = std::fs::read_to_string(&controller_path).unwrap();
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_controller_plain() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_controller("User", false, true).unwrap();

        let controller_path = temp_dir.path().join("app/controller/User.rs");
        assert!(controller_path.exists());

        let content = std::fs::read_to_string(&controller_path).unwrap();
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_controller_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_controller("User", false, false).unwrap();
        let result = execute_make_controller("User", false, false);
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_guard_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_guard("Admin").unwrap();

        let guard_path = temp_dir.path().join("app/guard/Admin.rs");
        assert!(guard_path.exists());

        let content = std::fs::read_to_string(&guard_path).unwrap();
        assert!(content.contains("pub struct Admin;"));
        assert!(content.contains("impl Guard for Admin"));
        assert!(content.contains("use sz_rust_core::guard::Guard"));
    }

    #[test]
    fn test_execute_make_guard_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_guard("Admin").unwrap();
        let result = execute_make_guard("Admin");
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_middleware_creates_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_middleware("Cors").unwrap();

        let middleware_path = temp_dir.path().join("app/middleware/Cors.rs");
        assert!(middleware_path.exists());

        let content = std::fs::read_to_string(&middleware_path).unwrap();
        assert!(content.contains("Cors"));
        assert!(content.contains("app::middleware"));
        assert!(!content.contains("{%"));
    }

    #[test]
    fn test_execute_make_middleware_file_already_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_middleware("Cors").unwrap();
        let result = execute_make_middleware("Cors");
        assert!(matches!(result, Err(CliError::FileExists(_))));
    }

    #[test]
    fn test_execute_make_scaffold_creates_files() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        execute_make_scaffold("Post").unwrap();

        // scaffold 应生成 model + controller + migration
        let model_path = temp_dir.path().join("app/model/Post.rs");
        let controller_path = temp_dir.path().join("app/controller/Post.rs");
        assert!(model_path.exists(), "model should be created");
        assert!(controller_path.exists(), "controller should be created");
        // migration 目录应有文件
        let migrations_dir = temp_dir.path().join("migrations");
        assert!(migrations_dir.exists(), "migrations dir should be created");
        let migration_count = std::fs::read_dir(&migrations_dir).unwrap().count();
        assert_eq!(
            migration_count, 2,
            "should create up + down migration files"
        );
    }

    #[tokio::test]
    async fn test_execute_dispatch_model() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Model {
            name: "User".to_string(),
        };
        execute(&cmd).await.unwrap();

        let model_path = temp_dir.path().join("app/model/User.rs");
        assert!(model_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_controller() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Controller {
            name: "User".to_string(),
            api: false,
            plain: false,
        };
        execute(&cmd).await.unwrap();

        let controller_path = temp_dir.path().join("app/controller/User.rs");
        assert!(controller_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_migration() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let migrations_path = temp_dir.path().join("migrations");
        let cmd = MakeCommand::Migration {
            name: "create_users".to_string(),
            path: migrations_path.to_string_lossy().to_string(),
        };
        execute(&cmd).await.unwrap();

        let migration_count = std::fs::read_dir(&migrations_path).unwrap().count();
        assert_eq!(migration_count, 2);
    }

    #[tokio::test]
    async fn test_execute_dispatch_seeder() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let seeds_path = temp_dir.path().join("seeds");
        let cmd = MakeCommand::Seeder {
            name: "001_users".to_string(),
            path: seeds_path.to_string_lossy().to_string(),
        };
        execute(&cmd).await.unwrap();

        let seeder_path = seeds_path.join("001_users.sql");
        assert!(seeder_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_guard() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Guard {
            name: "Admin".to_string(),
        };
        execute(&cmd).await.unwrap();

        let guard_path = temp_dir.path().join("app/guard/Admin.rs");
        assert!(guard_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_event() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Event {
            name: "UserLogin".to_string(),
        };
        execute(&cmd).await.unwrap();

        let event_path = temp_dir.path().join("app/event/UserLogin.rs");
        assert!(event_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_listener() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Listener {
            name: "SendEmail".to_string(),
            event: None,
        };
        execute(&cmd).await.unwrap();

        let listener_path = temp_dir.path().join("app/listener/SendEmail.rs");
        assert!(listener_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_command() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Command {
            name: "SyncData".to_string(),
        };
        execute(&cmd).await.unwrap();

        let command_path = temp_dir.path().join("app/command/SyncData.rs");
        assert!(command_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_service() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Service {
            name: "UserService".to_string(),
        };
        execute(&cmd).await.unwrap();

        let service_path = temp_dir.path().join("app/service/UserService.rs");
        assert!(service_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_middleware() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Middleware {
            name: "Cors".to_string(),
        };
        execute(&cmd).await.unwrap();

        let middleware_path = temp_dir.path().join("app/middleware/Cors.rs");
        assert!(middleware_path.exists());
    }

    #[tokio::test]
    async fn test_execute_dispatch_scaffold() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Scaffold {
            name: "Post".to_string(),
        };
        execute(&cmd).await.unwrap();

        let model_path = temp_dir.path().join("app/model/Post.rs");
        assert!(model_path.exists());
    }

    // ---------- make:plugin 测试 ----------

    #[tokio::test]
    async fn test_execute_make_plugin_crud() {
        let temp_dir = tempfile::tempdir().unwrap();
        let args = crate::context_builder::PluginCommandArgs {
            template: "plugin-crud".to_string(),
            name: "test_plugin".to_string(),
            table: Some("test_table".to_string()),
            fields: Some("id:i32:pk,name:String".to_string()),
            force: false,
            output: Some(
                temp_dir
                    .path()
                    .join("myplugin")
                    .to_string_lossy()
                    .to_string(),
            ),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        // 生成后 cargo check 因无 Cargo.toml 失败,回滚
        let result = execute_make_plugin(args).await;
        assert!(result.is_err(), "无 Cargo.toml 应失败");
        let err = format!("{}", result.unwrap_err());
        // 失败文案跨平台不同:Windows 直报 Cargo.toml 缺失,Linux 走
        // CompileFailed 包装为 "Compilation failed: [...]"——断言失败族而非文案
        assert!(
            err.contains("Cargo.toml")
                || err.contains("CompileFailed")
                || err.contains("Compilation failed"),
            "应含编译失败: {err}"
        );
    }

    #[tokio::test]
    async fn test_execute_make_plugin_workflow() {
        let temp_dir = tempfile::tempdir().unwrap();
        let args = crate::context_builder::PluginCommandArgs {
            template: "plugin-workflow".to_string(),
            name: "wf_plugin".to_string(),
            table: None,
            fields: Some("id:i32:pk,title:String".to_string()),
            force: false,
            output: Some(
                temp_dir
                    .path()
                    .join("wfplugin")
                    .to_string_lossy()
                    .to_string(),
            ),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute_make_plugin(args).await;
        assert!(result.is_err(), "无 Cargo.toml 应失败");
    }

    #[tokio::test]
    async fn test_execute_make_plugin_report() {
        let temp_dir = tempfile::tempdir().unwrap();
        let args = crate::context_builder::PluginCommandArgs {
            template: "plugin-report".to_string(),
            name: "rpt_plugin".to_string(),
            table: None,
            fields: Some("id:i32:pk,data:String".to_string()),
            force: false,
            output: Some(
                temp_dir
                    .path()
                    .join("rptplugin")
                    .to_string_lossy()
                    .to_string(),
            ),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute_make_plugin(args).await;
        assert!(result.is_err(), "无 Cargo.toml 应失败");
    }

    #[tokio::test]
    async fn test_execute_make_plugin_dir_exists_no_force() {
        let temp_dir = tempfile::tempdir().unwrap();
        let output_dir = temp_dir.path().join("existing_plugin");
        std::fs::create_dir_all(&output_dir).unwrap();

        let args = crate::context_builder::PluginCommandArgs {
            template: "plugin-crud".to_string(),
            name: "existing".to_string(),
            table: None,
            fields: Some("id:i32:pk".to_string()),
            force: false,
            output: Some(output_dir.to_string_lossy().to_string()),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute_make_plugin(args).await;
        assert!(matches!(result, Err(CliError::DirExists(_))));
    }

    #[tokio::test]
    async fn test_execute_make_plugin_force_overwrite() {
        let temp_dir = tempfile::tempdir().unwrap();
        let output_dir = temp_dir.path().join("force_plugin");
        std::fs::create_dir_all(&output_dir).unwrap();

        let args = crate::context_builder::PluginCommandArgs {
            template: "plugin-crud".to_string(),
            name: "forced".to_string(),
            table: None,
            fields: Some("id:i32:pk".to_string()),
            force: true,
            output: Some(output_dir.to_string_lossy().to_string()),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute_make_plugin(args).await;
        assert!(result.is_err(), "无 Cargo.toml 应失败");
    }

    #[tokio::test]
    async fn test_execute_make_plugin_invalid_name() {
        let temp_dir = tempfile::tempdir().unwrap();
        let args = crate::context_builder::PluginCommandArgs {
            template: "plugin-crud".to_string(),
            name: "InvalidName".to_string(),
            table: None,
            fields: None,
            force: false,
            output: Some(temp_dir.path().join("bad").to_string_lossy().to_string()),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute_make_plugin(args).await;
        assert!(result.is_err(), "大写插件名应失败");
    }

    #[tokio::test]
    async fn test_execute_make_plugin_invalid_template() {
        let temp_dir = tempfile::tempdir().unwrap();
        let args = crate::context_builder::PluginCommandArgs {
            template: "nonexistent".to_string(),
            name: "test_plug".to_string(),
            table: None,
            fields: None,
            force: false,
            output: Some(temp_dir.path().join("bad").to_string_lossy().to_string()),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute_make_plugin(args).await;
        assert!(result.is_err(), "不存在的模板应失败");
    }

    #[tokio::test]
    async fn test_execute_dispatch_plugin() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();

        let cmd = MakeCommand::Plugin {
            template: "plugin-crud".to_string(),
            name: "dispatched".to_string(),
            table: None,
            fields: Some("id:i32:pk".to_string()),
            force: false,
            output: Some(temp_dir.path().join("disp").to_string_lossy().to_string()),
            master: None,
            slave: None,
            master_fields: None,
            slave_fields: None,
            foreign_key: None,
        };
        let result = execute(&cmd).await;
        assert!(result.is_err(), "无 Cargo.toml 应失败");
    }

    #[tokio::test]
    async fn test_execute_make_frontend_invalid_framework() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let result = execute_make_frontend(
            &["User".to_string()],
            "src/model/",
            "invalid_framework",
            "element_plus",
            "./frontend/",
            None,
            "skip",
            false,
            false,
            true,
            false,
        )
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("不支持的前端框架"));
    }

    #[tokio::test]
    async fn test_execute_make_frontend_invalid_ui() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let result = execute_make_frontend(
            &["User".to_string()],
            "src/model/",
            "vue",
            "invalid_ui",
            "./frontend/",
            None,
            "skip",
            false,
            false,
            true,
            false,
        )
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("不支持的 UI 库"));
    }

    #[tokio::test]
    async fn test_execute_make_frontend_invalid_override_strategy() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let result = execute_make_frontend(
            &["User".to_string()],
            "src/model/",
            "vue",
            "element_plus",
            "./frontend/",
            None,
            "invalid_strategy",
            false,
            false,
            true,
            false,
        )
        .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("不支持的覆盖策略"));
    }

    #[tokio::test]
    async fn test_execute_make_frontend_vue_element_plus() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let model_dir = temp_dir.path().join("src/model");
        std::fs::create_dir_all(&model_dir).unwrap();
        std::fs::write(
            model_dir.join("User.rs"),
            "#[derive(Model)]\npub struct User { pub id: i32, pub name: String }",
        )
        .unwrap();
        let output = temp_dir
            .path()
            .join("frontend")
            .to_string_lossy()
            .to_string();
        let result = execute_make_frontend(
            &["User".to_string()],
            &model_dir.to_string_lossy(),
            "vue",
            "element_plus",
            &output,
            None,
            "skip",
            false,
            false,
            true,
            false,
        )
        .await;
        assert!(result.is_ok(), "vue+element_plus 应成功: {:?}", result);
    }

    #[tokio::test]
    async fn test_execute_make_frontend_react_ant_design() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let model_dir = temp_dir.path().join("src/model");
        std::fs::create_dir_all(&model_dir).unwrap();
        std::fs::write(
            model_dir.join("Product.rs"),
            "#[derive(Model)]\npub struct Product { pub id: i32, pub name: String }",
        )
        .unwrap();
        let output = temp_dir
            .path()
            .join("frontend")
            .to_string_lossy()
            .to_string();
        let result = execute_make_frontend(
            &["Product".to_string()],
            &model_dir.to_string_lossy(),
            "react",
            "ant_design_vue",
            &output,
            None,
            "overwrite",
            true,
            true,
            false,
            true,
        )
        .await;
        assert!(result.is_ok(), "react+ant_design_vue 应成功: {:?}", result);
    }

    #[tokio::test]
    async fn test_execute_make_frontend_element_plus_hyphen() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let model_dir = temp_dir.path().join("src/model");
        std::fs::create_dir_all(&model_dir).unwrap();
        std::fs::write(
            model_dir.join("Order.rs"),
            "#[derive(Model)]\npub struct Order { pub id: i32 }",
        )
        .unwrap();
        let output = temp_dir
            .path()
            .join("frontend")
            .to_string_lossy()
            .to_string();
        let result = execute_make_frontend(
            &["Order".to_string()],
            &model_dir.to_string_lossy(),
            "vue",
            "element-plus",
            &output,
            None,
            "merge",
            false,
            false,
            true,
            false,
        )
        .await;
        assert!(result.is_ok(), "element-plus (hyphen) 应成功: {:?}", result);
    }

    #[tokio::test]
    async fn test_execute_make_frontend_ant_design_hyphen() {
        let temp_dir = tempfile::tempdir().unwrap();
        let _guard = CwdGuard::switch(temp_dir.path()).unwrap();
        let model_dir = temp_dir.path().join("src/model");
        std::fs::create_dir_all(&model_dir).unwrap();
        std::fs::write(
            model_dir.join("Item.rs"),
            "#[derive(Model)]\npub struct Item { pub id: i32 }",
        )
        .unwrap();
        let output = temp_dir
            .path()
            .join("frontend")
            .to_string_lossy()
            .to_string();
        let result = execute_make_frontend(
            &["Item".to_string()],
            &model_dir.to_string_lossy(),
            "vue",
            "ant-design-vue",
            &output,
            None,
            "skip",
            false,
            false,
            true,
            false,
        )
        .await;
        assert!(
            result.is_ok(),
            "ant-design-vue (hyphen) 应成功: {:?}",
            result
        );
    }

    #[test]
    fn test_openapi_spec_generation() {
        let spec = generate_openapi_spec("Test API", "2.0.0");
        assert_eq!(spec.openapi, "3.0.3");
        assert_eq!(spec.info.title, "Test API");
        assert_eq!(spec.info.version, "2.0.0");
    }

    #[test]
    fn test_openapi_spec_default() {
        let spec = generate_openapi_spec("SZ-Rust API", "1.0.0");
        assert_eq!(spec.info.title, "SZ-Rust API");
        assert_eq!(spec.info.version, "1.0.0");
    }

    #[test]
    fn test_openapi_spec_serialize() {
        let spec = generate_openapi_spec("Test", "1.0");
        let json = serde_json::to_string(&spec).unwrap();
        assert!(json.contains("\"openapi\":\"3.0.3\""));
        assert!(json.contains("\"title\":\"Test\""));
        assert!(json.contains("bearerAuth"));
    }

    #[test]
    fn test_check_file_exists_with_force() {
        let temp = tempfile::NamedTempFile::new().unwrap();
        let path = temp.path();

        let result = check_file_exists_with_force(path, false);
        assert!(result.is_err(), "should error without force");

        let result = check_file_exists_with_force(path, true);
        assert!(result.is_ok(), "should pass with force");
    }

    #[test]
    fn test_check_file_exists_with_force_nonexistent() {
        let path = std::path::Path::new("nonexistent_file_12345.rs");
        let result = check_file_exists_with_force(path, false);
        assert!(result.is_ok(), "nonexistent file should pass");
    }
}