mockforge-cli 0.3.116

CLI interface for MockForge
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
//! Scenario management CLI commands

use base64::{engine::general_purpose, Engine as _};
use clap::Subcommand;
use mockforge_core::behavioral_economics::BehaviorRule;
use mockforge_core::config::{load_config, save_config, ServerConfig};
use mockforge_scenarios::{
    DomainPackInstaller, InstallOptions, ScenarioInstaller, ScenarioRegistry,
    ScenarioReviewSubmission,
};
use mockforge_vbr::entities::Entity;
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::Path;

#[derive(Subcommand)]
pub enum ScenarioCommands {
    /// Install a scenario from various sources
    Install {
        /// Scenario source (URL, Git repo, local path, or registry name)
        ///
        /// Examples:
        /// - ./scenarios/my-scenario
        /// - https://github.com/user/repo#main:scenarios/my-scenario
        /// - https://example.com/scenario.zip
        /// - ecommerce-store@1.0.0
        source: String,

        /// Force reinstall even if scenario exists
        #[arg(long)]
        force: bool,

        /// Skip validation checks
        #[arg(long)]
        skip_validation: bool,

        /// Expected SHA-256 checksum (for URL sources)
        #[arg(long)]
        checksum: Option<String>,
    },

    /// Uninstall a scenario
    Uninstall {
        /// Scenario name
        name: String,

        /// Scenario version (optional, defaults to latest)
        #[arg(long)]
        version: Option<String>,
    },

    /// List installed scenarios
    List {
        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Show scenario information
    Info {
        /// Scenario name
        name: String,

        /// Scenario version (optional, defaults to latest)
        #[arg(long)]
        version: Option<String>,
    },

    /// Preview a scenario before installing
    Preview {
        /// Scenario source (URL, Git repo, local path, or registry name)
        ///
        /// Examples:
        /// - ./scenarios/my-scenario
        /// - https://github.com/user/repo#main:scenarios/my-scenario
        /// - https://example.com/scenario.zip
        /// - ecommerce-store@1.0.0
        source: String,
    },

    /// Apply scenario to current workspace
    Use {
        /// Scenario name
        name: String,

        /// Scenario version (optional, defaults to latest)
        #[arg(long)]
        version: Option<String>,

        /// Merge strategy for schema alignment (prefer-existing, prefer-scenario, intelligent, interactive)
        #[arg(long, default_value = "prefer-existing")]
        merge_strategy: String,

        /// Enable automatic schema alignment
        #[arg(long)]
        auto_align: bool,
    },

    /// Search for scenarios in the registry
    Search {
        /// Search query
        query: String,

        /// Category filter
        #[arg(long)]
        category: Option<String>,

        /// Maximum number of results
        #[arg(short, long, default_value = "10")]
        limit: usize,
    },

    /// Publish a scenario to the registry
    Publish {
        /// Path to scenario directory
        path: String,

        /// Registry URL (optional)
        #[arg(long)]
        registry: Option<String>,
    },

    /// Update a scenario to the latest version
    Update {
        /// Scenario name to update (or --all for all scenarios)
        name: Option<String>,

        /// Update all installed scenarios
        #[arg(long)]
        all: bool,
    },

    /// Domain pack commands
    Pack {
        /// Pack subcommand
        #[command(subcommand)]
        command: PackCommands,
    },

    /// Review commands
    Review {
        /// Review subcommand
        #[command(subcommand)]
        command: ReviewCommands,
    },
}

#[derive(Subcommand)]
pub enum PackCommands {
    /// List installed domain packs
    List,

    /// Install a domain pack from a manifest file
    Install {
        /// Path to pack manifest file (pack.yaml or pack.json)
        manifest: String,
    },

    /// Show information about a domain pack
    Info {
        /// Pack name
        name: String,
    },

    /// Studio pack commands (full studio packs with personas, chaos rules, etc.)
    Studio {
        /// Studio pack subcommand
        #[command(subcommand)]
        command: StudioPackCommands,
    },
}

#[derive(Subcommand)]
pub enum StudioPackCommands {
    /// Install a studio pack (applies personas, chaos rules, contract diffs, reality blends)
    Install {
        /// Studio pack name (e.g., "fintech-fraud-lab", "ecommerce-peak-day", "healthcare-outage-drill")
        /// or path to pack manifest file
        pack_name: String,

        /// Workspace ID to install the pack to (defaults to "default")
        #[arg(short, long, default_value = "default")]
        workspace: String,
    },

    /// List available studio packs
    List,

