mockforge-core 0.3.114

Shared logic for MockForge - routing, validation, latency, proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
//! Persistence layer for workspace configurations
//!
//! This module handles saving and loading workspace configurations to/from disk,
//! enabling persistent storage of workspace hierarchies and configurations.

use crate::config::AuthConfig as ConfigAuthConfig;
use crate::encryption::{utils, AutoEncryptionProcessor, WorkspaceKeyManager};
use crate::workspace::{EntityId, Folder, MockRequest, Workspace, WorkspaceRegistry};
use crate::{Error, Result};
use chrono::{DateTime, Utc};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;

// Pre-compiled regex patterns for sensitive data detection
static CREDIT_CARD_PATTERN: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b")
        .expect("CREDIT_CARD_PATTERN regex is valid")
});

static SSN_PATTERN: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b").expect("SSN_PATTERN regex is valid")
});

/// Workspace persistence manager
#[derive(Debug)]
pub struct WorkspacePersistence {
    /// Base directory for workspace storage
    base_dir: PathBuf,
}

/// Serializable workspace registry for persistence
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SerializableWorkspaceRegistry {
    workspaces: Vec<Workspace>,
    active_workspace: Option<EntityId>,
}

/// Sync state for tracking incremental syncs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncState {
    /// Last time a sync operation was performed
    pub last_sync_timestamp: DateTime<Utc>,
}

/// Sync strategy for workspace mirroring
#[derive(Debug, Clone, PartialEq)]
pub enum SyncStrategy {
    /// Sync all workspaces completely
    Full,
    /// Sync only changed workspaces (based on modification time)
    Incremental,
    /// Sync only specified workspace IDs
    Selective(Vec<String>),
}

/// Directory structure for synced workspaces
#[derive(Debug, Clone, PartialEq)]
pub enum DirectoryStructure {
    /// All workspaces in a flat structure: workspace-id.yaml
    Flat,
    /// Nested by workspace: workspaces/{name}/workspace.yaml + requests/
    Nested,
    /// Grouped by type: requests/, responses/, metadata/
    Grouped,
}

/// Result of a workspace sync operation
#[derive(Debug, Clone)]
pub struct SyncResult {
    /// Number of workspaces synced
    pub synced_workspaces: usize,
    /// Number of requests synced
    pub synced_requests: usize,
    /// Number of files created/updated
    pub files_created: usize,
    /// Target directory used
    pub target_dir: PathBuf,
}

/// Result of an encrypted workspace export
#[derive(Debug, Clone)]
pub struct EncryptedExportResult {
    /// Path to the encrypted export file
    pub output_path: PathBuf,
    /// Backup key for importing on other devices
    pub backup_key: String,
    /// When the export was created
    pub exported_at: DateTime<Utc>,
    /// Name of the exported workspace
    pub workspace_name: String,
    /// Whether encryption was successfully applied
    pub encryption_enabled: bool,
}

/// Result of an encrypted workspace import
#[derive(Debug, Clone)]
pub struct EncryptedImportResult {
    /// ID of the imported workspace
    pub workspace_id: String,
    /// Name of the imported workspace
    pub workspace_name: String,
    /// When the import was completed
    pub imported_at: DateTime<Utc>,
    /// Number of requests imported
    pub request_count: usize,
    /// Whether encryption was successfully restored
    pub encryption_restored: bool,
}

/// Result of a security check for sensitive data
#[derive(Debug, Clone)]
pub struct SecurityCheckResult {
    /// Workspace ID that was checked
    pub workspace_id: String,
    /// Workspace name that was checked
    pub workspace_name: String,
    /// Security warnings found
    pub warnings: Vec<SecurityWarning>,
    /// Security errors found (critical issues)
    pub errors: Vec<SecurityWarning>,
    /// Whether the workspace is considered secure
    pub is_secure: bool,
    /// Recommended actions to improve security
    pub recommended_actions: Vec<String>,
}

/// Security warning or error
#[derive(Debug, Clone)]
pub struct SecurityWarning {
    /// Type of field that contains sensitive data
    pub field_type: String,
    /// Name of the field
    pub field_name: String,
    /// Location where the sensitive data was found
    pub location: String,
    /// Severity of the issue
    pub severity: SecuritySeverity,
    /// Human-readable message
    pub message: String,
    /// Suggestion for fixing the issue
    pub suggestion: String,
}

/// Severity levels for security issues
#[derive(Debug, Clone, PartialEq)]
pub enum SecuritySeverity {
    /// Low risk - informational
    Low,
    /// Medium risk - should be reviewed
    Medium,
    /// High risk - requires attention
    High,
    /// Critical risk - blocks operations
    Critical,
}

/// Git-friendly workspace export format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceExport {
    /// Workspace metadata
    pub metadata: WorkspaceMetadata,
    /// Workspace configuration
    pub config: WorkspaceConfig,
    /// All requests organized by folder structure
    pub requests: HashMap<String, ExportedRequest>,
}

/// Metadata for exported workspace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceMetadata {
    /// Original workspace ID
    pub id: String,
    /// Workspace name
    pub name: String,
    /// Workspace description
    pub description: Option<String>,
    /// Export timestamp
    pub exported_at: DateTime<Utc>,
    /// Total number of requests
    pub request_count: usize,
    /// Total number of folders
    pub folder_count: usize,
}

/// Simplified workspace configuration for export
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceConfig {
    /// Authentication configuration
    pub auth: Option<AuthConfig>,
    /// Base URL for requests
    pub base_url: Option<String>,
    /// Environment variables
    pub variables: HashMap<String, String>,
    /// Reality level for this workspace (1-5)
    /// Controls the realism of mock behavior (chaos, latency, MockAI)
    #[serde(default)]
    pub reality_level: Option<crate::RealityLevel>,
    /// AI mode for this workspace
    /// Controls how AI-generated artifacts are used at runtime
    #[serde(default)]
    pub ai_mode: Option<crate::ai_studio::config::AiMode>,
}

/// Authentication configuration for export
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    /// Authentication type
    pub auth_type: String,
    /// Authentication parameters
    pub params: HashMap<String, String>,
}

impl AuthConfig {
    /// Convert from config AuthConfig to export AuthConfig
    pub fn from_config_auth(config_auth: &ConfigAuthConfig) -> Option<Self> {
        if let Some(jwt) = &config_auth.jwt {
            let mut params = HashMap::new();
            if let Some(secret) = &jwt.secret {
                params.insert("secret".to_string(), secret.clone());
            }
            if let Some(rsa_public_key) = &jwt.rsa_public_key {
                params.insert("rsa_public_key".to_string(), rsa_public_key.clone());
            }
            if let Some(ecdsa_public_key) = &jwt.ecdsa_public_key {
                params.insert("ecdsa_public_key".to_string(), ecdsa_public_key.clone());
            }
            if let Some(issuer) = &jwt.issuer {
                params.insert("issuer".to_string(), issuer.clone());
            }
            if let Some(audience) = &jwt.audience {
                params.insert("audience".to_string(), audience.clone());
            }
            if !jwt.algorithms.is_empty() {
                params.insert("algorithms".to_string(), jwt.algorithms.join(","));
            }
            Some(AuthConfig {
                auth_type: "jwt".to_string(),
                params,
            })
        } else if let Some(oauth2) = &config_auth.oauth2 {
            let mut params = HashMap::new();
            params.insert("client_id".to_string(), oauth2.client_id.clone());
            params.insert("client_secret".to_string(), oauth2.client_secret.clone());
            params.insert("introspection_url".to_string(), oauth2.introspection_url.clone());
            if let Some(auth_url) = &oauth2.auth_url {
                params.insert("auth_url".to_string(), auth_url.clone());
            }
            if let Some(token_url) = &oauth2.token_url {
                params.insert("token_url".to_string(), token_url.clone());
            }
            if let Some(token_type_hint) = &oauth2.token_type_hint {
                params.insert("token_type_hint".to_string(), token_type_hint.clone());
            }
            Some(AuthConfig {
                auth_type: "oauth2".to_string(),
                params,
            })
        } else if let Some(basic_auth) = &config_auth.basic_auth {
            let mut params = HashMap::new();
            for (user, pass) in &basic_auth.credentials {
                params.insert(user.clone(), pass.clone());
            }
            Some(AuthConfig {
                auth_type: "basic".to_string(),
                params,
            })
        } else if let Some(api_key) = &config_auth.api_key {
            let mut params = HashMap::new();
            params.insert("header_name".to_string(), api_key.header_name.clone());
            if let Some(query_name) = &api_key.query_name {
                params.insert("query_name".to_string(), query_name.clone());
            }
            if !api_key.keys.is_empty() {
                params.insert("keys".to_string(), api_key.keys.join(","));
            }
            Some(AuthConfig {
                auth_type: "api_key".to_string(),
                params,
            })
        } else {
            None
        }
    }
}

/// Exported request format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedRequest {
    /// Request ID
    pub id: String,
    /// Request name
    pub name: String,
    /// HTTP method
    pub method: String,
    /// Request path
    pub path: String,
    /// Folder path (for organization)
    pub folder_path: String,
    /// Request headers
    pub headers: HashMap<String, String>,
    /// Query parameters
    pub query_params: HashMap<String, String>,
    /// Request body
    pub body: Option<String>,
    /// Response status code
    pub response_status: Option<u16>,
    /// Response body
    pub response_body: Option<String>,
    /// Response headers
    pub response_headers: HashMap<String, String>,
    /// Response delay (ms)
    pub delay: Option<u64>,
}

impl WorkspacePersistence {
    /// Create a new persistence manager
    pub fn new<P: AsRef<Path>>(base_dir: P) -> Self {
        Self {
            base_dir: base_dir.as_ref().to_path_buf(),
        }
    }

    /// Get the workspace directory path
    pub fn workspace_dir(&self) -> &Path {
        &self.base_dir
    }