    /// Create a new studio pack from the current workspace configuration
    Create {
        /// Name for the new studio pack
        name: String,

        /// Output path for the pack manifest (defaults to ./{name}-pack.yaml)
        #[arg(short, long)]
        output: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum ReviewCommands {
    /// Submit a review for a scenario
    Submit {
        /// Scenario name
        scenario_name: String,

        /// Scenario version (optional)
        #[arg(long)]
        scenario_version: Option<String>,

        /// Rating (1-5)
        #[arg(short, long)]
        rating: u8,

        /// Review title (optional)
        #[arg(long)]
        title: Option<String>,

        /// Review comment/text
        #[arg(short, long)]
        comment: String,

        /// Reviewer name/username
        #[arg(long)]
        reviewer: String,

        /// Reviewer email (optional)
        #[arg(long)]
        reviewer_email: Option<String>,

        /// Mark as verified purchase (reviewer used the scenario)
        #[arg(long)]
        verified: bool,
    },

    /// List reviews for a scenario
    List {
        /// Scenario name
        scenario_name: String,

        /// Page number (0-indexed)
        #[arg(long, default_value = "0")]
        page: Option<usize>,

        /// Results per page
        #[arg(long, default_value = "20")]
        per_page: Option<usize>,
    },
}

/// Handle scenario commands
pub async fn handle_scenario_command(command: ScenarioCommands) -> anyhow::Result<()> {
    match command {
        ScenarioCommands::Install {
            source,
            force,
            skip_validation,
            checksum,
        } => {
            println!("📦 Installing scenario from: {}", source);

            let mut installer = ScenarioInstaller::new()?;
            installer.init().await?;

            let options = InstallOptions {
                force,
                skip_validation,
                expected_checksum: checksum,
            };

            match installer.install(&source, options).await {
                Ok(scenario_id) => {
                    println!("✅ Scenario installed successfully: {}", scenario_id);
                }
                Err(e) => {
                    eprintln!("❌ Failed to install scenario: {}", e);
                    std::process::exit(1);
                }
            }
        }

        ScenarioCommands::Uninstall { name, version } => {
            let version = version.unwrap_or_else(|| "latest".to_string());
            println!("🗑️  Uninstalling scenario: {}@{}", name, version);

            let mut installer = ScenarioInstaller::new()?;
            installer.init().await?;

            // If version is "latest", get the latest version
            let actual_version = if version == "latest" {
                installer
                    .get_latest(&name)
                    .map(|s| s.version.clone())
                    .ok_or_else(|| anyhow::anyhow!("Scenario '{}' not found", name))?
            } else {
                version
            };

            match installer.uninstall(&name, &actual_version).await {
                Ok(_) => {
                    println!("✅ Scenario uninstalled successfully");
                }
                Err(e) => {
                    eprintln!("❌ Failed to uninstall scenario: {}", e);
                    std::process::exit(1);
                }
            }
        }

        ScenarioCommands::List { detailed } => {
            println!("📋 Installed scenarios:");

            let mut installer = ScenarioInstaller::new()?;
            installer.init().await?;

            let scenarios = installer.list_installed();

            if scenarios.is_empty() {
                println!("  No scenarios installed");
            } else {
                for scenario in scenarios {
                    if detailed {
                        println!("  - {}@{}", scenario.name, scenario.version);
                        println!("    Path: {}", scenario.path.display());
                        println!("    Description: {}", scenario.manifest.description);
                        println!("    Category: {:?}", scenario.manifest.category);
                        println!("    Installed: {}", scenario.installed_at);
                    } else {
                        println!("  - {}@{}", scenario.name, scenario.version);
                    }
                }
            }
        }

        ScenarioCommands::Info { name, version } => {
            let mut installer = ScenarioInstaller::new()?;
            installer.init().await?;

            let scenario = if let Some(v) = version {
                installer.get(&name, &v)
            } else {
                installer.get_latest(&name)
            };

            match scenario {
                Some(s) => {
                    println!("ℹ️  Scenario information: {}@{}", s.name, s.version);
                    println!("   Title: {}", s.manifest.title);
                    println!("   Description: {}", s.manifest.description);
                    println!("   Author: {}", s.manifest.author);
                    println!("   Category: {:?}", s.manifest.category);
                    println!("   Tags: {}", s.manifest.tags.join(", "));
                    println!("   Path: {}", s.path.display());
                    println!("   Installed: {}", s.installed_at);
                    if let Some(updated) = s.updated_at {
                        println!("   Updated: {}", updated);
                    }
                }
                None => {
                    eprintln!("❌ Scenario '{}' not found", name);
                    std::process::exit(1);
                }
            }
        }

        ScenarioCommands::Preview { source } => {
            println!("👁️  Previewing scenario from: {}", source);

            let installer = ScenarioInstaller::new()?;

            match installer.preview(&source).await {
                Ok(preview) => {
                    println!("{}", preview.format_display());
                }
                Err(e) => {
                    eprintln!("❌ Failed to preview scenario: {}", e);
                    std::process::exit(1);
                }
            }
        }

        ScenarioCommands::Use {
            name,
            version,
            merge_strategy,
            auto_align,
        } => {
            let mut installer = ScenarioInstaller::new()?;
            installer.init().await?;

            let version_clone = version.clone();
            let scenario = if let Some(ref v) = version {
                installer.get(&name, v)
            } else {
                installer.get_latest(&name)
            };

            match scenario {
                Some(s) => {
                    println!("🎯 Applying scenario: {}@{}", s.name, s.version);

                    // Parse merge strategy
                    let alignment_config = if auto_align {
                        use mockforge_scenarios::schema_alignment::{
                            MergeStrategy, SchemaAlignmentConfig,
                        };
                        let strategy = match merge_strategy.as_str() {
                            "prefer-existing" => MergeStrategy::PreferExisting,
                            "prefer-scenario" => MergeStrategy::PreferScenario,
                            "intelligent" => MergeStrategy::Intelligent,
                            "interactive" => MergeStrategy::Interactive,
                            _ => {
                                eprintln!("❌ Invalid merge strategy: {}. Valid options: prefer-existing, prefer-scenario, intelligent, interactive", merge_strategy);
                                std::process::exit(1);
                            }
                        };
                        Some(SchemaAlignmentConfig {
                            merge_strategy: strategy,
                            validate_merged: true,
                            backup_existing: true,
                        })
                    } else {
                        None
                    };

                    match installer
                        .apply_to_workspace_with_alignment(
                            &name,
                            version_clone.as_deref(),
                            alignment_config,
                        )
                        .await
                    {
                        Ok(_) => {
                            println!("✅ Scenario applied successfully to workspace");
                            if auto_align {
                                println!(
                                    "   Schema alignment enabled (strategy: {})",
                                    merge_strategy
                                );
                            }
                            println!(
                                "   Files copied: config.yaml, openapi.json, fixtures/, examples/"
                            );

                            // Apply VBR entities if present
                            if let Ok(Some(vbr_entities)) =
                                installer.get_vbr_entities(&name, version_clone.as_deref())
                            {
                                if !vbr_entities.is_empty() {
                                    println!("\n🔧 Applying VBR entities...");
                                    match apply_vbr_entities_from_scenario(vbr_entities, &s.path)
                                        .await
                                    {
                                        Ok(count) => {
                                            println!("   ✅ Applied {} VBR entities", count);
                                        }
                                        Err(e) => {
                                            println!(
                                                "   ⚠️  Warning: Failed to apply VBR entities: {}",
                                                e
                                            );
                                            println!("   You can apply them manually using 'mockforge vbr' commands");
                                        }
                                    }
                                }
                            }

                            // Merge MockAI config if present
                            if let Ok(Some(mockai_config)) =
                                installer.get_mockai_config(&name, version_clone.as_deref())
                            {
                                println!("\n🤖 Merging MockAI configuration...");
                                match merge_mockai_config_from_scenario(mockai_config, &s.path)
                                    .await
                                {
                                    Ok(_) => {
                                        println!("   ✅ MockAI config merged into config.yaml");
                                    }
                                    Err(e) => {
                                        println!(
                                            "   ⚠️  Warning: Failed to merge MockAI config: {}",
                                            e
                                        );
                                        println!(
                                            "   MockAI config is available in the scenario package"
                                        );
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("❌ Failed to apply scenario: {}", e);
                            std::process::exit(1);
                        }
                    }
                }
                None => {
                    eprintln!("❌ Scenario '{}' not found", name);
                    std::process::exit(1);
                }
            }
        }

        ScenarioCommands::Search {
            query,
            category,
            limit,
        } => {
            println!("🔍 Searching for scenarios: {}", query);

            let registry = ScenarioRegistry::new("https://registry.mockforge.dev".to_string());

            let search_query = mockforge_scenarios::ScenarioSearchQuery {
                query: Some(query),
                category,
                tags: vec![],
                sort: mockforge_scenarios::ScenarioSortOrder::Relevance,
                page: 0,
                per_page: limit,
            };

            match registry.search(search_query).await {
                Ok(results) => {
                    if results.scenarios.is_empty() {
                        println!("  No scenarios found");
                    } else {
                        println!("  Found {} scenarios:", results.total);
                        for scenario in results.scenarios {
                            println!("  - {}@{}", scenario.name, scenario.version);
                            println!("    {}", scenario.description);
                        }
                    }
                }
                Err(e) => {
                    eprintln!("❌ Failed to search scenarios: {}", e);
                    std::process::exit(1);
                }
            }
        }

        ScenarioCommands::Publish { path, registry } => {
            println!("📤 Publishing scenario from: {}", path);

            // Load scenario package
            let package = mockforge_scenarios::ScenarioPackage::from_directory(&path)
                .map_err(|e| anyhow::anyhow!("Failed to load scenario package: {}", e))?;

            // Validate package
            let validation = package
                .validate()
                .map_err(|e| anyhow::anyhow!("Package validation failed: {}", e))?;

            if !validation.is_valid {
                eprintln!("❌ Package validation failed:");
                for error in &validation.errors {
                    eprintln!("   - {}", error);
                }
                std::process::exit(1);
            }

            // Warn about warnings
            if !validation.warnings.is_empty() {
                println!("⚠️  Package validation warnings:");
                for warning in &validation.warnings {
                    println!("   - {}", warning);
                }
            }

            // Create package archive
            println!("   Creating package archive...");
            let (archive_path, checksum, size) = create_scenario_archive(&package)
                .map_err(|e| anyhow::anyhow!("Failed to create archive: {}", e))?;

            println!("   Package size: {} bytes", size);
            println!("   Checksum: {}", checksum);

            // Read archive as base64
            let archive_data = fs::read(&archive_path)
                .map_err(|e| anyhow::anyhow!("Failed to read archive: {}", e))?;
            let archive_base64 = general_purpose::STANDARD.encode(&archive_data);

            // Serialize manifest
            let manifest_json = serde_json::to_string(&package.manifest)
                .map_err(|e| anyhow::anyhow!("Failed to serialize manifest: {}", e))?;

            // Create publish request
            let publish_request = mockforge_scenarios::ScenarioPublishRequest {
                manifest: manifest_json,
                package: archive_base64,
                checksum,
                size,
            };

            // Get registry URL and token
            let registry_url =
                registry.unwrap_or_else(|| "https://registry.mockforge.dev".to_string());
            let token = std::env::var("MOCKFORGE_REGISTRY_TOKEN")
                .map_err(|_| anyhow::anyhow!("MOCKFORGE_REGISTRY_TOKEN environment variable not set. Required for publishing."))?;

            // Create registry client and publish
            let registry_client = ScenarioRegistry::with_token(registry_url, token);

            println!("   Publishing to registry...");
            match registry_client.publish(publish_request).await {
                Ok(response) => {
                    println!("✅ Scenario published successfully!");
                    println!("   Name: {}@{}", response.name, response.version);
                    println!("   Download URL: {}", response.download_url);
                    println!("   Published at: {}", response.published_at);
                }
                Err(e) => {
                    eprintln!("❌ Failed to publish scenario: {}", e);
                    std::process::exit(1);
                }
            }

            // Clean up temp archive
            let _ = fs::remove_file(&archive_path);
        }

        ScenarioCommands::Update { name, all } => {
            let mut installer = ScenarioInstaller::new()?;
            installer.init().await?;

            if all {
                println!("🔄 Updating all scenarios...");

                match installer.update_all().await {
                    Ok(updated) => {
                        if updated.is_empty() {
                            println!("✅ All scenarios are up to date");
                        } else {
                            println!("✅ Updated {} scenarios:", updated.len());
                            for item in updated {
                                println!("   - {}", item);
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("❌ Failed to update scenarios: {}", e);
                        std::process::exit(1);
                    }
                }
            } else if let Some(n) = name {
                println!("🔄 Updating scenario: {}", n);

                // Get current scenario info
                let scenario = installer
                    .get_latest(&n)
                    .ok_or_else(|| anyhow::anyhow!("Scenario '{}' not found", n))?;

                let current_version = scenario.version.clone();
                let source_str = scenario.source.clone();

                // Parse source to check if it's from registry
                let source = mockforge_scenarios::ScenarioSource::parse(&source_str)?;

                match source {
                    mockforge_scenarios::ScenarioSource::Registry { .. } => {
                        // Update from registry
                        let mut installer_mut = installer;
                        match installer_mut.update_from_registry(&n, &current_version).await {
                            Ok(new_version) => {
                                if new_version == current_version {
                                    println!(
                                        "✅ Scenario is already up to date: {}@{}",
                                        n, current_version
                                    );
                                } else {
                                    println!(
                                        "✅ Scenario updated: {}@{} -> {}",
                                        n, current_version, new_version
                                    );
                                }
                            }
                            Err(e) => {
                                eprintln!("❌ Failed to update scenario: {}", e);
                                std::process::exit(1);
                            }
                        }
                    }
                    _ => {
                        // Reinstall from original source
                        println!("   Reinstalling from original source: {}", source_str);
                        let options = InstallOptions {
                            force: true,
                            skip_validation: false,
                            expected_checksum: None,
                        };

                        match installer.install(&source_str, options).await {
                            Ok(_) => {
                                println!("✅ Scenario updated successfully");
                            }
                            Err(e) => {
                                eprintln!("❌ Failed to update scenario: {}", e);
                                std::process::exit(1);
                            }
                        }
                    }
                }
            } else {
                eprintln!("❌ Please specify a scenario name or use --all");
                std::process::exit(1);
            }
        }

        ScenarioCommands::Pack { command } => match command {
            PackCommands::List => {
                println!("📦 Installed domain packs:");

                let pack_installer = DomainPackInstaller::new()?;
                pack_installer.init()?;

                let packs = pack_installer.list_installed()?;

                if packs.is_empty() {
                    println!("  No packs installed");
                } else {
                    for pack in packs {
                        println!(
                            "  - {}@{} ({})",
                            pack.manifest.name, pack.manifest.version, pack.manifest.domain
                        );
                        println!("    Title: {}", pack.manifest.title);
                        println!("    Scenarios: {}", pack.manifest.scenarios.len());
                    }
                }
            }

            PackCommands::Install { manifest } => {
                println!("📦 Installing domain pack from: {}", manifest);

                let pack_installer = DomainPackInstaller::new()?;
                pack_installer.init()?;

                let manifest_path = Path::new(&manifest);
                if !manifest_path.exists() {
                    eprintln!("❌ Pack manifest not found: {}", manifest);
                    std::process::exit(1);
                }

                match pack_installer.install_from_manifest(manifest_path) {
                    Ok(pack_info) => {
                        println!(
                            "✅ Pack installed successfully: {}@{}",
                            pack_info.manifest.name, pack_info.manifest.version
                        );
                        println!("   Domain: {}", pack_info.manifest.domain);
                        println!("   Scenarios: {}", pack_info.manifest.scenarios.len());
                        println!("\n   To install scenarios from this pack, use:");
                        for scenario in &pack_info.manifest.scenarios {
                            println!("     mockforge scenario install {}", scenario.source);
                        }
                    }
                    Err(e) => {
                        eprintln!("❌ Failed to install pack: {}", e);
                        std::process::exit(1);
                    }
                }
            }

            PackCommands::Info { name } => {
                let pack_installer = DomainPackInstaller::new()?;
                pack_installer.init()?;

                match pack_installer.get_pack(&name)? {
                    Some(pack_info) => {
                        println!(
                            "ℹ️  Pack information: {}@{}",
                            pack_info.manifest.name, pack_info.manifest.version
                        );
                        println!("   Title: {}", pack_info.manifest.title);
                        println!("   Description: {}", pack_info.manifest.description);
                        println!("   Domain: {}", pack_info.manifest.domain);
                        println!("   Author: {}", pack_info.manifest.author);
                        println!("   Scenarios ({}):", pack_info.manifest.scenarios.len());
                        for scenario in &pack_info.manifest.scenarios {
                            println!("     - {} ({})", scenario.name, scenario.source);
                            if let Some(ref desc) = scenario.description {
                                println!("       {}", desc);
                            }
                        }
                        // Show studio pack components if present
                        if !pack_info.manifest.personas.is_empty() {
                            println!("   Personas ({}):", pack_info.manifest.personas.len());
                            for persona in &pack_info.manifest.personas {
                                println!("     - {} ({})", persona.name, persona.id);
                            }
                        }
                        if !pack_info.manifest.chaos_rules.is_empty() {
                            println!("   Chaos Rules ({}):", pack_info.manifest.chaos_rules.len());
                            for rule in &pack_info.manifest.chaos_rules {
                                println!("     - {}", rule.name);
                            }
                        }
                        if !pack_info.manifest.contract_diffs.is_empty() {
                            println!(
                                "   Contract Diffs ({}):",
                                pack_info.manifest.contract_diffs.len()
                            );
                            for diff in &pack_info.manifest.contract_diffs {
                                println!("     - {}", diff.name);
                            }
                        }
                        if !pack_info.manifest.reality_blends.is_empty() {
                            println!(
                                "   Reality Blends ({}):",
                                pack_info.manifest.reality_blends.len()
                            );
                            for blend in &pack_info.manifest.reality_blends {
                                println!(
                                    "     - {} ({}% real)",
                                    blend.name,
                                    (blend.reality_ratio * 100.0) as u32
                                );
                            }
                        }
                    }
                    None => {
                        eprintln!("❌ Pack '{}' not found", name);
                        std::process::exit(1);
                    }
                }
            }

            PackCommands::Studio { command } => {
                use mockforge_scenarios::StudioPackInstaller;

                let packs_dir = dirs::data_dir()
                    .ok_or_else(|| anyhow::anyhow!("Failed to get data directory"))?
                    .join("mockforge")
                    .join("packs");
                let studio_installer = StudioPackInstaller::new(packs_dir);

                match command {
                    StudioPackCommands::Install {
                        pack_name,
                        workspace,
                    } => {
                        println!("🎨 Installing studio pack: {}", pack_name);

                        // Check if it's a pre-built pack or a path
                        let manifest = if pack_name == "fintech-fraud-lab" {
                            #[cfg(feature = "studio-packs")]
                            {
                                Some(mockforge_scenarios::create_fintech_fraud_lab_pack())
                            }
                            #[cfg(not(feature = "studio-packs"))]
                            {
                                return Err(anyhow::anyhow!("studio-packs feature not enabled"));
                            }
                        } else if pack_name == "ecommerce-peak-day" {
                            #[cfg(feature = "studio-packs")]
                            {
                                Some(mockforge_scenarios::create_ecommerce_peak_day_pack())
                            }
                            #[cfg(not(feature = "studio-packs"))]
                            {
                                return Err(anyhow::anyhow!("studio-packs feature not enabled"));
                            }
                        } else if pack_name == "healthcare-outage-drill" {
                            #[cfg(feature = "studio-packs")]
                            {
                                Some(mockforge_scenarios::create_healthcare_outage_drill_pack())
                            }
                            #[cfg(not(feature = "studio-packs"))]
                            {
                                return Err(anyhow::anyhow!("studio-packs feature not enabled"));
                            }
                        } else {
                            // Try to load from file
                            let manifest_path = Path::new(&pack_name);
                            if manifest_path.exists() {
                                Some(mockforge_scenarios::DomainPackManifest::from_file(
                                    manifest_path,
                                )?)
                            } else {
                                eprintln!("❌ Studio pack '{}' not found", pack_name);
                                eprintln!("   Available pre-built packs: fintech-fraud-lab, ecommerce-peak-day, healthcare-outage-drill");
                                eprintln!("   Or provide a path to a pack manifest file");
                                std::process::exit(1);
                            }
                        };

                        if let Some(manifest) = manifest {
                            match studio_installer
                                .install_studio_pack(&manifest, Some(&workspace))
                                .await
                            {
                                Ok(result) => {
                                    println!("✅ Studio pack installed successfully!");
                                    println!("   Scenarios: {}", result.scenarios_installed);
                                    println!("   Personas: {}", result.personas_configured);
                                    println!("   Chaos Rules: {}", result.chaos_rules_applied);
                                    println!(
                                        "   Contract Diffs: {}",
                                        result.contract_diffs_configured
                                    );
                                    println!(
                                        "   Reality Blends: {}",
                                        result.reality_blends_configured
                                    );
                                    if result.workspace_config_applied {
                                        println!("   Workspace Config: Applied");
                                    }
                                    if !result.errors.is_empty() {
                                        println!("\n⚠️  Warnings:");
                                        for error in &result.errors {
                                            println!("   - {}", error);
                                        }
                                    }
                                }
                                Err(e) => {
                                    eprintln!("❌ Failed to install studio pack: {}", e);
                                    std::process::exit(1);
                                }
                            }
                        }
                    }

                    StudioPackCommands::List => {
                        println!("🎨 Available studio packs:");
                        println!("   Pre-built packs:");
                        println!(
                            "     - fintech-fraud-lab: Fraud detection and prevention scenarios"
                        );
                        println!("     - ecommerce-peak-day: High-traffic e-commerce scenarios");
                        println!(
                            "     - healthcare-outage-drill: Healthcare system outage scenarios"
                        );
                        println!("\n   To install a pack, use:");
                        println!("     mockforge scenario pack studio install <pack-name>");
                    }

                    StudioPackCommands::Create { name, output } => {
                        println!("🎨 Creating studio pack: {}", name);

                        // Load current workspace configuration
                        let config_path = std::env::current_dir()
                            .ok()
                            .map(|d| d.join("mockforge.yaml"))
                            .filter(|p| p.exists());

                        let config = if let Some(ref path) = config_path {
                            match load_config(path).await {
                                Ok(c) => c,
                                Err(e) => {
                                    eprintln!("⚠️  Failed to load config: {}. Using defaults.", e);
                                    ServerConfig::default()
                                }
                            }
                        } else {
                            println!("⚠️  No mockforge.yaml found. Creating pack with minimal configuration.");
                            ServerConfig::default()
                        };

                        // Extract personas from config (from mockai.intelligent_behavior.personas)
                        let personas = config
                            .mockai
                            .intelligent_behavior
                            .personas
                            .personas
                            .iter()
                            .map(|persona| mockforge_scenarios::domain_pack::StudioPersona {
                                id: persona.name.clone(),
                                name: persona.name.clone(),
                                domain: "general".to_string(), // Personas don't have domain in this structure
                                traits: HashMap::new(), // Personas don't have traits in this structure
                                backstory: None,
                                relationships: HashMap::new(),
                                metadata: HashMap::new(),
                            })
                            .collect();

                        // Extract chaos rules from config (chaos rules are not directly in ServerConfig)
                        // For now, create empty list - chaos rules would need to be extracted from a different source
                        let chaos_rules = Vec::new();

                        // Extract contract diffs from config (fitness rules as contract diffs)
                        let contract_diffs = config
                            .contracts
                            .fitness_rules
                            .iter()
                            .map(|rule| {
                                // Convert fitness rule to contract diff format
                                let drift_budget = serde_json::json!({
                                    "rule_type": rule.rule_type,
                                    "scope": rule.scope,
                                    "max_percent_increase": rule.max_percent_increase,
                                    "max_fields": rule.max_fields,
                                    "max_depth": rule.max_depth,
                                });

                                mockforge_scenarios::domain_pack::StudioContractDiff {
                                    name: rule.name.clone(),
                                    description: None,
                                    drift_budget,
                                    endpoint_patterns: vec![rule.scope.clone()],
                                }
                            })
                            .collect();

                        // Extract reality blends from config (reality level is not directly in ServerConfig)
                        // For now, use default moderate realism
                        let reality_blends = {
                            let reality_ratio = 0.5; // Default to moderate realism

                            vec![mockforge_scenarios::domain_pack::StudioRealityBlend {
                                name: "default".to_string(),
                                description: Some("Default reality blend from config".to_string()),
                                reality_ratio,
                                continuum_config: serde_json::json!({"level": 3}),
                                field_rules: Vec::new(),
                            }]
                        };

                        // Create studio pack manifest
                        let manifest = mockforge_scenarios::domain_pack::DomainPackManifest {
                            manifest_version: "1.0".to_string(),
                            name: name.clone(),
                            version: "1.0.0".to_string(),
                            title: format!("Studio Pack: {}", name),
                            description: format!("Exported studio pack from workspace: {}", name),
                            domain: "general".to_string(),
                            author: std::env::var("USER").unwrap_or_else(|_| "unknown".to_string()),
                            scenarios: Vec::new(), // Scenarios would need to be extracted separately
                            tags: vec!["exported".to_string(), "workspace".to_string()],
                            metadata: HashMap::new(),
                            personas,
                            chaos_rules,
                            contract_diffs,
                            reality_blends,
                            workspace_config: serde_json::to_value(&config).ok(),
                        };

                        // Determine output path
                        let output_path = output
                            .map(std::path::PathBuf::from)
                            .unwrap_or_else(|| std::path::PathBuf::from(format!("{}.yaml", name)));

                        // Write manifest to file
                        let yaml_content = serde_yaml::to_string(&manifest)
                            .map_err(|e| anyhow::anyhow!("Failed to serialize manifest: {}", e))?;

                        fs::write(&output_path, yaml_content)
                            .map_err(|e| anyhow::anyhow!("Failed to write manifest: {}", e))?;

                        println!("✅ Studio pack created successfully!");
                        println!("   Output: {}", output_path.display());
                        println!("   Personas: {}", manifest.personas.len());
                        println!("   Chaos rules: {}", manifest.chaos_rules.len());
                        println!("   Contract diffs: {}", manifest.contract_diffs.len());
                        println!("   Reality blends: {}", manifest.reality_blends.len());
                    }
                }
            }
        },

        ScenarioCommands::Review { command } => match command {
            ReviewCommands::Submit {
                scenario_name,
                scenario_version,
                rating,
                title,
                comment,
                reviewer,
                reviewer_email,
                verified,
            } => {
                println!("⭐ Submitting review for scenario: {}", scenario_name);

                let registry = ScenarioRegistry::new("https://registry.mockforge.dev".to_string());

                let review = ScenarioReviewSubmission {
                    scenario_name,
                    scenario_version,
                    rating,
                    title,
                    comment,
                    reviewer,
                    reviewer_email,
                    verified_purchase: verified,
                };

                match registry.submit_review(review).await {
                    Ok(submitted_review) => {
                        println!("✅ Review submitted successfully!");
                        println!("   Review ID: {}", submitted_review.id);
                        println!("   Rating: {}/5", submitted_review.rating);
                        if let Some(ref review_title) = submitted_review.title {
                            println!("   Title: {}", review_title);
                        }
                    }
                    Err(e) => {
                        eprintln!("❌ Failed to submit review: {}", e);
                        std::process::exit(1);
                    }
                }
            }

            ReviewCommands::List {
                scenario_name,
                page,
                per_page,
            } => {
                println!("📝 Reviews for scenario: {}", scenario_name);

                let registry = ScenarioRegistry::new("https://registry.mockforge.dev".to_string());

                match registry.get_reviews(&scenario_name, page, per_page).await {
                    Ok(reviews) => {
                        if reviews.is_empty() {
                            println!("  No reviews found");
                        } else {
                            println!("  Found {} reviews:", reviews.len());
                            for review in reviews {
                                println!("  - {} ({}/5)", review.reviewer, review.rating);
                                if let Some(ref title) = review.title {
                                    println!("    Title: {}", title);
                                }
                                println!("    Comment: {}", review.comment);
                                println!("    Date: {}", review.created_at);
                                if review.verified_purchase {
                                    println!("    ✓ Verified purchase");
                                }
                                if review.helpful_count > 0 {
                                    println!("    👍 {} helpful", review.helpful_count);
                                }
                                println!();
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("❌ Failed to get reviews: {}", e);
                        std::process::exit(1);
                    }
                }
            }
        },
    }

    Ok(())
}

/// Create a scenario package archive (ZIP format)
fn create_scenario_archive(
    package: &mockforge_scenarios::ScenarioPackage,
) -> anyhow::Result<(std::path::PathBuf, String, u64)> {
    use zip::write::FileOptions;
    use zip::ZipWriter;

    // Create temporary file for archive
    let temp_file = tempfile::NamedTempFile::new()?;
    let archive_path = temp_file.path().to_path_buf();
    drop(temp_file); // Close file so we can write to it

    // Create ZIP archive
    let file = fs::File::create(&archive_path)?;
    let mut zip = ZipWriter::new(file);
    let options = FileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated)
        .unix_permissions(0o755);

    // Add all files from package
    for file_path in &package.files {
        let full_path = package.root.join(file_path);

        if full_path.is_dir() {
            continue; // Skip directories, we'll add files individually
        }

        if !full_path.exists() {
            continue; // Skip missing files
        }

        // Get relative path for archive
        let archive_name = file_path.to_string_lossy().replace('\\', "/");

        // Read file contents
        let file_contents = fs::read(&full_path)?;

        // Add to ZIP
        zip.start_file(&archive_name, options)?;
        zip.write_all(&file_contents)?;
    }

    // Add all files from directories recursively
    add_directory_to_zip(&mut zip, &package.root, &package.root, options)?;

    // Finish writing the ZIP (consumes the writer)
    let _file = zip.finish()?;

    // Calculate checksum
    let archive_data = fs::read(&archive_path)?;
    let checksum = calculate_checksum(&archive_data);
    let size = archive_data.len() as u64;

    Ok((archive_path, checksum, size))
}

/// Recursively add directory contents to ZIP
fn add_directory_to_zip(
    zip: &mut zip::ZipWriter<fs::File>,
    base: &Path,
    dir: &Path,
    options: zip::write::FileOptions<()>,
) -> anyhow::Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        let file_name = entry.file_name();

        // Skip hidden files and common ignore patterns
        if file_name.to_string_lossy().starts_with('.') {
            continue;
        }

        if path.is_dir() {
            // Recursively add subdirectory
            add_directory_to_zip(zip, base, &path, options)?;
        } else {
            // Add file
            let relative_path = path
                .strip_prefix(base)
                .map_err(|e| anyhow::anyhow!("Failed to compute relative path: {}", e))?;
            let archive_name = relative_path.to_string_lossy().replace('\\', "/");

            let file_contents = fs::read(&path)?;
            zip.start_file(&archive_name, options)?;
            zip.write_all(&file_contents)?;
        }
    }

    Ok(())
}

/// Calculate SHA-256 checksum
fn calculate_checksum(data: &[u8]) -> String {
    use ring::digest::{Context, SHA256};
    let mut context = Context::new(&SHA256);
    context.update(data);
    let digest = context.finish();
    hex::encode(digest.as_ref())
}

/// Apply VBR entities from a scenario
///
/// This function converts scenario VBR entity definitions to actual VBR entities
/// and applies them. Since this requires both mockforge-scenarios and mockforge-vbr,
/// it's implemented in the CLI layer.
async fn apply_vbr_entities_from_scenario(
    entities: &[mockforge_scenarios::VbrEntityDefinition],
    scenario_path: &Path,
) -> anyhow::Result<usize> {
    use mockforge_vbr::schema::VbrSchemaDefinition;

    // For now, we'll create a simple VBR config and try to register entities
    // In a full implementation, this would integrate with an existing VBR engine
    // or create a new one based on workspace configuration

    let mut applied_count = 0;

    for entity_def in entities {
        // Try to convert JSON schema to VbrSchemaDefinition
        // The schema is stored as JSON, so we need to parse it
        match serde_json::from_value::<VbrSchemaDefinition>(entity_def.schema.clone()) {
            Ok(vbr_schema) => {
                // Create entity with state machine if provided
                // Convert state machine to the type expected by Entity::with_state_machine
                let _entity = if let Some(ref state_machine) = entity_def.state_machine {
                    // Convert from mockforge_scenarios::StateMachine to mockforge_core::intelligent_behavior::rules::StateMachine
                    use mockforge_core::intelligent_behavior::rules::StateMachine as CoreStateMachine;
                    let core_state_machine: CoreStateMachine =
                        serde_json::from_value(serde_json::to_value(state_machine)?)?;
                    Entity::with_state_machine(
                        entity_def.name.clone(),
                        vbr_schema,
                        core_state_machine,
                    )
                } else {
                    Entity::new(entity_def.name.clone(), vbr_schema)
                };

                // Note: In a full implementation, we would:
                // 1. Load or create a VBR engine from workspace config
                // 2. Register the entity with the engine
                // 3. Create database tables
                // 4. Seed data if seed_data_path is provided
                //
                // For now, we'll just validate that the entity can be created
                // The actual registration would happen when the server starts
                // or via explicit VBR commands

                println!("   - Entity '{}' ready for registration", entity_def.name);

                // If seed data path is provided, note it
                if let Some(ref seed_path) = entity_def.seed_data_path {
                    let full_seed_path = scenario_path.join(seed_path);
                    if full_seed_path.exists() {
                        println!("     Seed data: {}", seed_path);
                    } else {
                        println!("     ⚠️  Seed data file not found: {}", seed_path);
                    }
                }

                applied_count += 1;
            }
            Err(e) => {
                // If direct deserialization fails, try to convert from JSON Schema format
                // This is a simplified conversion - in production, you'd want a more robust converter
                println!(
                    "   ⚠️  Warning: Could not parse entity schema for '{}': {}",
                    entity_def.name, e
                );
                println!("     Entity definition will need manual conversion");
            }
        }
    }

    if applied_count > 0 {
        println!(
            "\n   💡 Note: VBR entities are prepared but need to be registered with a VBR engine."
        );
        println!(
            "   Use 'mockforge vbr create entity <name>' or start MockForge with VBR enabled."
        );
    }

    Ok(applied_count)
}

/// Merge MockAI configuration from a scenario into existing config.yaml
async fn merge_mockai_config_from_scenario(
    mockai_config_def: &mockforge_scenarios::MockAIConfigDefinition,
    scenario_path: &Path,
) -> anyhow::Result<()> {
    let current_dir = std::env::current_dir()
        .map_err(|e| anyhow::anyhow!("Failed to get current directory: {}", e))?;

    let config_path = current_dir.join("config.yaml");

    // Load existing config or create default
    let mut config = if config_path.exists() {
        load_config(&config_path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to load config.yaml: {}", e))?
    } else {
        ServerConfig::default()
    };

    // Merge MockAI config from scenario
    // The config is stored as JSON, so we need to convert it
    let mockai_config_json = &mockai_config_def.config;

    // Try to deserialize as MockAIConfig
    if let Ok(scenario_mockai) =
        serde_json::from_value::<mockforge_core::config::MockAIConfig>(mockai_config_json.clone())
    {
        // Merge: prefer scenario config over existing
        config.mockai = scenario_mockai;
    } else {
        // If direct deserialization fails, try manual merging
        // Extract key fields from JSON
        if let Some(enabled) = mockai_config_json.get("enabled").and_then(|v| v.as_bool()) {
            config.mockai.enabled = enabled;
        }

        // Try to merge intelligent_behavior if present
        if let Some(behavior_json) = mockai_config_json.get("intelligent_behavior") {
            if let Ok(behavior_config) = serde_json::from_value::<
                mockforge_core::intelligent_behavior::IntelligentBehaviorConfig,
            >(behavior_json.clone())
            {
                config.mockai.intelligent_behavior = behavior_config;
            }
        }

        // Merge other boolean flags
        if let Some(auto_learn) = mockai_config_json.get("auto_learn").and_then(|v| v.as_bool()) {
            config.mockai.auto_learn = auto_learn;
        }
        if let Some(mutation_detection) =
            mockai_config_json.get("mutation_detection").and_then(|v| v.as_bool())
        {
            config.mockai.mutation_detection = mutation_detection;
        }
        if let Some(ai_validation_errors) =
            mockai_config_json.get("ai_validation_errors").and_then(|v| v.as_bool())
        {
            config.mockai.ai_validation_errors = ai_validation_errors;
        }
        if let Some(intelligent_pagination) =
            mockai_config_json.get("intelligent_pagination").and_then(|v| v.as_bool())
        {
            config.mockai.intelligent_pagination = intelligent_pagination;
        }
    }

    // Load behavior rules if provided
    if let Some(ref rules_path) = mockai_config_def.behavior_rules_path {
        let full_rules_path = scenario_path.join(rules_path);
        if full_rules_path.exists() {
            println!("   Behavior rules file: {}", rules_path);
            // Note: Behavior rules would be loaded when MockAI is initialized
            // This is just informational for now
        }
    }

    // Load example pairs if provided
    if let Some(ref pairs_path) = mockai_config_def.example_pairs_path {
        let full_pairs_path = scenario_path.join(pairs_path);
        if full_pairs_path.exists() {
            println!("   Example pairs file: {}", pairs_path);
            // Note: Example pairs would be loaded when MockAI is initialized
            // This is just informational for now
        }
    }

    // Save merged config
    save_config(&config_path, &config)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to save config.yaml: {}", e))?;

    Ok(())
}

/// Reality Profile Pack commands
#[derive(Subcommand)]
pub enum RealityProfileCommands {
    /// Install a reality profile pack
    Install {
        /// Pack name or path to manifest file
        pack_name: String,
    },
    /// List installed reality profile packs
    List,
    /// Apply a reality profile pack to a workspace
    Apply {
        /// Pack name
        pack_name: String,
        /// Workspace ID (defaults to "default")
        #[arg(short, long, default_value = "default")]
        workspace: String,
    },
    /// Show information about a reality profile pack
    Info {
        /// Pack name
        pack_name: String,
    },
}

/// Behavioral Economics Rule commands
#[derive(Subcommand)]
pub enum BehaviorRuleCommands {
    /// Add a new behavior rule
    Add {
        /// Rule name
        #[arg(short, long)]
        name: String,
        /// Rule type (declarative or scriptable)
        #[arg(long, default_value = "declarative")]
        rule_type: String,
        /// Condition type (latency, load, pricing, fraud, segment, error-rate)
        #[arg(short, long)]
        condition: String,
        /// Condition threshold or value
        #[arg(long)]
        threshold: Option<String>,
        /// Endpoint pattern (e.g., "/api/users/*", "*" for all endpoints)
        #[arg(long, default_value = "*")]
        endpoint: String,
        /// Action type (modify-conversion-rate, decline-transaction, increase-churn, change-status, modify-latency, trigger-chaos)
        #[arg(short, long)]
        action: String,
        /// Action parameter (e.g., multiplier for conversion rate, status code for change-status)
        #[arg(long)]
        parameter: Option<String>,
        /// Priority (higher = evaluated first)
        #[arg(short, long, default_value = "100")]
        priority: u32,
        /// Script content (for scriptable rules)
        #[arg(long)]
        script: Option<String>,
        /// Script language (javascript, wasm)
        #[arg(long)]
        script_language: Option<String>,
    },
    /// List all behavior rules
    List,
    /// Remove a behavior rule
    Remove {
        /// Rule name
        name: String,
    },
    /// Enable behavioral economics engine
    Enable,
    /// Disable behavioral economics engine
    Disable,
    /// Show current status
    Status,
}

/// Drift Learning commands
#[derive(Subcommand)]
pub enum DriftLearningCommands {
    /// Enable drift learning
    Enable {
        /// Learning sensitivity (0.0 to 1.0)
        #[arg(short, long, default_value = "0.2")]
        sensitivity: f64,
        /// Minimum samples before learning starts
        #[arg(long, default_value = "10")]
        min_samples: usize,
        /// Learning mode (behavioral, statistical, hybrid)
        #[arg(short, long, default_value = "behavioral")]
        mode: String,
        /// Enable persona adaptation
        #[arg(long, default_value = "true")]
        persona_adaptation: bool,
        /// Enable traffic pattern mirroring
        #[arg(long, default_value = "true")]
        traffic_mirroring: bool,
    },
    /// Disable drift learning
    Disable,
    /// Show current drift learning status
    Status,
    /// Configure per-endpoint learning
    Endpoint {
        /// Endpoint pattern
        endpoint: String,
        /// Enable or disable learning for this endpoint
        #[arg(short, long)]
        enable: bool,
    },
    /// Configure per-persona learning
    Persona {
        /// Persona ID
        persona_id: String,
        /// Enable or disable learning for this persona
        #[arg(short, long)]
        enable: bool,
    },
}

/// Handle reality profile pack commands
pub async fn handle_reality_profile_command(command: RealityProfileCommands) -> anyhow::Result<()> {
    use mockforge_scenarios::RealityProfilePackInstaller;

    let installer = RealityProfilePackInstaller::new()?;
    installer.init()?;

    match command {
        RealityProfileCommands::Install { pack_name } => {
            println!("📦 Installing reality profile pack: {}", pack_name);

            // Check if it's a pre-built pack or a path
            let manifest = if pack_name == "ecommerce-peak-season" {
                Some(mockforge_scenarios::create_ecommerce_peak_season_pack())
            } else if pack_name == "fintech-fraud" {
                Some(mockforge_scenarios::create_fintech_fraud_pack())
            } else if pack_name == "healthcare-hl7" {
                Some(mockforge_scenarios::create_healthcare_hl7_pack())
            } else if pack_name == "iot-fleet-chaos" {
                Some(mockforge_scenarios::create_iot_fleet_chaos_pack())
            } else {
                // Try as a file path
                let path = Path::new(&pack_name);
                if path.exists() {
                    Some(mockforge_scenarios::RealityProfilePackManifest::from_file(path)?)
                } else {
                    None
                }
            };

            if let Some(manifest) = manifest {
                // Save manifest to temp file and install
                let temp_dir = std::env::temp_dir();
                let temp_manifest = temp_dir.join(format!("{}.yaml", manifest.name));
                manifest.to_file(&temp_manifest)?;
                installer.install_from_manifest(&temp_manifest)?;
                println!("✅ Reality profile pack installed: {}", manifest.name);
            } else {
                anyhow::bail!("Pack not found: {}", pack_name);
            }
        }
        RealityProfileCommands::List => {
            let packs = installer.list_installed()?;
            if packs.is_empty() {
                println!("No reality profile packs installed");
            } else {
                println!("Installed reality profile packs:");
                for pack in packs {
                    println!(
                        "  - {} v{} ({})",
                        pack.manifest.name, pack.manifest.version, pack.manifest.domain
                    );
                }
            }
        }
        RealityProfileCommands::Apply {
            pack_name,
            workspace,
        } => {
            println!("🎯 Applying reality profile pack: {} to workspace: {}", pack_name, workspace);

            let pack_info = installer.get_pack(&pack_name)?;
            if let Some(pack_info) = pack_info {
                let result = installer
                    .apply_reality_profile_pack(&pack_info.manifest, Some(&workspace))
                    .await?;
                println!("✅ Reality profile pack applied successfully!");
                println!("   Personas: {}", result.personas_configured);
                println!("   Chaos Rules: {}", result.chaos_rules_applied);
                println!("   Latency Curves: {}", result.latency_curves_applied);
                println!("   Error Distributions: {}", result.error_distributions_applied);
                println!("   Data Mutations: {}", result.data_mutation_behaviors_applied);
                println!("   Protocol Behaviors: {}", result.protocol_behaviors_applied);
            } else {
                anyhow::bail!("Pack not found: {}", pack_name);
            }
        }
        RealityProfileCommands::Info { pack_name } => {
            let pack_info = installer.get_pack(&pack_name)?;
            if let Some(pack_info) = pack_info {
                println!("Reality Profile Pack: {}", pack_info.manifest.name);
                println!("Version: {}", pack_info.manifest.version);
                println!("Domain: {}", pack_info.manifest.domain);
                println!("Description: {}", pack_info.manifest.description);
                println!("Personas: {}", pack_info.manifest.personas.len());
                println!("Chaos Rules: {}", pack_info.manifest.chaos_rules.len());
                println!("Latency Curves: {}", pack_info.manifest.latency_curves.len());
                println!("Error Distributions: {}", pack_info.manifest.error_distributions.len());
            } else {
                anyhow::bail!("Pack not found: {}", pack_name);
            }
        }
    }

    Ok(())
}

/// Helper function to get config file path
fn get_config_path() -> std::path::PathBuf {
    std::env::current_dir()
        .ok()
        .map(|d| {
            let yaml_path = d.join("mockforge.yaml");
            if yaml_path.exists() {
                yaml_path
            } else {
                let yml_path = d.join("mockforge.yml");
                if yml_path.exists() {
                    yml_path
                } else {
                    d.join("mockforge.yaml") // Default to .yaml for new files
                }
            }
        })
        .unwrap_or_else(|| std::path::PathBuf::from("mockforge.yaml"))
}

/// Helper function to load config with fallback to default
async fn load_config_with_fallback() -> anyhow::Result<(ServerConfig, std::path::PathBuf)> {
    let config_path = get_config_path();
    let config = if config_path.exists() {
        load_config(&config_path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to load config: {}", e))?
    } else {
        ServerConfig::default()
    };
    Ok((config, config_path))
}

/// Helper function to save behavior rule to config
async fn save_behavior_rule_to_config(rule: BehaviorRule) -> anyhow::Result<()> {
    let (mut config, config_path) = load_config_with_fallback().await?;

    // Check if rule already exists and remove it
    config.behavioral_economics.rules.retain(|r| r.name != rule.name);

    // Add the new rule
    config.behavioral_economics.rules.push(rule);

    // Save config
    save_config(&config_path, &config)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to save config: {}", e))?;

    Ok(())
}

/// Helper function to remove behavior rule from config
async fn remove_behavior_rule_from_config(rule_name: &str) -> anyhow::Result<bool> {
    let (mut config, config_path) = load_config_with_fallback().await?;

    let initial_len = config.behavioral_economics.rules.len();
    config.behavioral_economics.rules.retain(|r| r.name != rule_name);
    let removed = config.behavioral_economics.rules.len() < initial_len;

    if removed {
        save_config(&config_path, &config)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to save config: {}", e))?;
    }

    Ok(removed)
}

/// Helper function to update behavioral economics engine enabled status
async fn update_behavioral_economics_enabled(enabled: bool) -> anyhow::Result<()> {
    let (mut config, config_path) = load_config_with_fallback().await?;

    config.behavioral_economics.enabled = enabled;

    save_config(&config_path, &config)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to save config: {}", e))?;

    Ok(())
}

/// Handle behavioral economics rule commands
pub async fn handle_behavior_rule_command(command: BehaviorRuleCommands) -> anyhow::Result<()> {
    use mockforge_core::behavioral_economics::{BehaviorAction, BehaviorCondition, BehaviorRule};

    match command {
        BehaviorRuleCommands::Add {
            name,
            rule_type,
            condition,
            threshold,
            endpoint,
            action,
            parameter,
            priority,
            script,
            script_language,
        } => {
            println!("➕ Adding behavior rule: {}", name);
            println!("   Endpoint: {}", endpoint);

            // Parse condition
            let behavior_condition = match condition.as_str() {
                "latency" => {
                    let threshold_ms = threshold.and_then(|t| t.parse::<u64>().ok()).unwrap_or(400);
                    BehaviorCondition::LatencyThreshold {
                        endpoint: endpoint.clone(),
                        threshold_ms,
                    }
                }
                "load" => {
                    let threshold_rps =
                        threshold.and_then(|t| t.parse::<f64>().ok()).unwrap_or(100.0);
                    BehaviorCondition::LoadPressure { threshold_rps }
                }
                "error-rate" => {
                    let error_threshold =
                        threshold.and_then(|t| t.parse::<f64>().ok()).unwrap_or(0.1);
                    BehaviorCondition::ErrorRate {
                        endpoint: endpoint.clone(),
                        threshold: error_threshold,
                    }
                }
                "always" => BehaviorCondition::Always,
                _ => anyhow::bail!("Unknown condition type: {}", condition),
            };

            // Parse action
            let behavior_action = match action.as_str() {
                "modify-conversion-rate" => {
                    let multiplier = parameter.and_then(|p| p.parse::<f64>().ok()).unwrap_or(0.8);
                    BehaviorAction::ModifyConversionRate { multiplier }
                }
                "decline-transaction" => {
                    let reason = parameter.unwrap_or_else(|| "behavioral_rule".to_string());
                    BehaviorAction::DeclineTransaction { reason }
                }
                "increase-churn" => {
                    let factor = parameter.and_then(|p| p.parse::<f64>().ok()).unwrap_or(1.5);
                    BehaviorAction::IncreaseChurnProbability { factor }
                }
                "change-status" => {
                    let status = parameter.and_then(|p| p.parse::<u16>().ok()).unwrap_or(500);
                    BehaviorAction::ChangeResponseStatus { status }
                }
                "noop" => BehaviorAction::NoOp,
                _ => anyhow::bail!("Unknown action type: {}", action),
            };

            // Create rule
            let rule = if rule_type == "scriptable" {
                let (Some(script_val), Some(lang_val)) = (script, script_language) else {
                    anyhow::bail!("Scriptable rules require --script and --script-language");
                };
                BehaviorRule::scriptable(
                    name,
                    behavior_condition,
                    behavior_action,
                    priority,
                    script_val,
                    lang_val,
                )
            } else {
                BehaviorRule::declarative(name, behavior_condition, behavior_action, priority)
            };

            // Save to config
            save_behavior_rule_to_config(rule.clone()).await?;

            println!("✅ Behavior rule added: {}", rule.name);
            println!("   Type: {:?}", rule.rule_type);
            println!("   Priority: {}", rule.priority);
        }
        BehaviorRuleCommands::List => {
            println!("Behavior rules:");
            let (config, _) = load_config_with_fallback().await?;

            if config.behavioral_economics.rules.is_empty() {
                println!("  No behavior rules configured");
            } else {
                for rule in &config.behavioral_economics.rules {
                    println!(
                        "  - {} ({:?}, priority: {})",
                        rule.name, rule.rule_type, rule.priority
                    );
                    match &rule.condition {
                        BehaviorCondition::LatencyThreshold {
                            endpoint,
                            threshold_ms,
                        } => {
                            println!("    Condition: latency > {}ms on {}", threshold_ms, endpoint);
                        }
                        BehaviorCondition::LoadPressure { threshold_rps } => {
                            println!("    Condition: load > {} req/s", threshold_rps);
                        }
                        BehaviorCondition::Always => {
                            println!("    Condition: always");
                        }
                        _ => {
                            println!("    Condition: {:?}", rule.condition);
                        }
                    }
                    println!("    Action: {:?}", rule.action);
                }
            }
        }
        BehaviorRuleCommands::Remove { name } => {
            println!("🗑️  Removing behavior rule: {}", name);
            match remove_behavior_rule_from_config(&name).await {
                Ok(true) => {
                    println!("✅ Rule removed");
                }
                Ok(false) => {
                    println!("⚠️  Rule '{}' not found", name);
                }
                Err(e) => {
                    anyhow::bail!("Failed to remove rule: {}", e);
                }
            }
        }
        BehaviorRuleCommands::Enable => {
            println!("✅ Behavioral economics engine enabled");
            update_behavioral_economics_enabled(true).await?;
        }
        BehaviorRuleCommands::Disable => {
            println!("❌ Behavioral economics engine disabled");
            update_behavioral_economics_enabled(false).await?;
        }
        BehaviorRuleCommands::Status => {
            println!("Behavioral Economics Engine Status:");
            let (config, _) = load_config_with_fallback().await?;

            println!("  Enabled: {}", config.behavioral_economics.enabled);
            println!("  Rules: {}", config.behavioral_economics.rules.len());
            println!("  Global Sensitivity: {}", config.behavioral_economics.global_sensitivity);
            println!(
                "  Evaluation Interval: {}ms",
                config.behavioral_economics.evaluation_interval_ms
            );

            if !config.behavioral_economics.rules.is_empty() {
                println!("\n  Active Rules:");
                for rule in &config.behavioral_economics.rules {
                    println!("    - {} (priority: {})", rule.name, rule.priority);
                }
            }
        }
    }

    Ok(())
}

/// Helper function to convert LearningMode to DriftLearningMode
fn learning_mode_to_drift_mode(
    mode: &str,
) -> anyhow::Result<mockforge_core::config::DriftLearningMode> {
    match mode {
        "behavioral" => Ok(mockforge_core::config::DriftLearningMode::Behavioral),
        "statistical" => Ok(mockforge_core::config::DriftLearningMode::Statistical),
        "hybrid" => Ok(mockforge_core::config::DriftLearningMode::Hybrid),
        _ => anyhow::bail!("Unknown learning mode: {}", mode),
    }
}

/// Helper function to update drift learning config
async fn update_drift_learning_config<F>(updater: F) -> anyhow::Result<()>
where
    F: FnOnce(&mut mockforge_core::config::DriftLearningConfig),
{
    let (mut config, config_path) = load_config_with_fallback().await?;

    updater(&mut config.drift_learning);

    save_config(&config_path, &config)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to save config: {}", e))?;

    Ok(())
}

/// Handle drift learning commands
pub async fn handle_drift_learning_command(command: DriftLearningCommands) -> anyhow::Result<()> {
    match command {
        DriftLearningCommands::Enable {
            sensitivity,
            min_samples,
            mode,
            persona_adaptation,
            traffic_mirroring,
        } => {
            println!("🧠 Enabling drift learning");
            println!("   Sensitivity: {}", sensitivity);
            println!("   Min Samples: {}", min_samples);
            println!("   Mode: {}", mode);
            println!("   Persona Adaptation: {}", persona_adaptation);
            println!("   Traffic Mirroring: {}", traffic_mirroring);

            let drift_mode = learning_mode_to_drift_mode(&mode)?;

            update_drift_learning_config(|config| {
                config.enabled = true;
                config.mode = drift_mode;
                config.sensitivity = sensitivity;
                config.min_samples = min_samples as u64;
                config.persona_adaptation = persona_adaptation;
                // Note: traffic_mirroring is not in DriftLearningConfig, may need to be added
            })
            .await?;

            println!("✅ Drift learning enabled");
        }
        DriftLearningCommands::Disable => {
            println!("❌ Disabling drift learning");
            update_drift_learning_config(|config| {
                config.enabled = false;
            })
            .await?;
            println!("✅ Drift learning disabled");
        }
        DriftLearningCommands::Status => {
            println!("Drift Learning Status:");
            let (config, _) = load_config_with_fallback().await?;

            println!("  Enabled: {}", config.drift_learning.enabled);
            println!("  Mode: {:?}", config.drift_learning.mode);
            println!("  Sensitivity: {}", config.drift_learning.sensitivity);
            println!("  Decay: {}", config.drift_learning.decay);
            println!("  Min Samples: {}", config.drift_learning.min_samples);
            println!("  Persona Adaptation: {}", config.drift_learning.persona_adaptation);
            println!(
                "  Persona Learning Configs: {}",
                config.drift_learning.persona_learning.len()
            );
            println!(
                "  Endpoint Learning Configs: {}",
                config.drift_learning.endpoint_learning.len()
            );

            if !config.drift_learning.persona_learning.is_empty() {
                println!("\n  Persona Learning:");
                for (persona_id, enabled) in &config.drift_learning.persona_learning {
                    println!(
                        "    - {}: {}",
                        persona_id,
                        if *enabled { "enabled" } else { "disabled" }
                    );
                }
            }

            if !config.drift_learning.endpoint_learning.is_empty() {
                println!("\n  Endpoint Learning:");
                for (endpoint, enabled) in &config.drift_learning.endpoint_learning {
                    println!(
                        "    - {}: {}",
                        endpoint,
                        if *enabled { "enabled" } else { "disabled" }
                    );
                }
            }
        }
        DriftLearningCommands::Endpoint { endpoint, enable } => {
            println!(
                "{} learning for endpoint: {}",
                if enable { "Enabling" } else { "Disabling" },
                endpoint
            );
            update_drift_learning_config(|config| {
                config.endpoint_learning.insert(endpoint, enable);
            })
            .await?;
            println!("✅ Endpoint learning configuration updated");
        }
        DriftLearningCommands::Persona { persona_id, enable } => {
            println!(
                "{} learning for persona: {}",
                if enable { "Enabling" } else { "Disabling" },
                persona_id
            );
            update_drift_learning_config(|config| {
                config.persona_learning.insert(persona_id, enable);
            })
            .await?;
            println!("✅ Persona learning configuration updated");
        }
    }

    Ok(())
}

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

    // Tests for calculate_checksum
    #[test]
    fn test_calculate_checksum_empty() {
        let data = b"";
        let checksum = calculate_checksum(data);
        // SHA256 of empty string
        assert_eq!(checksum, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
    }

    #[test]
    fn test_calculate_checksum_hello_world() {
        let data = b"hello world";
        let checksum = calculate_checksum(data);
        // Known SHA256 of "hello world"
        assert_eq!(checksum, "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9");
    }

    #[test]
    fn test_calculate_checksum_different_data() {
        let data1 = b"test1";
        let data2 = b"test2";
        let checksum1 = calculate_checksum(data1);
        let checksum2 = calculate_checksum(data2);
        assert_ne!(checksum1, checksum2);
    }

    #[test]
    fn test_calculate_checksum_same_data() {
        let data = b"consistent data";
        let checksum1 = calculate_checksum(data);
        let checksum2 = calculate_checksum(data);
        assert_eq!(checksum1, checksum2);
    }

    #[test]
    fn test_calculate_checksum_binary_data() {
        let data = &[0u8, 1, 2, 3, 255];
        let checksum = calculate_checksum(data);
        assert_eq!(checksum.len(), 64); // SHA256 produces 64 hex characters
    }

    // Tests for get_config_path
    #[test]
    fn test_get_config_path_default() {
        let path = get_config_path();
        let path_str = path.to_string_lossy();
        assert!(path_str.ends_with("mockforge.yaml") || path_str.ends_with("mockforge.yml"));
    }

    #[test]
    fn test_get_config_path_returns_pathbuf() {
        let path = get_config_path();
        assert!(path.is_absolute() || path.is_relative());
    }

    // Tests for learning_mode_to_drift_mode
    #[test]
    fn test_learning_mode_to_drift_mode_behavioral() {
        let result = learning_mode_to_drift_mode("behavioral");
        assert!(result.is_ok());
        match result.unwrap() {
            mockforge_core::config::DriftLearningMode::Behavioral => (),
            _ => panic!("Expected Behavioral mode"),
        }
    }

    #[test]
    fn test_learning_mode_to_drift_mode_statistical() {
        let result = learning_mode_to_drift_mode("statistical");
        assert!(result.is_ok());
        match result.unwrap() {
            mockforge_core::config::DriftLearningMode::Statistical => (),
            _ => panic!("Expected Statistical mode"),
        }
    }

    #[test]
    fn test_learning_mode_to_drift_mode_hybrid() {
        let result = learning_mode_to_drift_mode("hybrid");
        assert!(result.is_ok());
        match result.unwrap() {
            mockforge_core::config::DriftLearningMode::Hybrid => (),
            _ => panic!("Expected Hybrid mode"),
        }
    }

    #[test]
    fn test_learning_mode_to_drift_mode_invalid() {
        let result = learning_mode_to_drift_mode("invalid_mode");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unknown learning mode"));
    }

    #[test]
    fn test_learning_mode_to_drift_mode_case_sensitive() {
        // Mode names should be case-sensitive
        let result = learning_mode_to_drift_mode("Behavioral");
        assert!(result.is_err());
    }

    #[test]
    fn test_learning_mode_to_drift_mode_empty() {
        let result = learning_mode_to_drift_mode("");
        assert!(result.is_err());
    }

    // Tests for ScenarioCommands enum variants
    #[test]
    fn test_scenario_commands_install_variant() {
        // Test that the enum has the Install variant with expected fields
        let _cmd = ScenarioCommands::Install {
            source: "test-source".to_string(),
            force: false,
            skip_validation: false,
            checksum: None,
        };
    }

    #[test]
    fn test_scenario_commands_uninstall_variant() {
        let _cmd = ScenarioCommands::Uninstall {
            name: "test-scenario".to_string(),
            version: Some("1.0.0".to_string()),
        };
    }

    #[test]
    fn test_scenario_commands_list_variant() {
        let _cmd = ScenarioCommands::List { detailed: true };
    }

    #[test]
    fn test_scenario_commands_info_variant() {
        let _cmd = ScenarioCommands::Info {
            name: "test".to_string(),
            version: Some("1.0.0".to_string()),
        };
    }

    #[test]
    fn test_scenario_commands_preview_variant() {
        let _cmd = ScenarioCommands::Preview {
            source: "https://example.com/scenario".to_string(),
        };
    }

    #[test]
    fn test_scenario_commands_use_variant() {
        let _cmd = ScenarioCommands::Use {
            name: "test".to_string(),
            version: None,
            merge_strategy: "prefer-existing".to_string(),
            auto_align: false,
        };
    }

    #[test]
    fn test_scenario_commands_search_variant() {
        let _cmd = ScenarioCommands::Search {
            query: "ecommerce".to_string(),
            category: Some("retail".to_string()),
            limit: 10,
        };
    }

    #[test]
    fn test_scenario_commands_publish_variant() {
        let _cmd = ScenarioCommands::Publish {
            path: "./scenario".to_string(),
            registry: Some("https://registry.example.com".to_string()),
        };
    }

    #[test]
    fn test_scenario_commands_update_variant() {
        let _cmd = ScenarioCommands::Update {
            name: Some("test".to_string()),
            all: false,
        };
    }

    // Tests for PackCommands enum variants
    #[test]
    fn test_pack_commands_list_variant() {
        let _cmd = PackCommands::List;
    }

    #[test]
    fn test_pack_commands_install_variant() {
        let _cmd = PackCommands::Install {
            manifest: "pack.yaml".to_string(),
        };
    }

    #[test]
    fn test_pack_commands_info_variant() {
        let _cmd = PackCommands::Info {
            name: "test-pack".to_string(),
        };
    }

    // Tests for ReviewCommands enum variants
    #[test]
    fn test_review_commands_submit_variant() {
        let _cmd = ReviewCommands::Submit {
            scenario_name: "test".to_string(),
            scenario_version: Some("1.0.0".to_string()),
            rating: 5,
            title: Some("Great!".to_string()),
            comment: "Excellent scenario".to_string(),
            reviewer: "john".to_string(),
            reviewer_email: Some("john@example.com".to_string()),
            verified: true,
        };
    }

    #[test]
    fn test_review_commands_list_variant() {
        let _cmd = ReviewCommands::List {
            scenario_name: "test".to_string(),
            page: Some(0),
            per_page: Some(20),
        };
    }

    // Tests for BehaviorRuleCommands enum variants
    #[test]
    fn test_behavior_rule_commands_add_variant() {
        let _cmd = BehaviorRuleCommands::Add {
            name: "test-rule".to_string(),
            rule_type: "declarative".to_string(),
            condition: "latency".to_string(),
            threshold: Some("400".to_string()),
            endpoint: "/api/*".to_string(),
            action: "modify-conversion-rate".to_string(),
            parameter: Some("0.8".to_string()),
            priority: 100,
            script: None,
            script_language: None,
        };
    }

    #[test]
    fn test_behavior_rule_commands_list_variant() {
        let _cmd = BehaviorRuleCommands::List;
    }

    #[test]
    fn test_behavior_rule_commands_remove_variant() {
        let _cmd = BehaviorRuleCommands::Remove {
            name: "test-rule".to_string(),
        };
    }

    #[test]
    fn test_behavior_rule_commands_enable_disable_status() {
        let _enable = BehaviorRuleCommands::Enable;
        let _disable = BehaviorRuleCommands::Disable;
        let _status = BehaviorRuleCommands::Status;
    }

    // Tests for DriftLearningCommands enum variants
    #[test]
    fn test_drift_learning_commands_enable_variant() {
        let _cmd = DriftLearningCommands::Enable {
            sensitivity: 0.2,
            min_samples: 10,
            mode: "behavioral".to_string(),
            persona_adaptation: true,
            traffic_mirroring: true,
        };
    }

    #[test]
    fn test_drift_learning_commands_disable_variant() {
        let _cmd = DriftLearningCommands::Disable;
    }

    #[test]
    fn test_drift_learning_commands_status_variant() {
        let _cmd = DriftLearningCommands::Status;
    }

    #[test]
    fn test_drift_learning_commands_endpoint_variant() {
        let _cmd = DriftLearningCommands::Endpoint {
            endpoint: "/api/users".to_string(),
            enable: true,
        };
    }

    #[test]
    fn test_drift_learning_commands_persona_variant() {
        let _cmd = DriftLearningCommands::Persona {
            persona_id: "persona-1".to_string(),
            enable: false,
        };
    }

    // Tests for RealityProfileCommands enum variants
    #[test]
    fn test_reality_profile_commands_install_variant() {
        let _cmd = RealityProfileCommands::Install {
            pack_name: "ecommerce-peak-season".to_string(),
        };
    }

    #[test]
    fn test_reality_profile_commands_list_variant() {
        let _cmd = RealityProfileCommands::List;
    }

    #[test]
    fn test_reality_profile_commands_apply_variant() {
        let _cmd = RealityProfileCommands::Apply {
            pack_name: "test-pack".to_string(),
            workspace: "default".to_string(),
        };
    }

    #[test]
    fn test_reality_profile_commands_info_variant() {
        let _cmd = RealityProfileCommands::Info {
            pack_name: "test-pack".to_string(),
        };
    }

    // Tests for StudioPackCommands enum variants
    #[test]
    fn test_studio_pack_commands_install_variant() {
        let _cmd = StudioPackCommands::Install {
            pack_name: "fintech-fraud-lab".to_string(),
            workspace: "default".to_string(),
        };
    }

    #[test]
    fn test_studio_pack_commands_list_variant() {
        let _cmd = StudioPackCommands::List;
    }

    #[test]
    fn test_studio_pack_commands_create_variant() {
        let _cmd = StudioPackCommands::Create {
            name: "my-pack".to_string(),
            output: Some("./output.yaml".to_string()),
        };
    }
}