    /// Get the path for a specific workspace file
    pub fn workspace_file_path(&self, workspace_id: &str) -> PathBuf {
        self.base_dir.join(format!("{}.yaml", workspace_id))
    }

    /// Get the registry metadata file path
    pub fn registry_file_path(&self) -> PathBuf {
        self.base_dir.join("registry.yaml")
    }

    /// Get the sync state file path
    pub fn sync_state_file_path(&self) -> PathBuf {
        self.base_dir.join("sync_state.yaml")
    }

    /// Ensure the workspace directory exists
    pub async fn ensure_workspace_dir(&self) -> Result<()> {
        if !self.base_dir.exists() {
            fs::create_dir_all(&self.base_dir).await.map_err(|e| {
                Error::io_with_context("creating workspace directory", e.to_string())
            })?;
        }
        Ok(())
    }

    /// Save a workspace to disk
    pub async fn save_workspace(&self, workspace: &Workspace) -> Result<()> {
        self.ensure_workspace_dir().await?;

        let file_path = self.workspace_file_path(&workspace.id);
        let content = serde_yaml::to_string(workspace)
            .map_err(|e| Error::config(format!("Failed to serialize workspace: {}", e)))?;

        fs::write(&file_path, content)
            .await
            .map_err(|e| Error::io_with_context("writing workspace file", e.to_string()))?;

        Ok(())
    }

    /// Load a workspace from disk
    pub async fn load_workspace(&self, workspace_id: &str) -> Result<Workspace> {
        let file_path = self.workspace_file_path(workspace_id);

        if !file_path.exists() {
            return Err(Error::not_found("Workspace file", &*file_path.to_string_lossy()));
        }

        let content = fs::read_to_string(&file_path)
            .await
            .map_err(|e| Error::io_with_context("reading workspace file", e.to_string()))?;

        let mut workspace: Workspace = serde_yaml::from_str(&content)
            .map_err(|e| Error::config(format!("Failed to deserialize workspace: {}", e)))?;

        // Initialize default mock environments if they don't exist (for backward compatibility)
        workspace.initialize_default_mock_environments();

        Ok(workspace)
    }

    /// Delete a workspace from disk
    pub async fn delete_workspace(&self, workspace_id: &str) -> Result<()> {
        let file_path = self.workspace_file_path(workspace_id);

        if file_path.exists() {
            fs::remove_file(&file_path)
                .await
                .map_err(|e| Error::io_with_context("deleting workspace file", e.to_string()))?;
        }

        Ok(())
    }

    /// Save the workspace registry metadata
    pub async fn save_registry(&self, registry: &WorkspaceRegistry) -> Result<()> {
        self.ensure_workspace_dir().await?;

        let serializable = SerializableWorkspaceRegistry {
            workspaces: registry.get_workspaces().into_iter().cloned().collect(),
            active_workspace: registry.get_active_workspace_id().map(|s| s.to_string()),
        };

        let file_path = self.registry_file_path();
        let content = serde_yaml::to_string(&serializable)
            .map_err(|e| Error::config(format!("Failed to serialize registry: {}", e)))?;

        fs::write(&file_path, content)
            .await
            .map_err(|e| Error::io_with_context("writing registry file", e.to_string()))?;

        Ok(())
    }

    /// Load the workspace registry metadata
    pub async fn load_registry(&self) -> Result<WorkspaceRegistry> {
        let file_path = self.registry_file_path();

        if !file_path.exists() {
            // Return empty registry if no registry file exists
            return Ok(WorkspaceRegistry::new());
        }

        let content = fs::read_to_string(&file_path)
            .await
            .map_err(|e| Error::io_with_context("reading registry file", e.to_string()))?;

        let serializable: SerializableWorkspaceRegistry = serde_yaml::from_str(&content)
            .map_err(|e| Error::config(format!("Failed to deserialize registry: {}", e)))?;

        let mut registry = WorkspaceRegistry::new();

        // Load individual workspaces
        for workspace_meta in &serializable.workspaces {
            match self.load_workspace(&workspace_meta.id).await {
                Ok(mut workspace) => {
                    // Ensure mock environments are initialized (for backward compatibility)
                    workspace.initialize_default_mock_environments();
                    registry.add_workspace(workspace)?;
                }
                Err(e) => {
                    tracing::warn!("Failed to load workspace {}: {}", workspace_meta.id, e);
                }
            }
        }

        // Set active workspace
        if let Some(active_id) = &serializable.active_workspace {
            if let Err(e) = registry.set_active_workspace(Some(active_id.clone())) {
                tracing::warn!("Failed to set active workspace {}: {}", active_id, e);
            }
        }

        Ok(registry)
    }

    /// Save the sync state
    pub async fn save_sync_state(&self, sync_state: &SyncState) -> Result<()> {
        self.ensure_workspace_dir().await?;

        let file_path = self.sync_state_file_path();
        let content = serde_yaml::to_string(sync_state)
            .map_err(|e| Error::config(format!("Failed to serialize sync state: {}", e)))?;

        fs::write(&file_path, content)
            .await
            .map_err(|e| Error::io_with_context("writing sync state file", e.to_string()))?;

        Ok(())
    }

    /// Load the sync state
    pub async fn load_sync_state(&self) -> Result<SyncState> {
        let file_path = self.sync_state_file_path();

        if !file_path.exists() {
            // Return default sync state if no sync state file exists
            return Ok(SyncState {
                last_sync_timestamp: Utc::now(),
            });
        }

        let content = fs::read_to_string(&file_path)
            .await
            .map_err(|e| Error::io_with_context("reading sync state file", e.to_string()))?;

        let sync_state: SyncState = serde_yaml::from_str(&content)
            .map_err(|e| Error::config(format!("Failed to deserialize sync state: {}", e)))?;

        Ok(sync_state)
    }

    /// List all workspace IDs from disk
    pub async fn list_workspace_ids(&self) -> Result<Vec<EntityId>> {
        if !self.base_dir.exists() {
            return Ok(Vec::new());
        }

        let mut workspace_ids = Vec::new();

        let mut entries = fs::read_dir(&self.base_dir)
            .await
            .map_err(|e| Error::io_with_context("reading workspace directory", e.to_string()))?;

        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| Error::io_with_context("reading directory entry", e.to_string()))?
        {
            let path = entry.path();
            if path.is_file() {
                if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
                    if file_name != "registry.yaml" && file_name.ends_with(".yaml") {
                        if let Some(id) = file_name.strip_suffix(".yaml") {
                            workspace_ids.push(id.to_string());
                        }
                    }
                }
            }
        }

        Ok(workspace_ids)
    }

    /// Save the entire registry and all workspaces
    pub async fn save_full_registry(&self, registry: &WorkspaceRegistry) -> Result<()> {
        // Save registry metadata
        self.save_registry(registry).await?;

        // Save all workspaces
        for workspace in registry.get_workspaces() {
            self.save_workspace(workspace).await?;
        }

        Ok(())
    }

    /// Load the entire registry and all workspaces
    pub async fn load_full_registry(&self) -> Result<WorkspaceRegistry> {
        self.load_registry().await
    }

    /// Backup workspace data
    pub async fn backup_workspace(&self, workspace_id: &str, backup_dir: &Path) -> Result<PathBuf> {
        let workspace_file = self.workspace_file_path(workspace_id);

        if !workspace_file.exists() {
            return Err(Error::not_found("Workspace", workspace_id));
        }

        // Ensure backup directory exists
        if !backup_dir.exists() {
            fs::create_dir_all(backup_dir)
                .await
                .map_err(|e| Error::io_with_context("creating backup directory", e.to_string()))?;
        }

        // Create backup filename with timestamp
        let timestamp = Utc::now().format("%Y%m%d_%H%M%S");
        let backup_filename = format!("{}_{}.yaml", workspace_id, timestamp);
        let backup_path = backup_dir.join(backup_filename);

        // Copy workspace file
        fs::copy(&workspace_file, &backup_path)
            .await
            .map_err(|e| Error::io_with_context("creating backup", e.to_string()))?;

        Ok(backup_path)
    }

    /// Restore workspace from backup
    pub async fn restore_workspace(&self, backup_path: &Path) -> Result<EntityId> {
        if !backup_path.exists() {
            return Err(Error::not_found("Backup file", &*backup_path.to_string_lossy()));
        }

        // Load workspace from backup
        let content = fs::read_to_string(backup_path)
            .await
            .map_err(|e| Error::io_with_context("reading backup file", e.to_string()))?;

        let workspace: Workspace = serde_yaml::from_str(&content)
            .map_err(|e| Error::config(format!("Failed to deserialize backup: {}", e)))?;

        // Save restored workspace
        self.save_workspace(&workspace).await?;

        Ok(workspace.id)
    }

    /// Clean up old backups
    pub async fn cleanup_old_backups(&self, backup_dir: &Path, keep_count: usize) -> Result<usize> {
        if !backup_dir.exists() {
            return Ok(0);
        }

        let mut backup_files = Vec::new();

        let mut entries = fs::read_dir(backup_dir)
            .await
            .map_err(|e| Error::io_with_context("reading backup directory", e.to_string()))?;

        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| Error::io_with_context("reading backup entry", e.to_string()))?
        {
            let path = entry.path();
            if path.is_file() {
                if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
                    if file_name.ends_with(".yaml") {
                        if let Ok(metadata) = entry.metadata().await {
                            if let Ok(modified) = metadata.modified() {
                                backup_files.push((path, modified));
                            }
                        }
                    }
                }
            }
        }

        // Sort by modification time (newest first)
        backup_files.sort_by(|a, b| b.1.cmp(&a.1));

        // Remove old backups
        let mut removed_count = 0;
        for (path, _) in backup_files.iter().skip(keep_count) {
            if fs::remove_file(path).await.is_ok() {
                removed_count += 1;
            }
        }

        Ok(removed_count)
    }

    /// Advanced sync with additional configuration options
    #[allow(clippy::too_many_arguments)]
    pub async fn sync_to_directory_advanced(
        &self,
        target_dir: &str,
        strategy: &str,
        workspace_ids: Option<&str>,
        structure: &str,
        include_meta: bool,
        force: bool,
        filename_pattern: &str,
        exclude_pattern: Option<&str>,
        dry_run: bool,
    ) -> Result<SyncResult> {
        let target_path = PathBuf::from(target_dir);

        // Ensure target directory exists (unless dry run)
        if !dry_run && !target_path.exists() {
            fs::create_dir_all(&target_path)
                .await
                .map_err(|e| Error::io_with_context("creating target directory", e.to_string()))?;
        }

        // Parse strategy
        let sync_strategy = match strategy {
            "full" => SyncStrategy::Full,
            "incremental" => SyncStrategy::Incremental,
            "selective" => {
                if let Some(ids) = workspace_ids {
                    let workspace_list = ids.split(',').map(|s| s.trim().to_string()).collect();
                    SyncStrategy::Selective(workspace_list)
                } else {
                    return Err(Error::validation("Selective strategy requires workspace IDs"));
                }
            }
            _ => return Err(Error::validation(format!("Unknown sync strategy: {}", strategy))),
        };

        // Parse directory structure
        let dir_structure = match structure {
            "flat" => DirectoryStructure::Flat,
            "nested" => DirectoryStructure::Nested,
            "grouped" => DirectoryStructure::Grouped,
            _ => {
                return Err(Error::validation(format!(
                    "Unknown directory structure: {}",
                    structure
                )))
            }
        };

        // Get workspaces to sync based on strategy
        let mut workspaces_to_sync = self.get_workspaces_for_sync(&sync_strategy).await?;

        // Apply exclusion filter if provided
        if let Some(exclude) = exclude_pattern {
            if let Ok(regex) = Regex::new(exclude) {
                workspaces_to_sync.retain(|id| !regex.is_match(id));
            }
        }

        let mut result = SyncResult {
            synced_workspaces: 0,
            synced_requests: 0,
            files_created: 0,
            target_dir: target_path.clone(),
        };

        // Sync each workspace
        for workspace_id in workspaces_to_sync {
            if let Ok(workspace) = self.load_workspace(&workspace_id).await {
                let workspace_result = self
                    .sync_workspace_to_directory_advanced(
                        &workspace,
                        &target_path,
                        &dir_structure,
                        include_meta,
                        force,
                        filename_pattern,
                        dry_run,
                    )
                    .await?;

                result.synced_workspaces += 1;
                result.synced_requests += workspace_result.requests_count;
                result.files_created += workspace_result.files_created;
            }
        }

        // Update sync state for incremental syncs
        if let SyncStrategy::Incremental = sync_strategy {
            let new_sync_state = SyncState {
                last_sync_timestamp: Utc::now(),
            };
            if let Err(e) = self.save_sync_state(&new_sync_state).await {
                tracing::warn!("Failed to save sync state: {}", e);
            }
        }

        Ok(result)
    }

    /// Advanced sync for a single workspace with custom filename patterns
    #[allow(clippy::too_many_arguments)]
    async fn sync_workspace_to_directory_advanced(
        &self,
        workspace: &Workspace,
        target_dir: &Path,
        structure: &DirectoryStructure,
        include_meta: bool,
        force: bool,
        filename_pattern: &str,
        dry_run: bool,
    ) -> Result<WorkspaceSyncResult> {
        let mut result = WorkspaceSyncResult {
            requests_count: 0,
            files_created: 0,
        };

        match structure {
            DirectoryStructure::Flat => {
                let export = self.create_workspace_export(workspace).await?;
                let filename = self.generate_filename(filename_pattern, workspace);
                let file_path = target_dir.join(format!("{}.yaml", filename));

                if force || !file_path.exists() {
                    if !dry_run {
                        let content = serde_yaml::to_string(&export).map_err(|e| {
                            Error::config(format!("Failed to serialize workspace: {}", e))
                        })?;

                        fs::write(&file_path, content).await.map_err(|e| {
                            Error::io_with_context("writing workspace file", e.to_string())
                        })?;
                    }
                    result.files_created += 1;
                }
            }

            DirectoryStructure::Nested => {
                let workspace_dir =
                    target_dir.join(self.generate_filename(filename_pattern, workspace));
                if !dry_run && !workspace_dir.exists() {
                    fs::create_dir_all(&workspace_dir).await.map_err(|e| {
                        Error::io_with_context("creating workspace directory", e.to_string())
                    })?;
                }

                // Export main workspace file
                let export = self.create_workspace_export(workspace).await?;
                let workspace_file = workspace_dir.join("workspace.yaml");

                if force || !workspace_file.exists() {
                    if !dry_run {
                        let content = serde_yaml::to_string(&export).map_err(|e| {
                            Error::config(format!("Failed to serialize workspace: {}", e))
                        })?;

                        fs::write(&workspace_file, content).await.map_err(|e| {
                            Error::io_with_context("writing workspace file", e.to_string())
                        })?;
                    }
                    result.files_created += 1;
                }

                // Export individual requests
                let requests_dir = workspace_dir.join("requests");
                if !dry_run && !requests_dir.exists() {
                    fs::create_dir_all(&requests_dir).await.map_err(|e| {
                        Error::io_with_context("creating requests directory", e.to_string())
                    })?;
                }

                result.requests_count += self
                    .export_workspace_requests_advanced(workspace, &requests_dir, force, dry_run)
                    .await?;
            }

            DirectoryStructure::Grouped => {
                // Create grouped directories
                let requests_dir = target_dir.join("requests");
                let workspaces_dir = target_dir.join("workspaces");

                if !dry_run {
                    for dir in [&requests_dir, &workspaces_dir] {
                        if !dir.exists() {
                            fs::create_dir_all(dir).await.map_err(|e| {
                                Error::io_with_context("creating directory", e.to_string())
                            })?;
                        }
                    }
                }

                // Export workspace metadata
                let export = self.create_workspace_export(workspace).await?;
                let filename = self.generate_filename(filename_pattern, workspace);
                let workspace_file = workspaces_dir.join(format!("{}.yaml", filename));

                if force || !workspace_file.exists() {
                    if !dry_run {
                        let content = serde_yaml::to_string(&export).map_err(|e| {
                            Error::config(format!("Failed to serialize workspace: {}", e))
                        })?;

                        fs::write(&workspace_file, content).await.map_err(|e| {
                            Error::io_with_context("writing workspace file", e.to_string())
                        })?;
                    }
                    result.files_created += 1;
                }

                // Export requests to requests directory
                result.requests_count += self
                    .export_workspace_requests_grouped_advanced(
                        workspace,
                        &requests_dir,
                        force,
                        dry_run,
                    )
                    .await?;
            }
        }

        // Create metadata file if requested
        if include_meta && !dry_run {
            self.create_metadata_file(workspace, target_dir, structure).await?;
            result.files_created += 1;
        }

        Ok(result)
    }

    /// Generate filename from pattern
    fn generate_filename(&self, pattern: &str, workspace: &Workspace) -> String {
        let timestamp = Utc::now().format("%Y%m%d_%H%M%S");

        pattern
            .replace("{name}", &self.sanitize_filename(&workspace.name))
            .replace("{id}", &workspace.id)
            .replace("{timestamp}", &timestamp.to_string())
    }

    /// Advanced request export with dry run support
    async fn export_workspace_requests_advanced(
        &self,
        workspace: &Workspace,
        requests_dir: &Path,
        force: bool,
        dry_run: bool,
    ) -> Result<usize> {
        let mut count = 0;

        for request in &workspace.requests {
            let file_path =
                requests_dir.join(format!("{}.yaml", self.sanitize_filename(&request.name)));
            if force || !file_path.exists() {
                if !dry_run {
                    let exported = self.convert_request_to_exported(request, "");
                    let content = serde_yaml::to_string(&exported).map_err(|e| {
                        Error::config(format!("Failed to serialize request: {}", e))
                    })?;

                    fs::write(&file_path, content).await.map_err(|e| {
                        Error::io_with_context("writing request file", e.to_string())
                    })?;
                }
                count += 1;
            }
        }

        // Export folder requests
        for folder in &workspace.folders {
            count += self
                .export_folder_requests_advanced(folder, requests_dir, force, &folder.name, dry_run)
                .await?;
        }

        Ok(count)
    }

    /// Advanced folder request export
    async fn export_folder_requests_advanced(
        &self,
        folder: &Folder,
        requests_dir: &Path,
        force: bool,
        folder_path: &str,
        dry_run: bool,
    ) -> Result<usize> {
        use std::collections::VecDeque;

        let mut count = 0;
        let mut queue = VecDeque::new();

        // Start with the root folder
        queue.push_back((folder, folder_path.to_string()));

        while let Some((current_folder, current_path)) = queue.pop_front() {
            // Export requests in current folder
            for request in &current_folder.requests {
                let file_path =
                    requests_dir.join(format!("{}.yaml", self.sanitize_filename(&request.name)));
                if force || !file_path.exists() {
                    if !dry_run {
                        let exported = self.convert_request_to_exported(request, &current_path);
                        let content = serde_yaml::to_string(&exported).map_err(|e| {
                            Error::config(format!("Failed to serialize request: {}", e))
                        })?;

                        fs::write(&file_path, content).await.map_err(|e| {
                            Error::io_with_context("writing request file", e.to_string())
                        })?;
                    }
                    count += 1;
                }
            }

            // Add subfolders to queue with updated paths
            for subfolder in &current_folder.folders {
                let subfolder_path = if current_path.is_empty() {
                    subfolder.name.clone()
                } else {
                    format!("{}/{}", current_path, subfolder.name)
                };
                queue.push_back((subfolder, subfolder_path));
            }
        }

        Ok(count)
    }

    /// Advanced grouped request export
    async fn export_workspace_requests_grouped_advanced(
        &self,
        workspace: &Workspace,
        requests_dir: &Path,
        force: bool,
        dry_run: bool,
    ) -> Result<usize> {
        let mut count = 0;
        let workspace_requests_dir = requests_dir.join(self.sanitize_filename(&workspace.name));

        if !dry_run && !workspace_requests_dir.exists() {
            fs::create_dir_all(&workspace_requests_dir).await.map_err(|e| {
                Error::io_with_context("creating workspace requests directory", e.to_string())
            })?;
        }

        count += self
            .export_workspace_requests_advanced(workspace, &workspace_requests_dir, force, dry_run)
            .await?;
        Ok(count)
    }

    /// Sync workspaces to an external directory for Git/Dropbox integration
    pub async fn sync_to_directory(
        &self,
        target_dir: &str,
        strategy: &str,
        workspace_ids: Option<&str>,
        structure: &str,
        include_meta: bool,
        force: bool,
    ) -> Result<SyncResult> {
        let target_path = PathBuf::from(target_dir);

        // Ensure target directory exists
        if !target_path.exists() {
            fs::create_dir_all(&target_path)
                .await
                .map_err(|e| Error::io_with_context("creating target directory", e.to_string()))?;
        }

        // Parse strategy
        let sync_strategy = match strategy {
            "full" => SyncStrategy::Full,
            "incremental" => SyncStrategy::Incremental,
            "selective" => {
                if let Some(ids) = workspace_ids {
                    let workspace_list = ids.split(',').map(|s| s.trim().to_string()).collect();
                    SyncStrategy::Selective(workspace_list)
                } else {
                    return Err(Error::validation("Selective strategy requires workspace IDs"));
                }
            }
            _ => return Err(Error::validation(format!("Unknown sync strategy: {}", strategy))),
        };

        // Parse directory structure
        let dir_structure = match structure {
            "flat" => DirectoryStructure::Flat,
            "nested" => DirectoryStructure::Nested,
            "grouped" => DirectoryStructure::Grouped,
            _ => {
                return Err(Error::validation(format!(
                    "Unknown directory structure: {}",
                    structure
                )))
            }
        };

        // Get workspaces to sync based on strategy
        let workspaces_to_sync = self.get_workspaces_for_sync(&sync_strategy).await?;

        let mut result = SyncResult {
            synced_workspaces: 0,
            synced_requests: 0,
            files_created: 0,
            target_dir: target_path.clone(),
        };

        // Sync each workspace
        for workspace_id in workspaces_to_sync {
            if let Ok(workspace) = self.load_workspace(&workspace_id).await {
                let workspace_result = self
                    .sync_workspace_to_directory(
                        &workspace,
                        &target_path,
                        &dir_structure,
                        include_meta,
                        force,
                    )
                    .await?;

                result.synced_workspaces += 1;
                result.synced_requests += workspace_result.requests_count;
                result.files_created += workspace_result.files_created;
            }
        }

        // Update sync state for incremental syncs
        if let SyncStrategy::Incremental = sync_strategy {
            let new_sync_state = SyncState {
                last_sync_timestamp: Utc::now(),
            };
            if let Err(e) = self.save_sync_state(&new_sync_state).await {
                tracing::warn!("Failed to save sync state: {}", e);
            }
        }

        Ok(result)
    }

    /// Get list of workspace IDs to sync based on strategy
    async fn get_workspaces_for_sync(&self, strategy: &SyncStrategy) -> Result<Vec<String>> {
        match strategy {
            SyncStrategy::Full => self.list_workspace_ids().await,
            SyncStrategy::Incremental => {
                // Load sync state to get last sync timestamp
                let sync_state = self.load_sync_state().await?;
                let last_sync = sync_state.last_sync_timestamp;

                // Get all workspace IDs
                let all_workspace_ids = self.list_workspace_ids().await?;

                // Filter workspaces that have been modified since last sync
                let mut modified_workspaces = Vec::new();
                for workspace_id in all_workspace_ids {
                    let file_path = self.workspace_file_path(&workspace_id);
                    if let Ok(metadata) = fs::metadata(&file_path).await {
                        if let Ok(modified_time) = metadata.modified() {
                            let modified_datetime = DateTime::<Utc>::from(modified_time);
                            if modified_datetime > last_sync {
                                modified_workspaces.push(workspace_id);
                            }
                        }
                    }
                }

                Ok(modified_workspaces)
            }
            SyncStrategy::Selective(ids) => Ok(ids.clone()),
        }
    }

    /// Sync a single workspace to the target directory
    async fn sync_workspace_to_directory(
        &self,
        workspace: &Workspace,
        target_dir: &Path,
        structure: &DirectoryStructure,
        include_meta: bool,
        force: bool,
    ) -> Result<WorkspaceSyncResult> {
        let mut result = WorkspaceSyncResult {
            requests_count: 0,
            files_created: 0,
        };

        match structure {
            DirectoryStructure::Flat => {
                let export = self.create_workspace_export(workspace).await?;
                let file_path =
                    target_dir.join(format!("{}.yaml", self.sanitize_filename(&workspace.name)));

                if force || !file_path.exists() {
                    let content = serde_yaml::to_string(&export).map_err(|e| {
                        Error::config(format!("Failed to serialize workspace: {}", e))
                    })?;

                    fs::write(&file_path, content).await.map_err(|e| {
                        Error::io_with_context("writing workspace file", e.to_string())
                    })?;

                    result.files_created += 1;
                }
            }

            DirectoryStructure::Nested => {
                let workspace_dir = target_dir.join(self.sanitize_filename(&workspace.name));
                if !workspace_dir.exists() {
                    fs::create_dir_all(&workspace_dir).await.map_err(|e| {
                        Error::io_with_context("creating workspace directory", e.to_string())
                    })?;
                }

                // Export main workspace file
                let export = self.create_workspace_export(workspace).await?;
                let workspace_file = workspace_dir.join("workspace.yaml");

                if force || !workspace_file.exists() {
                    let content = serde_yaml::to_string(&export).map_err(|e| {
                        Error::config(format!("Failed to serialize workspace: {}", e))
                    })?;

                    fs::write(&workspace_file, content).await.map_err(|e| {
                        Error::io_with_context("writing workspace file", e.to_string())
                    })?;

                    result.files_created += 1;
                }

                // Export individual requests
                let requests_dir = workspace_dir.join("requests");
                if !requests_dir.exists() {
                    fs::create_dir_all(&requests_dir).await.map_err(|e| {
                        Error::io_with_context("creating requests directory", e.to_string())
                    })?;
                }

                result.requests_count +=
                    self.export_workspace_requests(workspace, &requests_dir, force).await?;
            }

            DirectoryStructure::Grouped => {
                // Create grouped directories
                let requests_dir = target_dir.join("requests");
                let workspaces_dir = target_dir.join("workspaces");

                for dir in [&requests_dir, &workspaces_dir] {
                    if !dir.exists() {
                        fs::create_dir_all(dir).await.map_err(|e| {
                            Error::io_with_context("creating directory", e.to_string())
                        })?;
                    }
                }

                // Export workspace metadata
                let export = self.create_workspace_export(workspace).await?;
                let workspace_file = workspaces_dir
                    .join(format!("{}.yaml", self.sanitize_filename(&workspace.name)));

                if force || !workspace_file.exists() {
                    let content = serde_yaml::to_string(&export).map_err(|e| {
                        Error::config(format!("Failed to serialize workspace: {}", e))
                    })?;

                    fs::write(&workspace_file, content).await.map_err(|e| {
                        Error::io_with_context("writing workspace file", e.to_string())
                    })?;

                    result.files_created += 1;
                }

                // Export requests to requests directory
                result.requests_count +=
                    self.export_workspace_requests_grouped(workspace, &requests_dir, force).await?;
            }
        }

        // Create metadata file if requested
        if include_meta {
            self.create_metadata_file(workspace, target_dir, structure).await?;
            result.files_created += 1;
        }

        Ok(result)
    }

    /// Create a Git-friendly workspace export
    async fn create_workspace_export(&self, workspace: &Workspace) -> Result<WorkspaceExport> {
        let mut requests = HashMap::new();

        // Collect all requests from workspace
        self.collect_requests_from_workspace(workspace, &mut requests, "".to_string());

        let metadata = WorkspaceMetadata {
            id: workspace.id.clone(),
            name: workspace.name.clone(),
            description: workspace.description.clone(),
            exported_at: Utc::now(),
            request_count: requests.len(),
            folder_count: workspace.folders.len(),
        };

        let config = WorkspaceConfig {
            auth: workspace.config.auth.as_ref().and_then(AuthConfig::from_config_auth),
            base_url: workspace.config.base_url.clone(),
            variables: workspace.config.global_environment.variables.clone(),
            reality_level: workspace.config.reality_level,
            ai_mode: None, // Default to None for exported workspaces
        };

        Ok(WorkspaceExport {
            metadata,
            config,
            requests,
        })
    }

    /// Collect all requests from workspace into a hashmap
    fn collect_requests_from_workspace(
        &self,
        workspace: &Workspace,
        requests: &mut HashMap<String, ExportedRequest>,
        folder_path: String,
    ) {
        // Add root-level requests
        for request in &workspace.requests {
            let exported = self.convert_request_to_exported(request, &folder_path);
            requests.insert(request.id.clone(), exported);
        }

        // Add folder requests recursively
        for folder in &workspace.folders {
            let current_path = if folder_path.is_empty() {
                folder.name.clone()
            } else {
                format!("{}/{}", folder_path, folder.name)
            };

            for request in &folder.requests {
                let exported = self.convert_request_to_exported(request, &current_path);
                requests.insert(request.id.clone(), exported);
            }

            // Recursively process subfolders
            self.collect_requests_from_folders(folder, requests, current_path);
        }
    }

    /// Recursively collect requests from folders
    fn collect_requests_from_folders(
        &self,
        folder: &Folder,
        requests: &mut HashMap<String, ExportedRequest>,
        folder_path: String,
    ) {
        for subfolder in &folder.folders {
            let current_path = format!("{}/{}", folder_path, subfolder.name);

            for request in &subfolder.requests {
                let exported = self.convert_request_to_exported(request, &current_path);
                requests.insert(request.id.clone(), exported);
            }

            self.collect_requests_from_folders(subfolder, requests, current_path);
        }
    }

    /// Convert a MockRequest to ExportedRequest
    fn convert_request_to_exported(
        &self,
        request: &MockRequest,
        folder_path: &str,
    ) -> ExportedRequest {
        ExportedRequest {
            id: request.id.clone(),
            name: request.name.clone(),
            method: format!("{:?}", request.method),
            path: request.path.clone(),
            folder_path: folder_path.to_string(),
            headers: request.headers.clone(),
            query_params: request.query_params.clone(),
            body: request.body.clone(),
            response_status: Some(request.response.status_code),
            response_body: request.response.body.clone(),
            response_headers: request.response.headers.clone(),
            delay: request.response.delay_ms,
        }
    }

    /// Export workspace with encryption for secure sharing
    pub async fn export_workspace_encrypted(
        &self,
        workspace: &Workspace,
        output_path: &Path,
    ) -> Result<EncryptedExportResult> {
        // Check if encryption is enabled for this workspace
        if !workspace.config.auto_encryption.enabled {
            return Err(Error::invalid_state("Encryption is not enabled for this workspace. Enable encryption in workspace settings first."));
        }

        // Get auto-encryption config
        let encryption_config = workspace.config.auto_encryption.clone();
        let processor = AutoEncryptionProcessor::new(&workspace.id, encryption_config);

        // Create filtered workspace copy for export
        let mut filtered_workspace = workspace.to_filtered_for_sync();

        // Apply automatic encryption to the filtered workspace
        self.encrypt_workspace_data(&mut filtered_workspace, &processor)?;

        // Create standard export
        let export = self.create_workspace_export(&filtered_workspace).await?;

        // Encrypt the entire export
        let export_json = serde_json::to_string_pretty(&export)
            .map_err(|e| Error::config(format!("Failed to serialize export: {}", e)))?;

        let encrypted_data = utils::encrypt_for_workspace(&workspace.id, &export_json)?;

        // Generate backup key for sharing
        let key_manager = WorkspaceKeyManager::new();
        let backup_key = key_manager.generate_workspace_key_backup(&workspace.id)?;

        // Write encrypted data to file
        fs::write(output_path, &encrypted_data)
            .await
            .map_err(|e| Error::io_with_context("writing encrypted export", e.to_string()))?;

        Ok(EncryptedExportResult {
            output_path: output_path.to_path_buf(),
            backup_key,
            exported_at: Utc::now(),
            workspace_name: workspace.name.clone(),
            encryption_enabled: true,
        })
    }

    /// Import encrypted workspace
    pub async fn import_workspace_encrypted(
        &self,
        encrypted_file: &Path,
        _workspace_name: Option<&str>,
        _registry: &mut WorkspaceRegistry,
    ) -> Result<EncryptedImportResult> {
        // Read encrypted data
        let _encrypted_data = fs::read_to_string(encrypted_file)
            .await
            .map_err(|e| Error::io_with_context("reading encrypted file", e.to_string()))?;

        // For import, we need the workspace ID and backup key
        // This would typically be provided by the user or extracted from metadata
        Err(Error::validation("Encrypted import requires workspace ID and backup key. Use import_workspace_encrypted_with_key instead."))
    }

    /// Import encrypted workspace with specific workspace ID and backup key
    pub async fn import_workspace_encrypted_with_key(
        &self,
        encrypted_file: &Path,
        workspace_id: &str,
        backup_key: &str,
        workspace_name: Option<&str>,
        registry: &mut WorkspaceRegistry,
    ) -> Result<EncryptedImportResult> {
        // Ensure workspace key exists or restore from backup
        let key_manager = WorkspaceKeyManager::new();
        if !key_manager.has_workspace_key(workspace_id) {
            key_manager.restore_workspace_key_from_backup(workspace_id, backup_key)?;
        }

        // Read and decrypt the data
        let encrypted_data = fs::read_to_string(encrypted_file)
            .await
            .map_err(|e| Error::io_with_context("reading encrypted file", e.to_string()))?;

        let decrypted_json = utils::decrypt_for_workspace(workspace_id, &encrypted_data)?;

        // Parse the export data
        let export: WorkspaceExport = serde_json::from_str(&decrypted_json)
            .map_err(|e| Error::config(format!("Failed to parse decrypted export: {}", e)))?;

        // Convert export to workspace
        let workspace = self.convert_export_to_workspace(&export, workspace_name)?;

        // Add to registry
        let imported_id = registry.add_workspace(workspace)?;

        Ok(EncryptedImportResult {
            workspace_id: imported_id,
            workspace_name: export.metadata.name.clone(),
            imported_at: Utc::now(),
            request_count: export.requests.len(),
            encryption_restored: true,
        })
    }

    /// Apply encryption to workspace data before export
    fn encrypt_workspace_data(
        &self,
        workspace: &mut Workspace,
        processor: &AutoEncryptionProcessor,
    ) -> Result<()> {
        // Encrypt environment variables
        for env in &mut workspace.config.environments {
            processor.process_env_vars(&mut env.variables)?;
        }
        processor.process_env_vars(&mut workspace.config.global_environment.variables)?;

        // Note: Headers and request bodies would be encrypted here when implemented
        // For now, we rely on the filtering done by to_filtered_for_sync()

        Ok(())
    }

    /// Convert WorkspaceExport back to Workspace
    fn convert_export_to_workspace(
        &self,
        export: &WorkspaceExport,
        name_override: Option<&str>,
    ) -> Result<Workspace> {
        let mut workspace =
            Workspace::new(name_override.unwrap_or(&export.metadata.name).to_string());

        // Set description if provided
        if let Some(desc) = &export.metadata.description {
            workspace.description = Some(desc.clone());
        }

        // Restore requests from export
        for exported_request in export.requests.values() {
            // Convert exported request back to MockRequest
            let method = self.parse_http_method(&exported_request.method)?;
            let mut request = MockRequest::new(
                method,
                exported_request.path.clone(),
                exported_request.name.clone(),
            );

            // Set additional properties
            if let Some(status) = exported_request.response_status {
                request.response.status_code = status;
            }

            // Set other response properties if available
            if let Some(body) = &exported_request.response_body {
                request.response.body = Some(body.clone());
            }
            request.response.headers = exported_request.response_headers.clone();
            if let Some(delay) = exported_request.delay {
                request.response.delay_ms = Some(delay);
            }

            workspace.add_request(request)?;
        }

        // Restore configuration
        workspace.config.global_environment.variables = export.config.variables.clone();

        Ok(workspace)
    }

    /// Parse HTTP method string to enum
    fn parse_http_method(&self, method_str: &str) -> Result<crate::routing::HttpMethod> {
        match method_str.to_uppercase().as_str() {
            "GET" => Ok(crate::routing::HttpMethod::GET),
            "POST" => Ok(crate::routing::HttpMethod::POST),
            "PUT" => Ok(crate::routing::HttpMethod::PUT),
            "DELETE" => Ok(crate::routing::HttpMethod::DELETE),
            "PATCH" => Ok(crate::routing::HttpMethod::PATCH),
            "HEAD" => Ok(crate::routing::HttpMethod::HEAD),
            "OPTIONS" => Ok(crate::routing::HttpMethod::OPTIONS),
            _ => Err(Error::validation(format!("Unknown HTTP method: {}", method_str))),
        }
    }

    /// Check workspace for unencrypted sensitive data before export
    pub fn check_workspace_for_unencrypted_secrets(
        &self,
        workspace: &Workspace,
    ) -> Result<SecurityCheckResult> {
        let mut warnings = Vec::new();
        let errors = Vec::new();

        // Check environment variables
        self.check_environment_variables(workspace, &mut warnings)?;

        // Check for sensitive patterns in request data (when implemented)
        // This would check headers, bodies, etc.

        let has_warnings = !warnings.is_empty();
        let has_errors = !errors.is_empty();

        Ok(SecurityCheckResult {
            workspace_id: workspace.id.clone(),
            workspace_name: workspace.name.clone(),
            warnings,
            errors,
            is_secure: !has_warnings && !has_errors,
            recommended_actions: self.generate_security_recommendations(has_warnings, has_errors),
        })
    }

    /// Check environment variables for sensitive data
    fn check_environment_variables(
        &self,
        workspace: &Workspace,
        warnings: &mut Vec<SecurityWarning>,
    ) -> Result<()> {
        let sensitive_keys = [
            "password",
            "secret",
            "key",
            "token",
            "credential",
            "api_key",
            "apikey",
            "api_secret",
            "db_password",
            "database_password",
            "aws_secret_key",
            "aws_session_token",
            "private_key",
            "authorization",
            "auth_token",
            "access_token",
            "refresh_token",
            "cookie",
            "session",
            "csrf",
            "jwt",
            "bearer",
        ];

        // Check global environment
        for (key, value) in &workspace.config.global_environment.variables {
            if self.is_potentially_sensitive(key, value, &sensitive_keys) {
                warnings.push(SecurityWarning {
                    field_type: "environment_variable".to_string(),
                    field_name: key.clone(),
                    location: "global_environment".to_string(),
                    severity: SecuritySeverity::High,
                    message: format!(
                        "Potentially sensitive environment variable '{}' detected",
                        key
                    ),
                    suggestion: "Consider encrypting this value or excluding it from exports"
                        .to_string(),
                });
            }
        }

        // Check workspace environments
        for env in &workspace.config.environments {
            for (key, value) in &env.variables {
                if self.is_potentially_sensitive(key, value, &sensitive_keys) {
                    warnings.push(SecurityWarning {
                        field_type: "environment_variable".to_string(),
                        field_name: key.clone(),
                        location: format!("environment '{}'", env.name),
                        severity: SecuritySeverity::High,
                        message: format!("Potentially sensitive environment variable '{}' detected in environment '{}'", key, env.name),
                        suggestion: "Consider encrypting this value or excluding it from exports".to_string(),
                    });
                }
            }
        }

        Ok(())
    }

    /// Check if a key-value pair is potentially sensitive
    fn is_potentially_sensitive(&self, key: &str, value: &str, sensitive_keys: &[&str]) -> bool {
        let key_lower = key.to_lowercase();

        // Check if key contains sensitive keywords
        if sensitive_keys.iter().any(|&sensitive| key_lower.contains(sensitive)) {
            return true;
        }

        // Check for patterns that indicate sensitive data
        self.contains_sensitive_patterns(value)
    }

    /// Check if value contains sensitive patterns
    fn contains_sensitive_patterns(&self, value: &str) -> bool {
        // Credit card pattern
        if CREDIT_CARD_PATTERN.is_match(value) {
            return true;
        }

        // SSN pattern
        if SSN_PATTERN.is_match(value) {
            return true;
        }

        // Long random-looking strings (potential API keys)
        if value.len() > 20 && value.chars().any(|c| c.is_alphanumeric()) {
            let alphanumeric_count = value.chars().filter(|c| c.is_alphanumeric()).count();
            let total_count = value.len();
            if alphanumeric_count as f64 / total_count as f64 > 0.8 {
                return true;
            }
        }

        false
    }

    /// Generate security recommendations based on findings
    fn generate_security_recommendations(
        &self,
        has_warnings: bool,
        has_errors: bool,
    ) -> Vec<String> {
        let mut recommendations = Vec::new();

        if has_warnings || has_errors {
            recommendations.push("Enable encryption for this workspace in settings".to_string());
            recommendations.push("Review and encrypt sensitive environment variables".to_string());
            recommendations.push("Use encrypted export for sharing workspaces".to_string());
        }

        if has_errors {
            recommendations
                .push("CRITICAL: Remove or encrypt sensitive data before proceeding".to_string());
        }

        recommendations
    }

    /// Export individual requests for nested structure
    async fn export_workspace_requests(
        &self,
        workspace: &Workspace,
        requests_dir: &Path,
        force: bool,
    ) -> Result<usize> {
        let mut count = 0;

        for request in &workspace.requests {
            let file_path =
                requests_dir.join(format!("{}.yaml", self.sanitize_filename(&request.name)));
            if force || !file_path.exists() {
                let exported = self.convert_request_to_exported(request, "");
                let content = serde_yaml::to_string(&exported)
                    .map_err(|e| Error::config(format!("Failed to serialize request: {}", e)))?;

                fs::write(&file_path, content)
                    .await
                    .map_err(|e| Error::io_with_context("writing request file", e.to_string()))?;

                count += 1;
            }
        }

        // Export folder requests
        for folder in &workspace.folders {
            count += self.export_folder_requests(folder, requests_dir, force, &folder.name).await?;
        }

        Ok(count)
    }

    /// Export requests from folders recursively
    async fn export_folder_requests(
        &self,
        folder: &Folder,
        requests_dir: &Path,
        force: bool,
        folder_path: &str,
    ) -> Result<usize> {
        use std::collections::VecDeque;

        let mut count = 0;
        let mut queue = VecDeque::new();

        // Start with the root folder
        queue.push_back((folder, folder_path.to_string()));

        while let Some((current_folder, current_path)) = queue.pop_front() {
            // Export requests in current folder
            for request in &current_folder.requests {
                let file_path =
                    requests_dir.join(format!("{}.yaml", self.sanitize_filename(&request.name)));
                if force || !file_path.exists() {
                    let exported = self.convert_request_to_exported(request, &current_path);
                    let content = serde_yaml::to_string(&exported).map_err(|e| {
                        Error::config(format!("Failed to serialize request: {}", e))
                    })?;

                    fs::write(&file_path, content).await.map_err(|e| {
                        Error::io_with_context("writing request file", e.to_string())
                    })?;

                    count += 1;
                }
            }

            // Add subfolders to queue with updated paths
            for subfolder in &current_folder.folders {
                let subfolder_path = if current_path.is_empty() {
                    subfolder.name.clone()
                } else {
                    format!("{}/{}", current_path, subfolder.name)
                };
                queue.push_back((subfolder, subfolder_path));
            }
        }

        Ok(count)
    }

    /// Export requests for grouped structure
    async fn export_workspace_requests_grouped(
        &self,
        workspace: &Workspace,
        requests_dir: &Path,
        force: bool,
    ) -> Result<usize> {
        let mut count = 0;
        let workspace_requests_dir = requests_dir.join(self.sanitize_filename(&workspace.name));

        if !workspace_requests_dir.exists() {
            fs::create_dir_all(&workspace_requests_dir).await.map_err(|e| {
                Error::io_with_context("creating workspace requests directory", e.to_string())
            })?;
        }

        count += self
            .export_workspace_requests(workspace, &workspace_requests_dir, force)
            .await?;
        Ok(count)
    }

    /// Create metadata file for Git integration
    async fn create_metadata_file(
        &self,
        workspace: &Workspace,
        target_dir: &Path,
        structure: &DirectoryStructure,
    ) -> Result<()> {
        let metadata = serde_json::json!({
            "workspace_id": workspace.id,
            "workspace_name": workspace.name,
            "description": workspace.description,
            "exported_at": Utc::now().to_rfc3339(),
            "structure": format!("{:?}", structure),
            "version": "1.0",
            "source": "mockforge"
        });

        let metadata_file = target_dir.join(".mockforge-meta.json");
        let content = serde_json::to_string_pretty(&metadata)
            .map_err(|e| Error::config(format!("Failed to serialize metadata: {}", e)))?;

        fs::write(&metadata_file, content)
            .await
            .map_err(|e| Error::io_with_context("writing metadata file", e.to_string()))?;

        Ok(())
    }

    /// Export a reality preset to a file
    ///
    /// Exports a reality preset (JSON or YAML format) to the specified path.
    /// The preset can be imported later to restore the reality configuration.
    pub async fn export_reality_preset(
        &self,
        preset: &crate::RealityPreset,
        output_path: &Path,
    ) -> Result<()> {
        self.ensure_workspace_dir().await?;

        // Determine format from file extension
        let content = if output_path.extension().and_then(|s| s.to_str()) == Some("yaml")
            || output_path.extension().and_then(|s| s.to_str()) == Some("yml")
        {
            serde_yaml::to_string(preset)
                .map_err(|e| Error::config(format!("Failed to serialize preset to YAML: {}", e)))?
        } else {
            serde_json::to_string_pretty(preset)
                .map_err(|e| Error::config(format!("Failed to serialize preset to JSON: {}", e)))?
        };

        // Ensure parent directory exists
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent)
                .await
                .map_err(|e| Error::io_with_context("creating preset directory", e.to_string()))?;
        }

        fs::write(output_path, content)
            .await
            .map_err(|e| Error::io_with_context("writing preset file", e.to_string()))?;

        Ok(())
    }

    /// Import a reality preset from a file
    ///
    /// Loads a reality preset from a JSON or YAML file and returns it.
    /// The preset can then be applied to a workspace or the global configuration.
    pub async fn import_reality_preset(&self, input_path: &Path) -> Result<crate::RealityPreset> {
        let content = fs::read_to_string(input_path)
            .await
            .map_err(|e| Error::io_with_context("reading preset file", e.to_string()))?;

        // Determine format from file extension
        let preset = if input_path
            .extension()
            .and_then(|s| s.to_str())
            .map(|ext| ext == "yaml" || ext == "yml")
            .unwrap_or(false)
        {
            serde_yaml::from_str(&content).map_err(|e| {
                Error::config(format!("Failed to deserialize preset from YAML: {}", e))
            })?
        } else {
            serde_json::from_str(&content).map_err(|e| {
                Error::config(format!("Failed to deserialize preset from JSON: {}", e))
            })?
        };

        Ok(preset)
    }

    /// Get the presets directory path
    pub fn presets_dir(&self) -> PathBuf {
        self.base_dir.join("presets")
    }

    /// List all available reality presets
    ///
    /// Scans the presets directory and returns a list of all preset files found.
    pub async fn list_reality_presets(&self) -> Result<Vec<PathBuf>> {
        let presets_dir = self.presets_dir();
        if !presets_dir.exists() {
            return Ok(vec![]);
        }

        let mut presets = Vec::new();
        let mut entries = fs::read_dir(&presets_dir)
            .await
            .map_err(|e| Error::io_with_context("reading presets directory", e.to_string()))?;

        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| Error::io_with_context("reading directory entry", e.to_string()))?
        {
            let path = entry.path();
            if path.is_file() {
                let ext = path.extension().and_then(|s| s.to_str());
                if ext == Some("json") || ext == Some("yaml") || ext == Some("yml") {
                    presets.push(path);
                }
            }
        }

        Ok(presets)
    }

    /// Sanitize filename for filesystem compatibility
    fn sanitize_filename(&self, name: &str) -> String {
        name.chars()
            .map(|c| match c {
                '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
                c if c.is_whitespace() => '_',
                c => c,
            })
            .collect::<String>()
            .to_lowercase()
    }
}

/// Result of syncing a single workspace
#[derive(Debug)]
struct WorkspaceSyncResult {
    /// Number of requests exported
    requests_count: usize,
    /// Number of files created
    files_created: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workspace::{MockRequest, Workspace};
    use crate::HttpMethod;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_workspace_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let persistence = WorkspacePersistence::new(temp_dir.path());

        // Create a test workspace
        let mut workspace = Workspace::new("Test Workspace".to_string());
        let request =
            MockRequest::new(HttpMethod::GET, "/test".to_string(), "Test Request".to_string());
        workspace.add_request(request).unwrap();

        // Save workspace
        persistence.save_workspace(&workspace).await.unwrap();

        // Load workspace
        let loaded = persistence.load_workspace(&workspace.id).await.unwrap();
        assert_eq!(loaded.name, workspace.name);
        assert_eq!(loaded.requests.len(), 1);

        // List workspaces
        let ids = persistence.list_workspace_ids().await.unwrap();
        assert_eq!(ids.len(), 1);
        assert_eq!(ids[0], workspace.id);
    }

    #[tokio::test]
    async fn test_registry_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let persistence = WorkspacePersistence::new(temp_dir.path());

        let mut registry = WorkspaceRegistry::new();

        // Add workspaces
        let workspace1 = Workspace::new("Workspace 1".to_string());
        let workspace2 = Workspace::new("Workspace 2".to_string());

        let id1 = registry.add_workspace(workspace1).unwrap();
        let _id2 = registry.add_workspace(workspace2).unwrap();

        // Set active workspace
        registry.set_active_workspace(Some(id1.clone())).unwrap();

        // Save registry
        persistence.save_full_registry(&registry).await.unwrap();

        // Load registry
        let loaded_registry = persistence.load_full_registry().await.unwrap();

        assert_eq!(loaded_registry.get_workspaces().len(), 2);
        assert_eq!(loaded_registry.get_active_workspace().unwrap().name, "Workspace 1");
    }

    #[tokio::test]
    async fn test_backup_and_restore() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let persistence = WorkspacePersistence::new(temp_dir.path());

        // Create and save workspace
        let workspace = Workspace::new("Test Workspace".to_string());
        persistence.save_workspace(&workspace).await.unwrap();

        // Create backup
        let backup_path = persistence.backup_workspace(&workspace.id, &backup_dir).await.unwrap();
        assert!(backup_path.exists());

        // Delete original
        persistence.delete_workspace(&workspace.id).await.unwrap();
        assert!(persistence.load_workspace(&workspace.id).await.is_err());

        // Restore from backup
        let restored_id = persistence.restore_workspace(&backup_path).await.unwrap();

        // Verify restored workspace
        let restored = persistence.load_workspace(&restored_id).await.unwrap();
        assert_eq!(restored.name, "Test Workspace");
    }

    #[test]
    fn test_workspace_persistence_new() {
        let persistence = WorkspacePersistence::new("/tmp/test");
        assert_eq!(persistence.base_dir, PathBuf::from("/tmp/test"));
    }

    #[test]
    fn test_workspace_persistence_workspace_dir() {
        let persistence = WorkspacePersistence::new("/tmp/test");
        assert_eq!(persistence.workspace_dir(), Path::new("/tmp/test"));
    }

    #[test]
    fn test_workspace_persistence_workspace_file_path() {
        let persistence = WorkspacePersistence::new("/tmp/test");
        let path = persistence.workspace_file_path("workspace-123");
        assert_eq!(path, PathBuf::from("/tmp/test/workspace-123.yaml"));
    }

    #[test]
    fn test_workspace_persistence_registry_file_path() {
        let persistence = WorkspacePersistence::new("/tmp/test");
        let path = persistence.registry_file_path();
        assert_eq!(path, PathBuf::from("/tmp/test/registry.yaml"));
    }

    #[test]
    fn test_workspace_persistence_sync_state_file_path() {
        let persistence = WorkspacePersistence::new("/tmp/test");
        let path = persistence.sync_state_file_path();
        assert_eq!(path, PathBuf::from("/tmp/test/sync_state.yaml"));
    }

    #[test]
    fn test_sync_state_creation() {
        let state = SyncState {
            last_sync_timestamp: Utc::now(),
        };
        assert!(state.last_sync_timestamp <= Utc::now());
    }

    #[test]
    fn test_sync_strategy_variants() {
        let full = SyncStrategy::Full;
        let incremental = SyncStrategy::Incremental;
        let selective = SyncStrategy::Selective(vec!["id1".to_string(), "id2".to_string()]);

        assert_eq!(full, SyncStrategy::Full);
        assert_eq!(incremental, SyncStrategy::Incremental);
        assert_eq!(selective, SyncStrategy::Selective(vec!["id1".to_string(), "id2".to_string()]));
    }

    #[test]
    fn test_directory_structure_variants() {
        let flat = DirectoryStructure::Flat;
        let nested = DirectoryStructure::Nested;
        let grouped = DirectoryStructure::Grouped;

        assert_eq!(flat, DirectoryStructure::Flat);
        assert_eq!(nested, DirectoryStructure::Nested);
        assert_eq!(grouped, DirectoryStructure::Grouped);
    }

    #[test]
    fn test_sync_result_creation() {
        let result = SyncResult {
            synced_workspaces: 5,
            synced_requests: 10,
            files_created: 15,
            target_dir: PathBuf::from("/tmp/sync"),
        };

        assert_eq!(result.synced_workspaces, 5);
        assert_eq!(result.synced_requests, 10);
        assert_eq!(result.files_created, 15);
    }

    #[test]
    fn test_encrypted_export_result_creation() {
        let result = EncryptedExportResult {
            output_path: PathBuf::from("/tmp/export.zip"),
            backup_key: "backup-key-123".to_string(),
            exported_at: Utc::now(),
            workspace_name: "Test Workspace".to_string(),
            encryption_enabled: true,
        };

        assert_eq!(result.workspace_name, "Test Workspace");
        assert!(result.encryption_enabled);
    }

    #[test]
    fn test_encrypted_import_result_creation() {
        let result = EncryptedImportResult {
            workspace_id: "ws-123".to_string(),
            workspace_name: "Imported Workspace".to_string(),
            imported_at: Utc::now(),
            request_count: 5,
            encryption_restored: true,
        };

        assert_eq!(result.workspace_id, "ws-123");
        assert_eq!(result.request_count, 5);
    }

    #[test]
    fn test_security_check_result_creation() {
        let result = SecurityCheckResult {
            workspace_id: "ws-123".to_string(),
            workspace_name: "Test Workspace".to_string(),
            warnings: vec![],
            errors: vec![],
            is_secure: true,
            recommended_actions: vec!["Action 1".to_string()],
        };

        assert_eq!(result.workspace_id, "ws-123");
        assert!(result.is_secure);
    }

    #[test]
    fn test_security_warning_creation() {
        let warning = SecurityWarning {
            field_type: "header".to_string(),
            field_name: "Authorization".to_string(),
            location: "request".to_string(),
            severity: SecuritySeverity::High,
            message: "Sensitive data detected".to_string(),
            suggestion: "Use encryption".to_string(),
        };

        assert_eq!(warning.severity, SecuritySeverity::High);
        assert_eq!(warning.field_name, "Authorization");
    }

    #[test]
    fn test_security_severity_variants() {
        assert_eq!(SecuritySeverity::Low, SecuritySeverity::Low);
        assert_eq!(SecuritySeverity::Medium, SecuritySeverity::Medium);
        assert_eq!(SecuritySeverity::High, SecuritySeverity::High);
        assert_eq!(SecuritySeverity::Critical, SecuritySeverity::Critical);
    }

    #[test]
    fn test_workspace_export_creation() {
        let export = WorkspaceExport {
            metadata: WorkspaceMetadata {
                id: "ws-123".to_string(),
                name: "Test Workspace".to_string(),
                description: None,
                exported_at: Utc::now(),
                request_count: 5,
                folder_count: 2,
            },
            config: WorkspaceConfig {
                auth: None,
                base_url: Some("http://localhost:8080".to_string()),
                variables: HashMap::new(),
                reality_level: None,
                ai_mode: None,
            },
            requests: HashMap::new(),
        };

        assert_eq!(export.metadata.id, "ws-123");
        assert_eq!(export.config.base_url, Some("http://localhost:8080".to_string()));
    }

    #[test]
    fn test_workspace_metadata_creation() {
        let metadata = WorkspaceMetadata {
            id: "ws-123".to_string(),
            name: "Test Workspace".to_string(),
            description: Some("Test description".to_string()),
            exported_at: Utc::now(),
            request_count: 10,
            folder_count: 5,
        };

        assert_eq!(metadata.id, "ws-123");
        assert_eq!(metadata.name, "Test Workspace");
        assert_eq!(metadata.request_count, 10);
        assert_eq!(metadata.folder_count, 5);
    }

    #[test]
    fn test_workspace_config_creation() {
        let config = WorkspaceConfig {
            auth: None,
            base_url: Some("http://localhost:8080".to_string()),
            variables: HashMap::new(),
            reality_level: None,
            ai_mode: None,
        };

        assert_eq!(config.base_url, Some("http://localhost:8080".to_string()));
    }

    #[test]
    fn test_auth_config_creation() {
        let mut params = HashMap::new();
        params.insert("token".to_string(), "token-123".to_string());
        let auth = AuthConfig {
            auth_type: "bearer".to_string(),
            params,
        };

        assert_eq!(auth.auth_type, "bearer");
        assert_eq!(auth.params.get("token"), Some(&"token-123".to_string()));
    }

    #[test]
    fn test_exported_request_creation() {
        let request = ExportedRequest {
            id: "req-123".to_string(),
            name: "Test Request".to_string(),
            method: "GET".to_string(),
            path: "/api/test".to_string(),
            folder_path: "/folder1".to_string(),
            headers: HashMap::new(),
            query_params: HashMap::new(),
            body: None,
            response_status: Some(200),
            response_body: Some("{}".to_string()),
            response_headers: HashMap::new(),
            delay: Some(100),
        };

        assert_eq!(request.id, "req-123");
        assert_eq!(request.method, "GET");
        assert_eq!(request.response_status, Some(200));
    }

    #[test]
    fn test_serializable_workspace_registry_creation() {
        let serializable = SerializableWorkspaceRegistry {
            workspaces: vec![],
            active_workspace: Some("ws-123".to_string()),
        };

        assert_eq!(serializable.active_workspace, Some("ws-123".to_string()));
        assert!(serializable.workspaces.is_empty());
    }

    #[test]
    fn test_serializable_workspace_registry_serialization() {
        let serializable = SerializableWorkspaceRegistry {
            workspaces: vec![],
            active_workspace: Some("ws-123".to_string()),
        };

        let json = serde_json::to_string(&serializable).unwrap();
        assert!(json.contains("ws-123"));
    }

    #[test]
    fn test_sync_state_clone() {
        let state1 = SyncState {
            last_sync_timestamp: Utc::now(),
        };
        let state2 = state1.clone();
        assert_eq!(state1.last_sync_timestamp, state2.last_sync_timestamp);
    }

    #[test]
    fn test_sync_state_debug() {
        let state = SyncState {
            last_sync_timestamp: Utc::now(),
        };
        let debug_str = format!("{:?}", state);
        assert!(debug_str.contains("SyncState"));
    }

    #[test]
    fn test_sync_strategy_clone() {
        let strategy1 = SyncStrategy::Selective(vec!["id1".to_string()]);
        let strategy2 = strategy1.clone();
        assert_eq!(strategy1, strategy2);
    }

    #[test]
    fn test_directory_structure_clone() {
        let structure1 = DirectoryStructure::Nested;
        let structure2 = structure1.clone();
        assert_eq!(structure1, structure2);
    }

    #[test]
    fn test_sync_result_clone() {
        let result1 = SyncResult {
            synced_workspaces: 1,
            synced_requests: 2,
            files_created: 3,
            target_dir: PathBuf::from("/tmp"),
        };
        let result2 = result1.clone();
        assert_eq!(result1.synced_workspaces, result2.synced_workspaces);
    }

    #[test]
    fn test_encrypted_export_result_clone() {
        let result1 = EncryptedExportResult {
            output_path: PathBuf::from("/tmp/export.zip"),
            backup_key: "key".to_string(),
            exported_at: Utc::now(),
            workspace_name: "Test".to_string(),
            encryption_enabled: true,
        };
        let result2 = result1.clone();
        assert_eq!(result1.workspace_name, result2.workspace_name);
    }

    #[test]
    fn test_encrypted_import_result_clone() {
        let result1 = EncryptedImportResult {
            workspace_id: "ws-1".to_string(),
            workspace_name: "Test".to_string(),
            imported_at: Utc::now(),
            request_count: 5,
            encryption_restored: true,
        };
        let result2 = result1.clone();
        assert_eq!(result1.workspace_id, result2.workspace_id);
    }

    #[test]
    fn test_security_check_result_clone() {
        let result1 = SecurityCheckResult {
            workspace_id: "ws-1".to_string(),
            workspace_name: "Test".to_string(),
            warnings: vec![],
            errors: vec![],
            is_secure: true,
            recommended_actions: vec![],
        };
        let result2 = result1.clone();
        assert_eq!(result1.workspace_id, result2.workspace_id);
    }

    #[test]
    fn test_security_warning_clone() {
        let warning1 = SecurityWarning {
            field_type: "header".to_string(),
            field_name: "Auth".to_string(),
            location: "request".to_string(),
            severity: SecuritySeverity::High,
            message: "Test".to_string(),
            suggestion: "Fix".to_string(),
        };
        let warning2 = warning1.clone();
        assert_eq!(warning1.field_name, warning2.field_name);
    }

    #[test]
    fn test_security_severity_clone() {
        let severity1 = SecuritySeverity::Critical;
        let severity2 = severity1.clone();
        assert_eq!(severity1, severity2);
    }

    #[test]
    fn test_workspace_export_clone() {
        let export1 = WorkspaceExport {
            metadata: WorkspaceMetadata {
                id: "ws-1".to_string(),
                name: "Test".to_string(),
                description: None,
                exported_at: Utc::now(),
                request_count: 0,
                folder_count: 0,
            },
            config: WorkspaceConfig {
                auth: None,
                base_url: None,
                variables: HashMap::new(),
                reality_level: None,
                ai_mode: None,
            },
            requests: HashMap::new(),
        };
        let export2 = export1.clone();
        assert_eq!(export1.metadata.id, export2.metadata.id);
    }

    #[test]
    fn test_workspace_metadata_clone() {
        let metadata1 = WorkspaceMetadata {
            id: "ws-1".to_string(),
            name: "Test".to_string(),
            description: None,
            exported_at: Utc::now(),
            request_count: 0,
            folder_count: 0,
        };
        let metadata2 = metadata1.clone();
        assert_eq!(metadata1.id, metadata2.id);
    }

    #[test]
    fn test_workspace_config_clone() {
        let config1 = WorkspaceConfig {
            auth: None,
            base_url: Some("http://localhost".to_string()),
            variables: HashMap::new(),
            reality_level: None,
            ai_mode: None,
        };
        let config2 = config1.clone();
        assert_eq!(config1.base_url, config2.base_url);
    }

    #[test]
    fn test_auth_config_clone() {
        let mut params = HashMap::new();
        params.insert("key".to_string(), "value".to_string());
        let auth1 = AuthConfig {
            auth_type: "bearer".to_string(),
            params: params.clone(),
        };
        let auth2 = auth1.clone();
        assert_eq!(auth1.auth_type, auth2.auth_type);
    }

    #[test]
    fn test_exported_request_clone() {
        let request1 = ExportedRequest {
            id: "req-1".to_string(),
            name: "Test".to_string(),
            method: "GET".to_string(),
            path: "/test".to_string(),
            folder_path: "/".to_string(),
            headers: HashMap::new(),
            query_params: HashMap::new(),
            body: None,
            response_status: Some(200),
            response_body: None,
            response_headers: HashMap::new(),
            delay: None,
        };
        let request2 = request1.clone();
        assert_eq!(request1.id, request2.id);
    }

    #[test]
    fn test_sync_result_debug() {
        let result = SyncResult {
            synced_workspaces: 1,
            synced_requests: 2,
            files_created: 3,
            target_dir: PathBuf::from("/tmp"),
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("SyncResult"));
    }

    #[test]
    fn test_encrypted_export_result_debug() {
        let result = EncryptedExportResult {
            output_path: PathBuf::from("/tmp/export.zip"),
            backup_key: "key".to_string(),
            exported_at: Utc::now(),
            workspace_name: "Test".to_string(),
            encryption_enabled: true,
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("EncryptedExportResult"));
    }

    #[test]
    fn test_encrypted_import_result_debug() {
        let result = EncryptedImportResult {
            workspace_id: "ws-1".to_string(),
            workspace_name: "Test".to_string(),
            imported_at: Utc::now(),
            request_count: 5,
            encryption_restored: true,
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("EncryptedImportResult"));
    }

    #[test]
    fn test_security_check_result_debug() {
        let result = SecurityCheckResult {
            workspace_id: "ws-1".to_string(),
            workspace_name: "Test".to_string(),
            warnings: vec![],
            errors: vec![],
            is_secure: true,
            recommended_actions: vec![],
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("SecurityCheckResult"));
    }

    #[test]
    fn test_security_warning_debug() {
        let warning = SecurityWarning {
            field_type: "header".to_string(),
            field_name: "Auth".to_string(),
            location: "request".to_string(),
            severity: SecuritySeverity::High,
            message: "Test".to_string(),
            suggestion: "Fix".to_string(),
        };
        let debug_str = format!("{:?}", warning);
        assert!(debug_str.contains("SecurityWarning"));
    }

    #[test]
    fn test_security_severity_debug() {
        let severity = SecuritySeverity::Critical;
        let debug_str = format!("{:?}", severity);
        assert!(debug_str.contains("Critical"));
    }

    #[test]
    fn test_workspace_export_debug() {
        let export = WorkspaceExport {
            metadata: WorkspaceMetadata {
                id: "ws-1".to_string(),
                name: "Test".to_string(),
                description: None,
                exported_at: Utc::now(),
                request_count: 0,
                folder_count: 0,
            },
            config: WorkspaceConfig {
                auth: None,
                base_url: None,
                variables: HashMap::new(),
                reality_level: None,
                ai_mode: None,
            },
            requests: HashMap::new(),
        };
        let debug_str = format!("{:?}", export);
        assert!(debug_str.contains("WorkspaceExport"));
    }

    #[test]
    fn test_workspace_metadata_debug() {
        let metadata = WorkspaceMetadata {
            id: "ws-1".to_string(),
            name: "Test".to_string(),
            description: None,
            exported_at: Utc::now(),
            request_count: 0,
            folder_count: 0,
        };
        let debug_str = format!("{:?}", metadata);
        assert!(debug_str.contains("WorkspaceMetadata"));
    }

    #[test]
    fn test_workspace_config_debug() {
        let config = WorkspaceConfig {
            auth: None,
            base_url: None,
            variables: HashMap::new(),
            reality_level: None,
            ai_mode: None,
        };
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("WorkspaceConfig"));
    }

    #[test]
    fn test_auth_config_debug() {
        let auth = AuthConfig {
            auth_type: "bearer".to_string(),
            params: HashMap::new(),
        };
        let debug_str = format!("{:?}", auth);
        assert!(debug_str.contains("AuthConfig"));
    }

    #[test]
    fn test_exported_request_debug() {
        let request = ExportedRequest {
            id: "req-1".to_string(),
            name: "Test".to_string(),
            method: "GET".to_string(),
            path: "/test".to_string(),
            folder_path: "/".to_string(),
            headers: HashMap::new(),
            query_params: HashMap::new(),
            body: None,
            response_status: None,
            response_body: None,
            response_headers: HashMap::new(),
            delay: None,
        };
        let debug_str = format!("{:?}", request);
        assert!(debug_str.contains("ExportedRequest"));
    }

    #[test]
    fn test_sync_strategy_debug() {
        let strategy = SyncStrategy::Full;
        let debug_str = format!("{:?}", strategy);
        assert!(debug_str.contains("Full") || debug_str.contains("SyncStrategy"));
    }

    #[test]
    fn test_directory_structure_debug() {
        let structure = DirectoryStructure::Flat;
        let debug_str = format!("{:?}", structure);
        assert!(debug_str.contains("Flat") || debug_str.contains("DirectoryStructure"));
    }
}