mockforge-ui 0.3.88

Admin UI for MockForge - web-based interface for managing mock servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
//! Request handlers for the admin UI
//!
//! This module has been refactored into sub-modules for better organization:
//! - assets: Static asset serving
//! - admin: Admin dashboard and server management
//! - workspace: Workspace management operations
//! - plugin: Plugin management operations
//! - sync: Synchronization operations
//! - import: Data import operations
//! - fixtures: Fixture management operations

use axum::{
    extract::{Path, Query, State},
    http::{self, StatusCode},
    response::{
        sse::{Event, Sse},
        Html, IntoResponse, Json,
    },
};
use chrono::Utc;
use futures_util::stream::{self, Stream};
use mockforge_core::{Error, Result};
use mockforge_plugin_loader::PluginRegistry;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use std::convert::Infallible;
use std::process::Command;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use sysinfo::System;
use tokio::sync::RwLock;

// Import all types from models
use crate::models::{
    ApiResponse, ConfigUpdate, DashboardData, DashboardSystemInfo, FaultConfig, HealthCheck,
    LatencyProfile, LogFilter, MetricsData, ProxyConfig, RequestLog, RouteInfo, ServerInfo,
    ServerStatus, SimpleMetricsData, SystemInfo, TrafficShapingConfig, ValidationSettings,
    ValidationUpdate,
};

// Import import types from core
use mockforge_core::workspace_import::{ImportResponse, ImportRoute};
use mockforge_plugin_loader::{
    GitPluginConfig, GitPluginLoader, PluginLoader, PluginLoaderConfig, PluginSource,
    RemotePluginConfig, RemotePluginLoader,
};

// Handler sub-modules
pub mod admin;
pub mod ai_studio;
pub mod analytics;
pub mod analytics_stream;
pub mod analytics_v2;
pub mod assets;
pub mod behavioral_cloning;
pub mod chains;
pub mod chaos_api;
pub mod community;
pub mod contract_diff;
pub mod coverage_metrics;
pub mod failure_analysis;
pub mod federation_api;
pub mod graph;
pub mod health;
pub mod migration;
pub mod pillar_analytics;
pub mod playground;
pub mod plugin;
pub mod promotions;
pub mod protocol_contracts;
pub mod recorder_api;
pub mod vbr_api;
pub mod verification;
pub mod voice;
pub mod workspaces;
pub mod world_state_proxy;

// Re-export commonly used types
pub use assets::*;
pub use chains::*;
pub use graph::*;
pub use migration::*;
pub use plugin::*;

// Import workspace persistence
use mockforge_core::workspace_import::WorkspaceImportConfig;
use mockforge_core::workspace_persistence::WorkspacePersistence;

/// Request metrics for tracking
#[derive(Debug, Clone, Default)]
pub struct RequestMetrics {
    /// Total requests served
    pub total_requests: u64,
    /// Active connections
    pub active_connections: u64,
    /// Requests by endpoint
    pub requests_by_endpoint: HashMap<String, u64>,
    /// Response times (last N measurements)
    pub response_times: Vec<u64>,
    /// Response times by endpoint (last N measurements per endpoint)
    pub response_times_by_endpoint: HashMap<String, Vec<u64>>,
    /// Error count by endpoint
    pub errors_by_endpoint: HashMap<String, u64>,
    /// Last request timestamp by endpoint
    pub last_request_by_endpoint: HashMap<String, chrono::DateTime<Utc>>,
}

/// System metrics
#[derive(Debug, Clone)]
pub struct SystemMetrics {
    /// Memory usage in MB
    pub memory_usage_mb: u64,
    /// CPU usage percentage
    pub cpu_usage_percent: f64,
    /// Active threads
    pub active_threads: u32,
}

/// Time series data point
#[derive(Debug, Clone)]
pub struct TimeSeriesPoint {
    /// Timestamp
    pub timestamp: chrono::DateTime<Utc>,
    /// Value
    pub value: f64,
}

/// Time series data for tracking metrics over time
#[derive(Debug, Clone, Default)]
pub struct TimeSeriesData {
    /// Memory usage over time
    pub memory_usage: Vec<TimeSeriesPoint>,
    /// CPU usage over time
    pub cpu_usage: Vec<TimeSeriesPoint>,
    /// Request count over time
    pub request_count: Vec<TimeSeriesPoint>,
    /// Response time over time
    pub response_time: Vec<TimeSeriesPoint>,
}

/// Restart status tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestartStatus {
    /// Whether a restart is currently in progress
    pub in_progress: bool,
    /// Timestamp when restart was initiated
    pub initiated_at: Option<chrono::DateTime<Utc>>,
    /// Restart reason/message
    pub reason: Option<String>,
    /// Whether restart was successful
    pub success: Option<bool>,
}

/// Fixture metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureInfo {
    /// Unique identifier for the fixture
    pub id: String,
    /// Protocol type (http, websocket, grpc)
    pub protocol: String,
    /// HTTP method or operation type
    pub method: String,
    /// Request path
    pub path: String,
    /// When the fixture was saved
    pub saved_at: chrono::DateTime<Utc>,
    /// File size in bytes
    pub file_size: u64,
    /// File path relative to fixtures directory
    pub file_path: String,
    /// Request fingerprint hash
    pub fingerprint: String,
    /// Additional metadata from the fixture file
    pub metadata: serde_json::Value,
}

/// Smoke test result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmokeTestResult {
    /// Test ID
    pub id: String,
    /// Test name
    pub name: String,
    /// HTTP method
    pub method: String,
    /// Request path
    pub path: String,
    /// Test description
    pub description: String,
    /// When the test was last run
    pub last_run: Option<chrono::DateTime<Utc>>,
    /// Test status (passed, failed, running, pending)
    pub status: String,
    /// Response time in milliseconds
    pub response_time_ms: Option<u64>,
    /// Error message if test failed
    pub error_message: Option<String>,
    /// HTTP status code received
    pub status_code: Option<u16>,
    /// Test duration in seconds
    pub duration_seconds: Option<f64>,
}

/// Smoke test execution context
#[derive(Debug, Clone)]
pub struct SmokeTestContext {
    /// Base URL for the service being tested
    pub base_url: String,
    /// Timeout for individual tests
    pub timeout_seconds: u64,
    /// Whether to run tests in parallel
    pub parallel: bool,
}

/// Configuration state
#[derive(Debug, Clone, Serialize)]
pub struct ConfigurationState {
    /// Latency profile
    pub latency_profile: LatencyProfile,
    /// Fault configuration
    pub fault_config: FaultConfig,
    /// Proxy configuration
    pub proxy_config: ProxyConfig,
    /// Validation settings
    pub validation_settings: ValidationSettings,
    /// Traffic shaping settings
    pub traffic_shaping: TrafficShapingConfig,
}

/// Import history entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportHistoryEntry {
    /// Unique ID for the import
    pub id: String,
    /// Import format (postman, insomnia, curl)
    pub format: String,
    /// Timestamp of the import
    pub timestamp: chrono::DateTime<Utc>,
    /// Number of routes imported
    pub routes_count: usize,
    /// Number of variables imported
    pub variables_count: usize,
    /// Number of warnings
    pub warnings_count: usize,
    /// Whether the import was successful
    pub success: bool,
    /// Filename of the imported file
    pub filename: Option<String>,
    /// Environment used
    pub environment: Option<String>,
    /// Base URL used
    pub base_url: Option<String>,
    /// Error message if failed
    pub error_message: Option<String>,
}

/// Shared state for the admin UI
#[derive(Clone)]
pub struct AdminState {
    /// HTTP server address
    pub http_server_addr: Option<std::net::SocketAddr>,
    /// WebSocket server address
    pub ws_server_addr: Option<std::net::SocketAddr>,
    /// gRPC server address
    pub grpc_server_addr: Option<std::net::SocketAddr>,
    /// GraphQL server address
    pub graphql_server_addr: Option<std::net::SocketAddr>,
    /// Whether API endpoints are enabled
    pub api_enabled: bool,
    /// Admin server port
    pub admin_port: u16,
    /// Start time
    pub start_time: chrono::DateTime<Utc>,
    /// Request metrics (protected by RwLock)
    pub metrics: Arc<RwLock<RequestMetrics>>,
    /// System metrics (protected by RwLock)
    pub system_metrics: Arc<RwLock<SystemMetrics>>,
    /// Configuration (protected by RwLock)
    pub config: Arc<RwLock<ConfigurationState>>,
    /// Request logs (protected by RwLock)
    pub logs: Arc<RwLock<Vec<RequestLog>>>,
    /// Time series data (protected by RwLock)
    pub time_series: Arc<RwLock<TimeSeriesData>>,
    /// Restart status (protected by RwLock)
    pub restart_status: Arc<RwLock<RestartStatus>>,
    /// Smoke test results (protected by RwLock)
    pub smoke_test_results: Arc<RwLock<Vec<SmokeTestResult>>>,
    /// Import history (protected by RwLock)
    pub import_history: Arc<RwLock<Vec<ImportHistoryEntry>>>,
    /// Workspace persistence
    pub workspace_persistence: Arc<WorkspacePersistence>,
    /// Plugin registry (protected by RwLock)
    pub plugin_registry: Arc<RwLock<PluginRegistry>>,
    /// Reality engine for managing realism levels
    pub reality_engine: Arc<RwLock<mockforge_core::RealityEngine>>,
    /// Reality Continuum engine for blending mock and real data sources
    pub continuum_engine: Arc<RwLock<mockforge_core::RealityContinuumEngine>>,
    /// Chaos API state for hot-reload support (optional)
    /// Contains config that can be updated at runtime
    pub chaos_api_state: Option<Arc<mockforge_chaos::api::ChaosApiState>>,
    /// Latency injector for HTTP middleware (optional)
    /// Allows updating latency profile at runtime
    pub latency_injector: Option<Arc<RwLock<mockforge_core::latency::LatencyInjector>>>,
    /// MockAI instance (optional)
    /// Allows updating MockAI configuration at runtime
    pub mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
    /// Traffic recorder (optional)
    pub recorder: Option<Arc<mockforge_recorder::Recorder>>,
    /// Federation instance (optional)
    pub federation: Option<Arc<mockforge_federation::Federation>>,
    /// VBR engine (optional)
    pub vbr_engine: Option<Arc<mockforge_vbr::VbrEngine>>,
}

impl AdminState {
    /// Start system monitoring background task
    pub async fn start_system_monitoring(&self) {
        let state_clone = self.clone();
        tokio::spawn(async move {
            let mut sys = System::new_all();
            let mut refresh_count = 0u64;

            tracing::info!("Starting system monitoring background task");

            loop {
                // Refresh system information
                sys.refresh_all();

                // Get CPU usage
                let cpu_usage = sys.global_cpu_usage();

                // Get memory usage
                let _total_memory = sys.total_memory() as f64;
                let used_memory = sys.used_memory() as f64;
                let memory_usage_mb = used_memory / 1024.0 / 1024.0;

                // Get thread count (use available CPU cores as approximate measure)
                let active_threads = sys.cpus().len() as u32;

                // Update system metrics
                let memory_mb_u64 = memory_usage_mb as u64;

                // Only log every 10 refreshes to avoid spam
                if refresh_count.is_multiple_of(10) {
                    tracing::debug!(
                        "System metrics updated: CPU={:.1}%, Mem={}MB, Threads={}",
                        cpu_usage,
                        memory_mb_u64,
                        active_threads
                    );
                }

                state_clone
                    .update_system_metrics(memory_mb_u64, cpu_usage as f64, active_threads)
                    .await;

                refresh_count += 1;

                // Sleep for 10 seconds between updates
                tokio::time::sleep(Duration::from_secs(10)).await;
            }
        });
    }

    /// Create new admin state
    ///
    /// # Arguments
    /// * `http_server_addr` - HTTP server address
    /// * `ws_server_addr` - WebSocket server address
    /// * `grpc_server_addr` - gRPC server address
    /// * `graphql_server_addr` - GraphQL server address
    /// * `api_enabled` - Whether API endpoints are enabled
    /// * `admin_port` - Admin server port
    /// * `chaos_api_state` - Optional chaos API state for hot-reload support
    /// * `latency_injector` - Optional latency injector for hot-reload support
    /// * `mockai` - Optional MockAI instance for hot-reload support
    /// * `continuum_config` - Optional Reality Continuum configuration
    /// * `virtual_clock` - Optional virtual clock for time-based progression
    /// * `recorder` - Optional traffic recorder
    /// * `federation` - Optional federation instance
    /// * `vbr_engine` - Optional VBR engine
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        http_server_addr: Option<std::net::SocketAddr>,
        ws_server_addr: Option<std::net::SocketAddr>,
        grpc_server_addr: Option<std::net::SocketAddr>,
        graphql_server_addr: Option<std::net::SocketAddr>,
        api_enabled: bool,
        admin_port: u16,
        chaos_api_state: Option<Arc<mockforge_chaos::api::ChaosApiState>>,
        latency_injector: Option<Arc<RwLock<mockforge_core::latency::LatencyInjector>>>,
        mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
        continuum_config: Option<mockforge_core::ContinuumConfig>,
        virtual_clock: Option<Arc<mockforge_core::VirtualClock>>,
        recorder: Option<Arc<mockforge_recorder::Recorder>>,
        federation: Option<Arc<mockforge_federation::Federation>>,
        vbr_engine: Option<Arc<mockforge_vbr::VbrEngine>>,
    ) -> Self {
        let start_time = Utc::now();

        Self {
            http_server_addr,
            ws_server_addr,
            grpc_server_addr,
            graphql_server_addr,
            api_enabled,
            admin_port,
            start_time,
            metrics: Arc::new(RwLock::new(RequestMetrics::default())),
            system_metrics: Arc::new(RwLock::new(SystemMetrics {
                memory_usage_mb: 0,
                cpu_usage_percent: 0.0,
                active_threads: 0,
            })),
            config: Arc::new(RwLock::new(ConfigurationState {
                latency_profile: LatencyProfile {
                    name: "default".to_string(),
                    base_ms: 50,
                    jitter_ms: 20,
                    tag_overrides: HashMap::new(),
                },
                fault_config: FaultConfig {
                    enabled: false,
                    failure_rate: 0.0,
                    status_codes: vec![500, 502, 503],
                    active_failures: 0,
                },
                proxy_config: ProxyConfig {
                    enabled: false,
                    upstream_url: None,
                    timeout_seconds: 30,
                    requests_proxied: 0,
                },
                validation_settings: ValidationSettings {
                    mode: "enforce".to_string(),
                    aggregate_errors: true,
                    validate_responses: false,
                    overrides: HashMap::new(),
                },
                traffic_shaping: TrafficShapingConfig {
                    enabled: false,
                    bandwidth: crate::models::BandwidthConfig {
                        enabled: false,
                        max_bytes_per_sec: 1_048_576,
                        burst_capacity_bytes: 10_485_760,
                        tag_overrides: HashMap::new(),
                    },
                    burst_loss: crate::models::BurstLossConfig {
                        enabled: false,
                        burst_probability: 0.1,
                        burst_duration_ms: 5000,
                        loss_rate_during_burst: 0.5,
                        recovery_time_ms: 30000,
                        tag_overrides: HashMap::new(),
                    },
                },
            })),
            logs: Arc::new(RwLock::new(Vec::new())),
            time_series: Arc::new(RwLock::new(TimeSeriesData::default())),
            restart_status: Arc::new(RwLock::new(RestartStatus {
                in_progress: false,
                initiated_at: None,
                reason: None,
                success: None,
            })),
            smoke_test_results: Arc::new(RwLock::new(Vec::new())),
            import_history: Arc::new(RwLock::new(Vec::new())),
            workspace_persistence: Arc::new(WorkspacePersistence::new("./workspaces")),
            plugin_registry: Arc::new(RwLock::new(PluginRegistry::new())),
            reality_engine: Arc::new(RwLock::new(mockforge_core::RealityEngine::new())),
            continuum_engine: Arc::new(RwLock::new({
                let config = continuum_config.unwrap_or_default();
                if let Some(clock) = virtual_clock {
                    mockforge_core::RealityContinuumEngine::with_virtual_clock(config, clock)
                } else {
                    mockforge_core::RealityContinuumEngine::new(config)
                }
            })),
            chaos_api_state,
            latency_injector,
            mockai,
            recorder,
            federation,
            vbr_engine,
        }
    }

    /// Record a request
    pub async fn record_request(
        &self,
        method: &str,
        path: &str,
        status_code: u16,
        response_time_ms: u64,
        error: Option<String>,
    ) {
        let mut metrics = self.metrics.write().await;

        metrics.total_requests += 1;
        let endpoint = format!("{} {}", method, path);
        *metrics.requests_by_endpoint.entry(endpoint.clone()).or_insert(0) += 1;

        if status_code >= 400 {
            *metrics.errors_by_endpoint.entry(endpoint.clone()).or_insert(0) += 1;
        }

        // Keep only last 100 response times globally
        metrics.response_times.push(response_time_ms);
        if metrics.response_times.len() > 100 {
            metrics.response_times.remove(0);
        }

        // Keep only last 50 response times per endpoint
        let endpoint_times = metrics
            .response_times_by_endpoint
            .entry(endpoint.clone())
            .or_insert_with(Vec::new);
        endpoint_times.push(response_time_ms);
        if endpoint_times.len() > 50 {
            endpoint_times.remove(0);
        }

        // Update last request timestamp for this endpoint
        metrics.last_request_by_endpoint.insert(endpoint, Utc::now());

        // Capture total_requests before releasing the lock
        let total_requests = metrics.total_requests;

        // Release metrics lock before acquiring other locks
        drop(metrics);

        // Update time series data for request count and response time
        self.update_time_series_on_request(response_time_ms, total_requests).await;

        // Record the log
        let mut logs = self.logs.write().await;
        let log_entry = RequestLog {
            id: format!("req_{}", total_requests),
            timestamp: Utc::now(),
            method: method.to_string(),
            path: path.to_string(),
            status_code,
            response_time_ms,
            client_ip: None,
            user_agent: None,
            headers: HashMap::new(),
            response_size_bytes: 0,
            error_message: error,
        };

        logs.push(log_entry);

        // Keep only last 1000 logs
        if logs.len() > 1000 {
            logs.remove(0);
        }
    }

    /// Get current metrics
    pub async fn get_metrics(&self) -> RequestMetrics {
        self.metrics.read().await.clone()
    }

    /// Update system metrics
    pub async fn update_system_metrics(&self, memory_mb: u64, cpu_percent: f64, threads: u32) {
        let mut system_metrics = self.system_metrics.write().await;
        system_metrics.memory_usage_mb = memory_mb;
        system_metrics.cpu_usage_percent = cpu_percent;
        system_metrics.active_threads = threads;

        // Update time series data
        self.update_time_series_data(memory_mb as f64, cpu_percent).await;
    }

    /// Update time series data with new metrics
    async fn update_time_series_data(&self, memory_mb: f64, cpu_percent: f64) {
        let now = Utc::now();
        let mut time_series = self.time_series.write().await;

        // Add memory usage data point
        time_series.memory_usage.push(TimeSeriesPoint {
            timestamp: now,
            value: memory_mb,
        });

        // Add CPU usage data point
        time_series.cpu_usage.push(TimeSeriesPoint {
            timestamp: now,
            value: cpu_percent,
        });

        // Add request count data point (from current metrics)
        let metrics = self.metrics.read().await;
        time_series.request_count.push(TimeSeriesPoint {
            timestamp: now,
            value: metrics.total_requests as f64,
        });

        // Add average response time data point
        let avg_response_time = if !metrics.response_times.is_empty() {
            metrics.response_times.iter().sum::<u64>() as f64 / metrics.response_times.len() as f64
        } else {
            0.0
        };
        time_series.response_time.push(TimeSeriesPoint {
            timestamp: now,
            value: avg_response_time,
        });

        // Keep only last 100 data points for each metric to prevent memory bloat
        const MAX_POINTS: usize = 100;
        if time_series.memory_usage.len() > MAX_POINTS {
            time_series.memory_usage.remove(0);
        }
        if time_series.cpu_usage.len() > MAX_POINTS {
            time_series.cpu_usage.remove(0);
        }
        if time_series.request_count.len() > MAX_POINTS {
            time_series.request_count.remove(0);
        }
        if time_series.response_time.len() > MAX_POINTS {
            time_series.response_time.remove(0);
        }
    }

    /// Get system metrics
    pub async fn get_system_metrics(&self) -> SystemMetrics {
        self.system_metrics.read().await.clone()
    }

    /// Get time series data
    pub async fn get_time_series_data(&self) -> TimeSeriesData {
        self.time_series.read().await.clone()
    }

    /// Get restart status
    pub async fn get_restart_status(&self) -> RestartStatus {
        self.restart_status.read().await.clone()
    }

    /// Initiate server restart
    pub async fn initiate_restart(&self, reason: String) -> Result<()> {
        let mut status = self.restart_status.write().await;

        if status.in_progress {
            return Err(Error::generic("Restart already in progress".to_string()));
        }

        status.in_progress = true;
        status.initiated_at = Some(Utc::now());
        status.reason = Some(reason);
        status.success = None;

        Ok(())
    }

    /// Complete restart (success or failure)
    pub async fn complete_restart(&self, success: bool) {
        let mut status = self.restart_status.write().await;
        status.in_progress = false;
        status.success = Some(success);
    }

    /// Get smoke test results
    pub async fn get_smoke_test_results(&self) -> Vec<SmokeTestResult> {
        self.smoke_test_results.read().await.clone()
    }

    /// Update smoke test result
    pub async fn update_smoke_test_result(&self, result: SmokeTestResult) {
        let mut results = self.smoke_test_results.write().await;

        // Find existing result by ID and update, or add new one
        if let Some(existing) = results.iter_mut().find(|r| r.id == result.id) {
            *existing = result;
        } else {
            results.push(result);
        }

        // Keep only last 100 test results
        if results.len() > 100 {
            results.remove(0);
        }
    }

    /// Clear all smoke test results
    pub async fn clear_smoke_test_results(&self) {
        let mut results = self.smoke_test_results.write().await;
        results.clear();
    }

    /// Update time series data when a request is recorded
    async fn update_time_series_on_request(&self, response_time_ms: u64, total_requests: u64) {
        let now = Utc::now();
        let mut time_series = self.time_series.write().await;

        // Add request count data point
        time_series.request_count.push(TimeSeriesPoint {
            timestamp: now,
            value: total_requests as f64,
        });

        // Add response time data point
        time_series.response_time.push(TimeSeriesPoint {
            timestamp: now,
            value: response_time_ms as f64,
        });

        // Keep only last 100 data points for each metric to prevent memory bloat
        const MAX_POINTS: usize = 100;
        if time_series.request_count.len() > MAX_POINTS {
            time_series.request_count.remove(0);
        }
        if time_series.response_time.len() > MAX_POINTS {
            time_series.response_time.remove(0);
        }
    }

    /// Get current configuration
    pub async fn get_config(&self) -> ConfigurationState {
        self.config.read().await.clone()
    }

    /// Update latency configuration
    pub async fn update_latency_config(
        &self,
        base_ms: u64,
        jitter_ms: u64,
        tag_overrides: HashMap<String, u64>,
    ) {
        let mut config = self.config.write().await;
        config.latency_profile.base_ms = base_ms;
        config.latency_profile.jitter_ms = jitter_ms;
        config.latency_profile.tag_overrides = tag_overrides;
    }

    /// Update fault configuration
    pub async fn update_fault_config(
        &self,
        enabled: bool,
        failure_rate: f64,
        status_codes: Vec<u16>,
    ) {
        let mut config = self.config.write().await;
        config.fault_config.enabled = enabled;
        config.fault_config.failure_rate = failure_rate;
        config.fault_config.status_codes = status_codes;
    }

    /// Update proxy configuration
    pub async fn update_proxy_config(
        &self,
        enabled: bool,
        upstream_url: Option<String>,
        timeout_seconds: u64,
    ) {
        let mut config = self.config.write().await;
        config.proxy_config.enabled = enabled;
        config.proxy_config.upstream_url = upstream_url;
        config.proxy_config.timeout_seconds = timeout_seconds;
    }

    /// Update validation settings
    pub async fn update_validation_config(
        &self,
        mode: String,
        aggregate_errors: bool,
        validate_responses: bool,
        overrides: HashMap<String, String>,
    ) {
        let mut config = self.config.write().await;
        config.validation_settings.mode = mode;
        config.validation_settings.aggregate_errors = aggregate_errors;
        config.validation_settings.validate_responses = validate_responses;
        config.validation_settings.overrides = overrides;
    }

    /// Get filtered logs
    pub async fn get_logs_filtered(&self, filter: &LogFilter) -> Vec<RequestLog> {
        let logs = self.logs.read().await;

        logs.iter()
            .rev() // Most recent first
            .filter(|log| {
                if let Some(ref method) = filter.method {
                    if log.method != *method {
                        return false;
                    }
                }
                if let Some(ref path_pattern) = filter.path_pattern {
                    if !log.path.contains(path_pattern) {
                        return false;
                    }
                }
                if let Some(status) = filter.status_code {
                    if log.status_code != status {
                        return false;
                    }
                }
                true
            })
            .take(filter.limit.unwrap_or(100))
            .cloned()
            .collect()
    }

    /// Clear all logs
    pub async fn clear_logs(&self) {
        let mut logs = self.logs.write().await;
        logs.clear();
    }
}

/// Serve the main admin interface
pub async fn serve_admin_html() -> Html<&'static str> {
    Html(crate::get_admin_html())
}

/// Serve admin CSS
pub async fn serve_admin_css() -> ([(http::HeaderName, &'static str); 1], &'static str) {
    ([(http::header::CONTENT_TYPE, "text/css")], crate::get_admin_css())
}

/// Serve admin JavaScript
pub async fn serve_admin_js() -> ([(http::HeaderName, &'static str); 1], &'static str) {
    ([(http::header::CONTENT_TYPE, "application/javascript")], crate::get_admin_js())
}

/// Get dashboard data
pub async fn get_dashboard(State(state): State<AdminState>) -> Json<ApiResponse<DashboardData>> {
    let uptime = Utc::now().signed_duration_since(state.start_time).num_seconds() as u64;

    // Get system metrics from state
    let system_metrics = state.get_system_metrics().await;
    let _config = state.get_config().await;

    // Get recent logs and calculate metrics from centralized logger
    let (recent_logs, calculated_metrics): (Vec<RequestLog>, RequestMetrics) =
        if let Some(global_logger) = mockforge_core::get_global_logger() {
            // Get all logs to calculate metrics
            let all_logs = global_logger.get_recent_logs(None).await;
            let recent_logs_subset = global_logger.get_recent_logs(Some(20)).await;

            // Calculate metrics from logs
            let total_requests = all_logs.len() as u64;
            let mut requests_by_endpoint = HashMap::new();
            let mut errors_by_endpoint = HashMap::new();
            let mut response_times = Vec::new();
            let mut last_request_by_endpoint = HashMap::new();

            for log in &all_logs {
                let endpoint_key = format!("{} {}", log.method, log.path);
                *requests_by_endpoint.entry(endpoint_key.clone()).or_insert(0) += 1;

                if log.status_code >= 400 {
                    *errors_by_endpoint.entry(endpoint_key.clone()).or_insert(0) += 1;
                }

                response_times.push(log.response_time_ms);
                last_request_by_endpoint.insert(endpoint_key, log.timestamp);
            }

            let calculated_metrics = RequestMetrics {
                total_requests,
                active_connections: 0, // We don't track this from logs
                requests_by_endpoint,
                response_times,
                response_times_by_endpoint: HashMap::new(), // Simplified for now
                errors_by_endpoint,
                last_request_by_endpoint,
            };

            // Convert to RequestLog format for admin UI
            let recent_logs = recent_logs_subset
                .into_iter()
                .map(|log| RequestLog {
                    id: log.id,
                    timestamp: log.timestamp,
                    method: log.method,
                    path: log.path,
                    status_code: log.status_code,
                    response_time_ms: log.response_time_ms,
                    client_ip: log.client_ip,
                    user_agent: log.user_agent,
                    headers: log.headers,
                    response_size_bytes: log.response_size_bytes,
                    error_message: log.error_message,
                })
                .collect();

            (recent_logs, calculated_metrics)
        } else {
            // Fallback to local logs if centralized logger not available
            let logs = state.logs.read().await;
            let recent_logs = logs.iter().rev().take(10).cloned().collect();
            let metrics = state.get_metrics().await;
            (recent_logs, metrics)
        };

    let metrics = calculated_metrics;

    let system_info = SystemInfo {
        version: env!("CARGO_PKG_VERSION").to_string(),
        uptime_seconds: uptime,
        memory_usage_mb: system_metrics.memory_usage_mb,
        cpu_usage_percent: system_metrics.cpu_usage_percent,
        active_threads: system_metrics.active_threads as usize,
        total_routes: metrics.requests_by_endpoint.len(),
        total_fixtures: count_fixtures().unwrap_or(0),
    };

    let servers = vec![
        ServerStatus {
            server_type: "HTTP".to_string(),
            address: state.http_server_addr.map(|addr| addr.to_string()),
            running: state.http_server_addr.is_some(),
            start_time: Some(state.start_time),
            uptime_seconds: Some(uptime),
            active_connections: metrics.active_connections,
            total_requests: count_requests_by_server_type(&metrics, "HTTP"),
        },
        ServerStatus {
            server_type: "WebSocket".to_string(),
            address: state.ws_server_addr.map(|addr| addr.to_string()),
            running: state.ws_server_addr.is_some(),
            start_time: Some(state.start_time),
            uptime_seconds: Some(uptime),
            active_connections: metrics.active_connections / 2, // Estimate
            total_requests: count_requests_by_server_type(&metrics, "WebSocket"),
        },
        ServerStatus {
            server_type: "gRPC".to_string(),
            address: state.grpc_server_addr.map(|addr| addr.to_string()),
            running: state.grpc_server_addr.is_some(),
            start_time: Some(state.start_time),
            uptime_seconds: Some(uptime),
            active_connections: metrics.active_connections / 3, // Estimate
            total_requests: count_requests_by_server_type(&metrics, "gRPC"),
        },
    ];

    // Build routes info from actual request metrics
    let mut routes = Vec::new();
    for (endpoint, count) in &metrics.requests_by_endpoint {
        let parts: Vec<&str> = endpoint.splitn(2, ' ').collect();
        if parts.len() == 2 {
            let method = parts[0].to_string();
            let path = parts[1].to_string();
            let error_count = *metrics.errors_by_endpoint.get(endpoint).unwrap_or(&0);

            routes.push(RouteInfo {
                method: Some(method.clone()),
                path: path.clone(),
                priority: 0,
                has_fixtures: route_has_fixtures(&method, &path),
                latency_ms: calculate_endpoint_latency(&metrics, endpoint),
                request_count: *count,
                last_request: get_endpoint_last_request(&metrics, endpoint),
                error_count,
            });
        }
    }

    let dashboard = DashboardData {
        server_info: ServerInfo {
            version: env!("CARGO_PKG_VERSION").to_string(),
            build_time: option_env!("VERGEN_BUILD_TIMESTAMP").unwrap_or("unknown").to_string(),
            git_sha: option_env!("VERGEN_GIT_SHA").unwrap_or("unknown").to_string(),
            http_server: state.http_server_addr.map(|addr| addr.to_string()),
            ws_server: state.ws_server_addr.map(|addr| addr.to_string()),
            grpc_server: state.grpc_server_addr.map(|addr| addr.to_string()),
            graphql_server: state.graphql_server_addr.map(|addr| addr.to_string()),
            api_enabled: state.api_enabled,
            admin_port: state.admin_port,
        },
        system_info: DashboardSystemInfo {
            os: std::env::consts::OS.to_string(),
            arch: std::env::consts::ARCH.to_string(),
            uptime,
            memory_usage: system_metrics.memory_usage_mb * 1024 * 1024, // Convert MB to bytes
        },
        metrics: SimpleMetricsData {
            total_requests: metrics.requests_by_endpoint.values().sum(),
            active_requests: metrics.active_connections,
            average_response_time: if metrics.response_times.is_empty() {
                0.0
            } else {
                metrics.response_times.iter().sum::<u64>() as f64
                    / metrics.response_times.len() as f64
            },
            error_rate: {
                let total_requests = metrics.requests_by_endpoint.values().sum::<u64>();
                let total_errors = metrics.errors_by_endpoint.values().sum::<u64>();
                if total_requests == 0 {
                    0.0
                } else {
                    total_errors as f64 / total_requests as f64
                }
            },
        },
        servers,
        recent_logs,
        system: system_info,
    };

    Json(ApiResponse::success(dashboard))
}

/// Get routes from the global route store (populated by the HTTP server at startup)
pub async fn get_routes() -> impl IntoResponse {
    let routes = mockforge_core::request_logger::get_global_routes();
    let json = serde_json::json!({
        "routes": routes,
        "total": routes.len()
    });
    (
        StatusCode::OK,
        [("content-type", "application/json")],
        serde_json::to_string(&json).unwrap_or_else(|_| r#"{"routes":[]}"#.to_string()),
    )
}

/// Get server info (HTTP server address for API calls)
pub async fn get_server_info(State(state): State<AdminState>) -> Json<serde_json::Value> {
    Json(json!({
        "http_server": state.http_server_addr.map(|addr| addr.to_string()),
        "ws_server": state.ws_server_addr.map(|addr| addr.to_string()),
        "grpc_server": state.grpc_server_addr.map(|addr| addr.to_string()),
        "admin_port": state.admin_port
    }))
}

/// Get health check status
pub async fn get_health() -> Json<HealthCheck> {
    Json(
        HealthCheck::healthy()
            .with_service("http".to_string(), "healthy".to_string())
            .with_service("websocket".to_string(), "healthy".to_string())
            .with_service("grpc".to_string(), "healthy".to_string()),
    )
}

/// Get request logs with optional filtering
pub async fn get_logs(
    State(state): State<AdminState>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Vec<RequestLog>>> {
    let mut filter = LogFilter::default();

    if let Some(method) = params.get("method") {
        filter.method = Some(method.clone());
    }
    if let Some(path) = params.get("path") {
        filter.path_pattern = Some(path.clone());
    }
    if let Some(status) = params.get("status").and_then(|s| s.parse().ok()) {
        filter.status_code = Some(status);
    }
    if let Some(limit) = params.get("limit").and_then(|s| s.parse().ok()) {
        filter.limit = Some(limit);
    }

    // Get logs from centralized logger (same as dashboard)
    let logs = if let Some(global_logger) = mockforge_core::get_global_logger() {
        // Get logs from centralized logger
        let centralized_logs = global_logger.get_recent_logs(filter.limit).await;

        // Convert to RequestLog format and apply filters
        centralized_logs
            .into_iter()
            .filter(|log| {
                if let Some(ref method) = filter.method {
                    if log.method != *method {
                        return false;
                    }
                }
                if let Some(ref path_pattern) = filter.path_pattern {
                    if !log.path.contains(path_pattern) {
                        return false;
                    }
                }
                if let Some(status) = filter.status_code {
                    if log.status_code != status {
                        return false;
                    }
                }
                true
            })
            .map(|log| RequestLog {
                id: log.id,
                timestamp: log.timestamp,
                method: log.method,
                path: log.path,
                status_code: log.status_code,
                response_time_ms: log.response_time_ms,
                client_ip: log.client_ip,
                user_agent: log.user_agent,
                headers: log.headers,
                response_size_bytes: log.response_size_bytes,
                error_message: log.error_message,
            })
            .collect()
    } else {
        // Fallback to local logs if centralized logger not available
        state.get_logs_filtered(&filter).await
    };

    Json(ApiResponse::success(logs))
}

/// Get reality trace metadata for a specific request
///
/// GET /__mockforge/api/reality/trace/:request_id
pub async fn get_reality_trace(
    Path(request_id): Path<String>,
) -> Json<ApiResponse<Option<mockforge_core::request_logger::RealityTraceMetadata>>> {
    if let Some(global_logger) = mockforge_core::get_global_logger() {
        let logs = global_logger.get_recent_logs(None).await;
        if let Some(log_entry) = logs.into_iter().find(|log| log.id == request_id) {
            Json(ApiResponse::success(log_entry.reality_metadata))
        } else {
            Json(ApiResponse::error(format!("Request {} not found", request_id)))
        }
    } else {
        Json(ApiResponse::error("Request logger not initialized".to_string()))
    }
}

/// Get response generation trace for a specific request
///
/// GET /__mockforge/api/reality/response-trace/:request_id
pub async fn get_response_trace(
    Path(request_id): Path<String>,
) -> Json<ApiResponse<Option<serde_json::Value>>> {
    if let Some(global_logger) = mockforge_core::get_global_logger() {
        let logs = global_logger.get_recent_logs(None).await;
        if let Some(log_entry) = logs.into_iter().find(|log| log.id == request_id) {
            // Response generation trace would be stored in metadata
            // For now, return the metadata as JSON
            let trace = log_entry
                .metadata
                .get("response_generation_trace")
                .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok());
            Json(ApiResponse::success(trace))
        } else {
            Json(ApiResponse::error(format!("Request {} not found", request_id)))
        }
    } else {
        Json(ApiResponse::error("Request logger not initialized".to_string()))
    }
}

// Configuration for recent logs display
const RECENT_LOGS_LIMIT: usize = 20;
const RECENT_LOGS_TTL_MINUTES: i64 = 5;

/// SSE endpoint for real-time log streaming
pub async fn logs_sse(
    State(_state): State<AdminState>,
) -> Sse<impl Stream<Item = std::result::Result<Event, Infallible>>> {
    tracing::info!("SSE endpoint /logs/sse accessed - starting real-time log streaming for recent requests only");

    let stream = stream::unfold(std::collections::HashSet::new(), |mut seen_ids| async move {
        tokio::time::sleep(Duration::from_millis(500)).await;

        // Get recent logs from centralized logger (limit to recent entries for dashboard)
        if let Some(global_logger) = mockforge_core::get_global_logger() {
            let centralized_logs = global_logger.get_recent_logs(Some(RECENT_LOGS_LIMIT)).await;

            tracing::debug!(
                "SSE: Checking logs - total logs: {}, seen logs: {}",
                centralized_logs.len(),
                seen_ids.len()
            );

            // Filter for recent logs within TTL
            let now = Utc::now();
            let ttl_cutoff = now - chrono::Duration::minutes(RECENT_LOGS_TTL_MINUTES);

            // Find new logs that haven't been seen before
            let new_logs: Vec<RequestLog> = centralized_logs
                .into_iter()
                .filter(|log| {
                    // Only include logs from the last X minutes and not yet seen
                    log.timestamp > ttl_cutoff && !seen_ids.contains(&log.id)
                })
                .map(|log| RequestLog {
                    id: log.id,
                    timestamp: log.timestamp,
                    method: log.method,
                    path: log.path,
                    status_code: log.status_code,
                    response_time_ms: log.response_time_ms,
                    client_ip: log.client_ip,
                    user_agent: log.user_agent,
                    headers: log.headers,
                    response_size_bytes: log.response_size_bytes,
                    error_message: log.error_message,
                })
                .collect();

            // Add new log IDs to the seen set
            for log in &new_logs {
                seen_ids.insert(log.id.clone());
            }

            // Send new logs if any
            if !new_logs.is_empty() {
                tracing::info!("SSE: Sending {} new logs to client", new_logs.len());

                let event_data = serde_json::to_string(&new_logs).unwrap_or_default();
                let event = Ok(Event::default().event("new_logs").data(event_data));

                return Some((event, seen_ids));
            }
        }

        // Send keep-alive
        let event = Ok(Event::default().event("keep_alive").data(""));
        Some((event, seen_ids))
    });

    Sse::new(stream).keep_alive(
        axum::response::sse::KeepAlive::new()
            .interval(Duration::from_secs(15))
            .text("keep-alive-text"),
    )
}

/// Get metrics data
pub async fn get_metrics(State(state): State<AdminState>) -> Json<ApiResponse<MetricsData>> {
    // Get metrics from global logger (same as get_dashboard)
    let metrics = if let Some(global_logger) = mockforge_core::get_global_logger() {
        let all_logs = global_logger.get_recent_logs(None).await;

        let total_requests = all_logs.len() as u64;
        let mut requests_by_endpoint = HashMap::new();
        let mut errors_by_endpoint = HashMap::new();
        let mut response_times = Vec::new();
        let mut last_request_by_endpoint = HashMap::new();

        for log in &all_logs {
            let endpoint_key = format!("{} {}", log.method, log.path);
            *requests_by_endpoint.entry(endpoint_key.clone()).or_insert(0) += 1;

            if log.status_code >= 400 {
                *errors_by_endpoint.entry(endpoint_key.clone()).or_insert(0) += 1;
            }

            response_times.push(log.response_time_ms);
            last_request_by_endpoint.insert(endpoint_key, log.timestamp);
        }

        RequestMetrics {
            total_requests,
            active_connections: 0,
            requests_by_endpoint,
            response_times,
            response_times_by_endpoint: HashMap::new(),
            errors_by_endpoint,
            last_request_by_endpoint,
        }
    } else {
        state.get_metrics().await
    };

    let system_metrics = state.get_system_metrics().await;
    let time_series = state.get_time_series_data().await;

    // Helper function to calculate percentile from sorted array
    fn calculate_percentile(sorted_data: &[u64], percentile: f64) -> u64 {
        if sorted_data.is_empty() {
            return 0;
        }
        let idx = ((sorted_data.len() as f64) * percentile).ceil() as usize;
        let idx = idx.min(sorted_data.len().saturating_sub(1));
        sorted_data[idx]
    }

    // Calculate percentiles from response times (p50, p75, p90, p95, p99, p99.9)
    let mut response_times = metrics.response_times.clone();
    response_times.sort();

    let p50 = calculate_percentile(&response_times, 0.50);
    let p75 = calculate_percentile(&response_times, 0.75);
    let p90 = calculate_percentile(&response_times, 0.90);
    let p95 = calculate_percentile(&response_times, 0.95);
    let p99 = calculate_percentile(&response_times, 0.99);
    let p999 = calculate_percentile(&response_times, 0.999);

    // Calculate per-endpoint percentiles for detailed analysis
    let mut response_times_by_endpoint: HashMap<String, Vec<u64>> = HashMap::new();
    if let Some(global_logger) = mockforge_core::get_global_logger() {
        let all_logs = global_logger.get_recent_logs(None).await;
        for log in &all_logs {
            let endpoint_key = format!("{} {}", log.method, log.path);
            response_times_by_endpoint
                .entry(endpoint_key)
                .or_default()
                .push(log.response_time_ms);
        }
    }

    // Calculate percentiles for each endpoint
    let mut endpoint_percentiles: HashMap<String, HashMap<String, u64>> = HashMap::new();
    for (endpoint, times) in &mut response_times_by_endpoint {
        times.sort();
        if !times.is_empty() {
            endpoint_percentiles.insert(
                endpoint.clone(),
                HashMap::from([
                    ("p50".to_string(), calculate_percentile(times, 0.50)),
                    ("p75".to_string(), calculate_percentile(times, 0.75)),
                    ("p90".to_string(), calculate_percentile(times, 0.90)),
                    ("p95".to_string(), calculate_percentile(times, 0.95)),
                    ("p99".to_string(), calculate_percentile(times, 0.99)),
                    ("p999".to_string(), calculate_percentile(times, 0.999)),
                ]),
            );
        }
    }

    // Calculate error rates
    let mut error_rate_by_endpoint = HashMap::new();
    for (endpoint, total_count) in &metrics.requests_by_endpoint {
        let error_count = *metrics.errors_by_endpoint.get(endpoint).unwrap_or(&0);
        let error_rate = if *total_count > 0 {
            error_count as f64 / *total_count as f64
        } else {
            0.0
        };
        error_rate_by_endpoint.insert(endpoint.clone(), error_rate);
    }

    // Convert time series data to the format expected by the frontend
    // If no time series data exists yet, use current system metrics as a fallback
    let memory_usage_over_time = if time_series.memory_usage.is_empty() {
        vec![(Utc::now(), system_metrics.memory_usage_mb)]
    } else {
        time_series
            .memory_usage
            .iter()
            .map(|point| (point.timestamp, point.value as u64))
            .collect()
    };

    let cpu_usage_over_time = if time_series.cpu_usage.is_empty() {
        vec![(Utc::now(), system_metrics.cpu_usage_percent)]
    } else {
        time_series
            .cpu_usage
            .iter()
            .map(|point| (point.timestamp, point.value))
            .collect()
    };

    // Build time-series latency data (last 100 data points)
    let latency_over_time: Vec<(chrono::DateTime<Utc>, u64)> =
        if let Some(global_logger) = mockforge_core::get_global_logger() {
            let all_logs = global_logger.get_recent_logs(Some(100)).await;
            all_logs.iter().map(|log| (log.timestamp, log.response_time_ms)).collect()
        } else {
            Vec::new()
        };

    let metrics_data = MetricsData {
        requests_by_endpoint: metrics.requests_by_endpoint,
        response_time_percentiles: HashMap::from([
            ("p50".to_string(), p50),
            ("p75".to_string(), p75),
            ("p90".to_string(), p90),
            ("p95".to_string(), p95),
            ("p99".to_string(), p99),
            ("p999".to_string(), p999),
        ]),
        endpoint_percentiles: Some(endpoint_percentiles),
        latency_over_time: Some(latency_over_time),
        error_rate_by_endpoint,
        memory_usage_over_time,
        cpu_usage_over_time,
    };

    Json(ApiResponse::success(metrics_data))
}

/// Update latency profile
pub async fn update_latency(
    State(state): State<AdminState>,
    headers: http::HeaderMap,
    Json(update): Json<ConfigUpdate>,
) -> Json<ApiResponse<String>> {
    use crate::audit::{create_audit_log, get_global_audit_store, AdminActionType};
    use crate::rbac::{extract_user_context, get_default_user_context};

    if update.config_type != "latency" {
        return Json(ApiResponse::error("Invalid config type".to_string()));
    }

    // Extract latency configuration from the update data
    let base_ms = update.data.get("base_ms").and_then(|v| v.as_u64()).unwrap_or(50);
    let jitter_ms = update.data.get("jitter_ms").and_then(|v| v.as_u64()).unwrap_or(20);

    let tag_overrides: HashMap<String, u64> = update
        .data
        .get("tag_overrides")
        .and_then(|v| v.as_object())
        .map(|obj| obj.iter().filter_map(|(k, v)| v.as_u64().map(|val| (k.clone(), val))).collect())
        .unwrap_or_default();

    // Update the actual configuration
    state.update_latency_config(base_ms, jitter_ms, tag_overrides.clone()).await;

    // Record audit log with user context
    if let Some(audit_store) = get_global_audit_store() {
        let metadata = serde_json::json!({
            "base_ms": base_ms,
            "jitter_ms": jitter_ms,
            "tag_overrides": tag_overrides,
        });
        let mut audit_log = create_audit_log(
            AdminActionType::ConfigLatencyUpdated,
            format!("Latency profile updated: base_ms={}, jitter_ms={}", base_ms, jitter_ms),
            None,
            true,
            None,
            Some(metadata),
        );

        // Extract user context from headers
        if let Some(user_ctx) = extract_user_context(&headers).or_else(get_default_user_context) {
            audit_log.user_id = Some(user_ctx.user_id);
            audit_log.username = Some(user_ctx.username);
        }

        // Extract IP address from headers
        if let Some(ip) = headers
            .get("x-forwarded-for")
            .or_else(|| headers.get("x-real-ip"))
            .and_then(|h| h.to_str().ok())
        {
            audit_log.ip_address = Some(ip.to_string());
        }

        // Extract user agent
        if let Some(ua) = headers.get("user-agent").and_then(|h| h.to_str().ok()) {
            audit_log.user_agent = Some(ua.to_string());
        }

        audit_store.record(audit_log).await;
    }

    tracing::info!("Updated latency profile: base_ms={}, jitter_ms={}", base_ms, jitter_ms);

    Json(ApiResponse::success("Latency profile updated".to_string()))
}

/// Update fault injection configuration
pub async fn update_faults(
    State(state): State<AdminState>,
    Json(update): Json<ConfigUpdate>,
) -> Json<ApiResponse<String>> {
    if update.config_type != "faults" {
        return Json(ApiResponse::error("Invalid config type".to_string()));
    }

    // Extract fault configuration from the update data
    let enabled = update.data.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false);

    let failure_rate = update.data.get("failure_rate").and_then(|v| v.as_f64()).unwrap_or(0.0);

    let status_codes = update
        .data
        .get("status_codes")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_u64().map(|n| n as u16)).collect())
        .unwrap_or_else(|| vec![500, 502, 503]);

    // Update the actual configuration
    state.update_fault_config(enabled, failure_rate, status_codes).await;

    tracing::info!(
        "Updated fault configuration: enabled={}, failure_rate={}",
        enabled,
        failure_rate
    );

    Json(ApiResponse::success("Fault configuration updated".to_string()))
}

/// Update proxy configuration
pub async fn update_proxy(
    State(state): State<AdminState>,
    Json(update): Json<ConfigUpdate>,
) -> Json<ApiResponse<String>> {
    if update.config_type != "proxy" {
        return Json(ApiResponse::error("Invalid config type".to_string()));
    }

    // Extract proxy configuration from the update data
    let enabled = update.data.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false);

    let upstream_url =
        update.data.get("upstream_url").and_then(|v| v.as_str()).map(|s| s.to_string());

    let timeout_seconds = update.data.get("timeout_seconds").and_then(|v| v.as_u64()).unwrap_or(30);

    // Update the actual configuration
    state.update_proxy_config(enabled, upstream_url.clone(), timeout_seconds).await;

    tracing::info!(
        "Updated proxy configuration: enabled={}, upstream_url={:?}",
        enabled,
        upstream_url
    );

    Json(ApiResponse::success("Proxy configuration updated".to_string()))
}

/// Clear request logs
pub async fn clear_logs(State(state): State<AdminState>) -> Json<ApiResponse<String>> {
    // Clear the actual logs from state
    state.clear_logs().await;
    tracing::info!("Cleared all request logs");

    Json(ApiResponse::success("Logs cleared".to_string()))
}

/// Restart servers
pub async fn restart_servers(State(state): State<AdminState>) -> Json<ApiResponse<String>> {
    use crate::audit::{create_audit_log, get_global_audit_store, AdminActionType};
    // Check if restart is already in progress
    let current_status = state.get_restart_status().await;
    if current_status.in_progress {
        return Json(ApiResponse::error("Server restart already in progress".to_string()));
    }

    // Initiate restart status
    let restart_result = state
        .initiate_restart("Manual restart requested via admin UI".to_string())
        .await;

    let success = restart_result.is_ok();
    let error_msg = restart_result.as_ref().err().map(|e| format!("{}", e));

    // Record audit log
    if let Some(audit_store) = get_global_audit_store() {
        let audit_log = create_audit_log(
            AdminActionType::ServerRestarted,
            "Server restart initiated via admin UI".to_string(),
            None,
            success,
            error_msg.clone(),
            None,
        );
        audit_store.record(audit_log).await;
    }

    if let Err(e) = restart_result {
        return Json(ApiResponse::error(format!("Failed to initiate restart: {}", e)));
    }

    // Spawn restart task to avoid blocking the response
    let state_clone = state.clone();
    tokio::spawn(async move {
        if let Err(e) = perform_server_restart(&state_clone).await {
            tracing::error!("Server restart failed: {}", e);
            state_clone.complete_restart(false).await;
        } else {
            tracing::info!("Server restart completed successfully");
            state_clone.complete_restart(true).await;
        }
    });

    tracing::info!("Server restart initiated via admin UI");
    Json(ApiResponse::success(
        "Server restart initiated. Please wait for completion.".to_string(),
    ))
}

/// Perform the actual server restart
async fn perform_server_restart(_state: &AdminState) -> Result<()> {
    // Get the current process ID
    let current_pid = std::process::id();
    tracing::info!("Initiating restart for process PID: {}", current_pid);

    // Try to find the parent process (MockForge CLI)
    let parent_pid = get_parent_process_id(current_pid).await?;
    tracing::info!("Found parent process PID: {}", parent_pid);

    // Method 1: Try to restart via parent process signal
    if let Ok(()) = restart_via_parent_signal(parent_pid).await {
        tracing::info!("Restart initiated via parent process signal");
        return Ok(());
    }

    // Method 2: Fallback to process replacement
    if let Ok(()) = restart_via_process_replacement().await {
        tracing::info!("Restart initiated via process replacement");
        return Ok(());
    }

    // Method 3: Last resort - graceful shutdown with restart script
    restart_via_script().await
}

/// Get parent process ID
async fn get_parent_process_id(pid: u32) -> Result<u32> {
    // Try to read from /proc/pid/stat on Linux
    #[cfg(target_os = "linux")]
    {
        // Read /proc filesystem using spawn_blocking
        let stat_path = format!("/proc/{}/stat", pid);
        if let Ok(ppid) = tokio::task::spawn_blocking(move || -> Result<u32> {
            let content = std::fs::read_to_string(&stat_path)
                .map_err(|e| Error::generic(format!("Failed to read {}: {}", stat_path, e)))?;

            let fields: Vec<&str> = content.split_whitespace().collect();
            if fields.len() > 3 {
                fields[3]
                    .parse::<u32>()
                    .map_err(|e| Error::generic(format!("Failed to parse PPID: {}", e)))
            } else {
                Err(Error::generic("Insufficient fields in /proc/pid/stat".to_string()))
            }
        })
        .await
        {
            return ppid;
        }
    }

    // Fallback: assume we're running under a shell/process manager
    Ok(1) // PID 1 as fallback
}

/// Restart via parent process signal
async fn restart_via_parent_signal(parent_pid: u32) -> Result<()> {
    #[cfg(unix)]
    {
        use std::process::Command;

        // Send SIGTERM to parent process to trigger restart
        let output = Command::new("kill")
            .args(["-TERM", &parent_pid.to_string()])
            .output()
            .map_err(|e| Error::generic(format!("Failed to send signal: {}", e)))?;

        if !output.status.success() {
            return Err(Error::generic(
                "Failed to send restart signal to parent process".to_string(),
            ));
        }

        // Wait a moment for the signal to be processed
        tokio::time::sleep(Duration::from_millis(100)).await;
        Ok(())
    }

    #[cfg(not(unix))]
    {
        Err(Error::generic(
            "Signal-based restart not supported on this platform".to_string(),
        ))
    }
}

/// Restart via process replacement
async fn restart_via_process_replacement() -> Result<()> {
    // Get the current executable path
    let current_exe = std::env::current_exe()
        .map_err(|e| Error::generic(format!("Failed to get current executable: {}", e)))?;

    // Get current command line arguments
    let args: Vec<String> = std::env::args().collect();

    tracing::info!("Restarting with command: {:?}", args);

    // Start new process
    let mut child = Command::new(&current_exe)
        .args(&args[1..]) // Skip the program name
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .map_err(|e| Error::generic(format!("Failed to start new process: {}", e)))?;

    // Give the new process a moment to start
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Check if the new process is still running
    match child.try_wait() {
        Ok(Some(status)) => {
            if status.success() {
                tracing::info!("New process started successfully");
                Ok(())
            } else {
                Err(Error::generic("New process exited with error".to_string()))
            }
        }
        Ok(None) => {
            tracing::info!("New process is running, exiting current process");
            // Exit current process
            std::process::exit(0);
        }
        Err(e) => Err(Error::generic(format!("Failed to check new process status: {}", e))),
    }
}

/// Restart via external script
async fn restart_via_script() -> Result<()> {
    // Look for restart script in common locations
    let script_paths = ["./scripts/restart.sh", "./restart.sh", "restart.sh"];

    for script_path in &script_paths {
        if std::path::Path::new(script_path).exists() {
            tracing::info!("Using restart script: {}", script_path);

            let output = Command::new("bash")
                .arg(script_path)
                .output()
                .map_err(|e| Error::generic(format!("Failed to execute restart script: {}", e)))?;

            if output.status.success() {
                return Ok(());
            } else {
                tracing::warn!(
                    "Restart script failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
            }
        }
    }

    // If no script found, try to use the clear-ports script as a fallback
    let clear_script = "./scripts/clear-ports.sh";
    if std::path::Path::new(clear_script).exists() {
        tracing::info!("Using clear-ports script as fallback");

        let _ = Command::new("bash").arg(clear_script).output();
    }

    Err(Error::generic(
        "No restart mechanism available. Please restart manually.".to_string(),
    ))
}

/// Get restart status
pub async fn get_restart_status(
    State(state): State<AdminState>,
) -> Json<ApiResponse<RestartStatus>> {
    let status = state.get_restart_status().await;
    Json(ApiResponse::success(status))
}

/// Get audit logs
pub async fn get_audit_logs(
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Vec<crate::audit::AdminAuditLog>>> {
    use crate::audit::{get_global_audit_store, AdminActionType};

    let action_type_str = params.get("action_type");
    let user_id = params.get("user_id").map(|s| s.as_str());
    let limit = params.get("limit").and_then(|s| s.parse::<usize>().ok());
    let offset = params.get("offset").and_then(|s| s.parse::<usize>().ok());

    // Parse action type if provided
    let action_type = action_type_str.and_then(|s| {
        // Simple string matching - could be enhanced with proper parsing
        match s.as_str() {
            "config_latency_updated" => Some(AdminActionType::ConfigLatencyUpdated),
            "config_faults_updated" => Some(AdminActionType::ConfigFaultsUpdated),
            "server_restarted" => Some(AdminActionType::ServerRestarted),
            "logs_cleared" => Some(AdminActionType::LogsCleared),
            _ => None,
        }
    });

    if let Some(audit_store) = get_global_audit_store() {
        let logs = audit_store.get_logs(action_type, user_id, limit, offset).await;
        Json(ApiResponse::success(logs))
    } else {
        Json(ApiResponse::error("Audit logging not initialized".to_string()))
    }
}

/// Get audit log statistics
pub async fn get_audit_stats() -> Json<ApiResponse<crate::audit::AuditLogStats>> {
    use crate::audit::get_global_audit_store;

    if let Some(audit_store) = get_global_audit_store() {
        let stats = audit_store.get_stats().await;
        Json(ApiResponse::success(stats))
    } else {
        Json(ApiResponse::error("Audit logging not initialized".to_string()))
    }
}

/// Get server configuration
pub async fn get_config(State(state): State<AdminState>) -> Json<ApiResponse<serde_json::Value>> {
    let config_state = state.get_config().await;

    let config = json!({
        "latency": {
            "enabled": true,
            "base_ms": config_state.latency_profile.base_ms,
            "jitter_ms": config_state.latency_profile.jitter_ms,
            "tag_overrides": config_state.latency_profile.tag_overrides
        },
        "faults": {
            "enabled": config_state.fault_config.enabled,
            "failure_rate": config_state.fault_config.failure_rate,
            "status_codes": config_state.fault_config.status_codes
        },
        "proxy": {
            "enabled": config_state.proxy_config.enabled,
            "upstream_url": config_state.proxy_config.upstream_url,
            "timeout_seconds": config_state.proxy_config.timeout_seconds
        },
        "traffic_shaping": {
            "enabled": config_state.traffic_shaping.enabled,
            "bandwidth": config_state.traffic_shaping.bandwidth,
            "burst_loss": config_state.traffic_shaping.burst_loss
        },
        "validation": {
            "mode": config_state.validation_settings.mode,
            "aggregate_errors": config_state.validation_settings.aggregate_errors,
            "validate_responses": config_state.validation_settings.validate_responses,
            "overrides": config_state.validation_settings.overrides
        }
    });

    Json(ApiResponse::success(config))
}

/// Count total fixtures in the fixtures directory
pub fn count_fixtures() -> Result<usize> {
    // Get the fixtures directory from environment or use default
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        return Ok(0);
    }

    let mut total_count = 0;

    // Count HTTP fixtures
    let http_fixtures_path = fixtures_path.join("http");
    if http_fixtures_path.exists() {
        total_count += count_fixtures_in_directory(&http_fixtures_path)?;
    }

    // Count WebSocket fixtures
    let ws_fixtures_path = fixtures_path.join("websocket");
    if ws_fixtures_path.exists() {
        total_count += count_fixtures_in_directory(&ws_fixtures_path)?;
    }

    // Count gRPC fixtures
    let grpc_fixtures_path = fixtures_path.join("grpc");
    if grpc_fixtures_path.exists() {
        total_count += count_fixtures_in_directory(&grpc_fixtures_path)?;
    }

    Ok(total_count)
}

/// Helper function to count JSON files in a directory recursively (blocking version)
fn count_fixtures_in_directory(dir_path: &std::path::Path) -> Result<usize> {
    let mut count = 0;

    if let Ok(entries) = std::fs::read_dir(dir_path) {
        for entry in entries {
            let entry = entry
                .map_err(|e| Error::generic(format!("Failed to read directory entry: {}", e)))?;
            let path = entry.path();

            if path.is_dir() {
                // Recursively count fixtures in subdirectories
                count += count_fixtures_in_directory(&path)?;
            } else if path.extension().and_then(|s| s.to_str()) == Some("json") {
                // Count JSON files as fixtures
                count += 1;
            }
        }
    }

    Ok(count)
}

/// Check if a specific route has fixtures
pub fn route_has_fixtures(method: &str, path: &str) -> bool {
    // Get the fixtures directory from environment or use default
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        return false;
    }

    // Check HTTP fixtures
    let method_lower = method.to_lowercase();
    let path_hash = path.replace(['/', ':'], "_");
    let http_fixtures_path = fixtures_path.join("http").join(&method_lower).join(&path_hash);

    if http_fixtures_path.exists() {
        // Check if there are any JSON files in this directory
        if let Ok(entries) = std::fs::read_dir(&http_fixtures_path) {
            for entry in entries.flatten() {
                if entry.path().extension().and_then(|s| s.to_str()) == Some("json") {
                    return true;
                }
            }
        }
    }

    // Check WebSocket fixtures for WS method
    if method.to_uppercase() == "WS" {
        let ws_fixtures_path = fixtures_path.join("websocket").join(&path_hash);

        if ws_fixtures_path.exists() {
            if let Ok(entries) = std::fs::read_dir(&ws_fixtures_path) {
                for entry in entries.flatten() {
                    if entry.path().extension().and_then(|s| s.to_str()) == Some("json") {
                        return true;
                    }
                }
            }
        }
    }

    false
}

/// Calculate average latency for a specific endpoint
fn calculate_endpoint_latency(metrics: &RequestMetrics, endpoint: &str) -> Option<u64> {
    metrics.response_times_by_endpoint.get(endpoint).and_then(|times| {
        if times.is_empty() {
            None
        } else {
            let sum: u64 = times.iter().sum();
            Some(sum / times.len() as u64)
        }
    })
}

/// Get the last request timestamp for a specific endpoint
fn get_endpoint_last_request(
    metrics: &RequestMetrics,
    endpoint: &str,
) -> Option<chrono::DateTime<Utc>> {
    metrics.last_request_by_endpoint.get(endpoint).copied()
}

/// Count total requests for a specific server type
fn count_requests_by_server_type(metrics: &RequestMetrics, server_type: &str) -> u64 {
    match server_type {
        "HTTP" => {
            // Count all HTTP requests (GET, POST, PUT, DELETE, etc.)
            metrics
                .requests_by_endpoint
                .iter()
                .filter(|(endpoint, _)| {
                    let method = endpoint.split(' ').next().unwrap_or("");
                    matches!(
                        method,
                        "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS"
                    )
                })
                .map(|(_, count)| count)
                .sum()
        }
        "WebSocket" => {
            // Count WebSocket requests (WS method)
            metrics
                .requests_by_endpoint
                .iter()
                .filter(|(endpoint, _)| {
                    let method = endpoint.split(' ').next().unwrap_or("");
                    method == "WS"
                })
                .map(|(_, count)| count)
                .sum()
        }
        "gRPC" => {
            // Count gRPC requests (gRPC method)
            metrics
                .requests_by_endpoint
                .iter()
                .filter(|(endpoint, _)| {
                    let method = endpoint.split(' ').next().unwrap_or("");
                    method == "gRPC"
                })
                .map(|(_, count)| count)
                .sum()
        }
        _ => 0,
    }
}

/// Get fixtures/replay data
pub async fn get_fixtures() -> Json<ApiResponse<Vec<FixtureInfo>>> {
    match scan_fixtures_directory() {
        Ok(fixtures) => Json(ApiResponse::success(fixtures)),
        Err(e) => {
            tracing::error!("Failed to scan fixtures directory: {}", e);
            Json(ApiResponse::error(format!("Failed to load fixtures: {}", e)))
        }
    }
}

/// Scan the fixtures directory and return all fixture information
fn scan_fixtures_directory() -> Result<Vec<FixtureInfo>> {
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        tracing::warn!("Fixtures directory does not exist: {}", fixtures_dir);
        return Ok(Vec::new());
    }

    let mut all_fixtures = Vec::new();

    // Scan HTTP fixtures
    let http_fixtures = scan_protocol_fixtures(fixtures_path, "http")?;
    all_fixtures.extend(http_fixtures);

    // Scan WebSocket fixtures
    let ws_fixtures = scan_protocol_fixtures(fixtures_path, "websocket")?;
    all_fixtures.extend(ws_fixtures);

    // Scan gRPC fixtures
    let grpc_fixtures = scan_protocol_fixtures(fixtures_path, "grpc")?;
    all_fixtures.extend(grpc_fixtures);

    // Sort by saved_at timestamp (newest first)
    all_fixtures.sort_by(|a, b| b.saved_at.cmp(&a.saved_at));

    tracing::info!("Found {} fixtures in directory: {}", all_fixtures.len(), fixtures_dir);
    Ok(all_fixtures)
}

/// Scan fixtures for a specific protocol
fn scan_protocol_fixtures(
    fixtures_path: &std::path::Path,
    protocol: &str,
) -> Result<Vec<FixtureInfo>> {
    let protocol_path = fixtures_path.join(protocol);
    let mut fixtures = Vec::new();

    if !protocol_path.exists() {
        return Ok(fixtures);
    }

    // Walk through the protocol directory recursively
    if let Ok(entries) = std::fs::read_dir(&protocol_path) {
        for entry in entries {
            let entry = entry
                .map_err(|e| Error::generic(format!("Failed to read directory entry: {}", e)))?;
            let path = entry.path();

            if path.is_dir() {
                // Recursively scan subdirectories
                let sub_fixtures = scan_directory_recursive(&path, protocol)?;
                fixtures.extend(sub_fixtures);
            } else if path.extension().and_then(|s| s.to_str()) == Some("json") {
                // Process individual JSON fixture file
                if let Ok(fixture) = parse_fixture_file_sync(&path, protocol) {
                    fixtures.push(fixture);
                }
            }
        }
    }

    Ok(fixtures)
}

/// Recursively scan a directory for fixture files
fn scan_directory_recursive(
    dir_path: &std::path::Path,
    protocol: &str,
) -> Result<Vec<FixtureInfo>> {
    let mut fixtures = Vec::new();

    if let Ok(entries) = std::fs::read_dir(dir_path) {
        for entry in entries {
            let entry = entry
                .map_err(|e| Error::generic(format!("Failed to read directory entry: {}", e)))?;
            let path = entry.path();

            if path.is_dir() {
                // Recursively scan subdirectories
                let sub_fixtures = scan_directory_recursive(&path, protocol)?;
                fixtures.extend(sub_fixtures);
            } else if path.extension().and_then(|s| s.to_str()) == Some("json") {
                // Process individual JSON fixture file
                if let Ok(fixture) = parse_fixture_file_sync(&path, protocol) {
                    fixtures.push(fixture);
                }
            }
        }
    }

    Ok(fixtures)
}

/// Parse a single fixture file and extract metadata (synchronous version)
fn parse_fixture_file_sync(file_path: &std::path::Path, protocol: &str) -> Result<FixtureInfo> {
    // Get file metadata
    let metadata = std::fs::metadata(file_path)
        .map_err(|e| Error::generic(format!("Failed to read file metadata: {}", e)))?;

    let file_size = metadata.len();
    let modified_time = metadata
        .modified()
        .map_err(|e| Error::generic(format!("Failed to get file modification time: {}", e)))?;

    let saved_at = chrono::DateTime::from(modified_time);

    // Read and parse the fixture file (blocking - called from spawn_blocking context)
    let content = std::fs::read_to_string(file_path)
        .map_err(|e| Error::generic(format!("Failed to read fixture file: {}", e)))?;

    let fixture_data: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| Error::generic(format!("Failed to parse fixture JSON: {}", e)))?;

    // Extract method and path from the fixture data
    let (method, path) = extract_method_and_path(&fixture_data, protocol)?;

    // Generate a unique ID based on file path and content
    let id = generate_fixture_id(file_path, &content);

    // Extract fingerprint from file path or fixture data
    let fingerprint = extract_fingerprint(file_path, &fixture_data)?;

    // Get relative file path
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);
    let file_path_str = file_path
        .strip_prefix(fixtures_path)
        .unwrap_or(file_path)
        .to_string_lossy()
        .to_string();

    Ok(FixtureInfo {
        id,
        protocol: protocol.to_string(),
        method,
        path,
        saved_at,
        file_size,
        file_path: file_path_str,
        fingerprint,
        metadata: fixture_data,
    })
}

/// Extract method and path from fixture data
fn extract_method_and_path(
    fixture_data: &serde_json::Value,
    protocol: &str,
) -> Result<(String, String)> {
    match protocol {
        "http" => {
            // For HTTP fixtures, look for request.method and request.path
            let method = fixture_data
                .get("request")
                .and_then(|req| req.get("method"))
                .and_then(|m| m.as_str())
                .unwrap_or("UNKNOWN")
                .to_uppercase();

            let path = fixture_data
                .get("request")
                .and_then(|req| req.get("path"))
                .and_then(|p| p.as_str())
                .unwrap_or("/unknown")
                .to_string();

            Ok((method, path))
        }
        "websocket" => {
            // For WebSocket fixtures, use WS method and extract path from metadata
            let path = fixture_data
                .get("path")
                .and_then(|p| p.as_str())
                .or_else(|| {
                    fixture_data
                        .get("request")
                        .and_then(|req| req.get("path"))
                        .and_then(|p| p.as_str())
                })
                .unwrap_or("/ws")
                .to_string();

            Ok(("WS".to_string(), path))
        }
        "grpc" => {
            // For gRPC fixtures, extract service and method
            let service =
                fixture_data.get("service").and_then(|s| s.as_str()).unwrap_or("UnknownService");

            let method =
                fixture_data.get("method").and_then(|m| m.as_str()).unwrap_or("UnknownMethod");

            let path = format!("/{}/{}", service, method);
            Ok(("gRPC".to_string(), path))
        }
        _ => {
            let path = fixture_data
                .get("path")
                .and_then(|p| p.as_str())
                .unwrap_or("/unknown")
                .to_string();
            Ok((protocol.to_uppercase(), path))
        }
    }
}

/// Generate a unique fixture ID
fn generate_fixture_id(file_path: &std::path::Path, content: &str) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    file_path.hash(&mut hasher);
    content.hash(&mut hasher);
    format!("fixture_{:x}", hasher.finish())
}

/// Extract fingerprint from file path or fixture data
fn extract_fingerprint(
    file_path: &std::path::Path,
    fixture_data: &serde_json::Value,
) -> Result<String> {
    // Try to extract from fixture data first
    if let Some(fingerprint) = fixture_data.get("fingerprint").and_then(|f| f.as_str()) {
        return Ok(fingerprint.to_string());
    }

    // Try to extract from file path (common pattern: method_path_hash.json)
    if let Some(file_name) = file_path.file_stem().and_then(|s| s.to_str()) {
        // Look for hash pattern at the end of filename
        if let Some(hash) = file_name.split('_').next_back() {
            if hash.len() >= 8 && hash.chars().all(|c| c.is_alphanumeric()) {
                return Ok(hash.to_string());
            }
        }
    }

    // Fallback: generate from file path
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    file_path.hash(&mut hasher);
    Ok(format!("{:x}", hasher.finish()))
}

/// Delete a fixture
pub async fn delete_fixture(
    Json(payload): Json<FixtureDeleteRequest>,
) -> Json<ApiResponse<String>> {
    match delete_fixture_by_id(&payload.fixture_id).await {
        Ok(_) => {
            tracing::info!("Successfully deleted fixture: {}", payload.fixture_id);
            Json(ApiResponse::success("Fixture deleted successfully".to_string()))
        }
        Err(e) => {
            tracing::error!("Failed to delete fixture {}: {}", payload.fixture_id, e);
            Json(ApiResponse::error(format!("Failed to delete fixture: {}", e)))
        }
    }
}

/// Delete multiple fixtures
pub async fn delete_fixtures_bulk(
    Json(payload): Json<FixtureBulkDeleteRequest>,
) -> Json<ApiResponse<FixtureBulkDeleteResult>> {
    let mut deleted_count = 0;
    let mut errors = Vec::new();

    for fixture_id in &payload.fixture_ids {
        match delete_fixture_by_id(fixture_id).await {
            Ok(_) => {
                deleted_count += 1;
                tracing::info!("Successfully deleted fixture: {}", fixture_id);
            }
            Err(e) => {
                errors.push(format!("Failed to delete {}: {}", fixture_id, e));
                tracing::error!("Failed to delete fixture {}: {}", fixture_id, e);
            }
        }
    }

    let result = FixtureBulkDeleteResult {
        deleted_count,
        total_requested: payload.fixture_ids.len(),
        errors: errors.clone(),
    };

    if errors.is_empty() {
        Json(ApiResponse::success(result))
    } else {
        Json(ApiResponse::error(format!(
            "Partial success: {} deleted, {} errors",
            deleted_count,
            errors.len()
        )))
    }
}

/// Delete a single fixture by ID
async fn delete_fixture_by_id(fixture_id: &str) -> Result<()> {
    // First, try to find the fixture by scanning the fixtures directory
    // This is more robust than trying to parse the ID format
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        return Err(Error::generic(format!("Fixtures directory does not exist: {}", fixtures_dir)));
    }

    // Search for the fixture file by ID across all protocols
    let file_path = find_fixture_file_by_id(fixtures_path, fixture_id)?;

    // Delete the file using spawn_blocking
    let file_path_clone = file_path.clone();
    tokio::task::spawn_blocking(move || {
        if file_path_clone.exists() {
            std::fs::remove_file(&file_path_clone).map_err(|e| {
                Error::generic(format!(
                    "Failed to delete fixture file {}: {}",
                    file_path_clone.display(),
                    e
                ))
            })
        } else {
            Err(Error::generic(format!("Fixture file not found: {}", file_path_clone.display())))
        }
    })
    .await
    .map_err(|e| Error::generic(format!("Task join error: {}", e)))??;

    tracing::info!("Deleted fixture file: {}", file_path.display());

    // Also try to remove empty parent directories
    cleanup_empty_directories(&file_path).await;

    Ok(())
}

/// Find a fixture file by its ID across all protocols
fn find_fixture_file_by_id(
    fixtures_path: &std::path::Path,
    fixture_id: &str,
) -> Result<std::path::PathBuf> {
    // Search in all protocol directories
    let protocols = ["http", "websocket", "grpc"];

    for protocol in &protocols {
        let protocol_path = fixtures_path.join(protocol);
        if let Ok(found_path) = search_fixture_in_directory(&protocol_path, fixture_id) {
            return Ok(found_path);
        }
    }

    Err(Error::generic(format!(
        "Fixture with ID '{}' not found in any protocol directory",
        fixture_id
    )))
}

/// Recursively search for a fixture file by ID in a directory
fn search_fixture_in_directory(
    dir_path: &std::path::Path,
    fixture_id: &str,
) -> Result<std::path::PathBuf> {
    if !dir_path.exists() {
        return Err(Error::generic(format!("Directory does not exist: {}", dir_path.display())));
    }

    if let Ok(entries) = std::fs::read_dir(dir_path) {
        for entry in entries {
            let entry = entry
                .map_err(|e| Error::generic(format!("Failed to read directory entry: {}", e)))?;
            let path = entry.path();

            if path.is_dir() {
                // Recursively search subdirectories
                if let Ok(found_path) = search_fixture_in_directory(&path, fixture_id) {
                    return Ok(found_path);
                }
            } else if path.extension().and_then(|s| s.to_str()) == Some("json") {
                // Check if this file matches the fixture ID
                if let Ok(fixture_info) = parse_fixture_file_sync(&path, "unknown") {
                    if fixture_info.id == fixture_id {
                        return Ok(path);
                    }
                }
            }
        }
    }

    Err(Error::generic(format!(
        "Fixture not found in directory: {}",
        dir_path.display()
    )))
}

/// Clean up empty directories after file deletion
async fn cleanup_empty_directories(file_path: &std::path::Path) {
    let file_path = file_path.to_path_buf();

    // Use spawn_blocking for directory operations
    let _ = tokio::task::spawn_blocking(move || {
        if let Some(parent) = file_path.parent() {
            // Try to remove empty directories up to the protocol level
            let mut current = parent;
            let fixtures_dir =
                std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
            let fixtures_path = std::path::Path::new(&fixtures_dir);

            while current != fixtures_path && current.parent().is_some() {
                if let Ok(entries) = std::fs::read_dir(current) {
                    if entries.count() == 0 {
                        if let Err(e) = std::fs::remove_dir(current) {
                            tracing::debug!(
                                "Failed to remove empty directory {}: {}",
                                current.display(),
                                e
                            );
                            break;
                        } else {
                            tracing::debug!("Removed empty directory: {}", current.display());
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }

                if let Some(next_parent) = current.parent() {
                    current = next_parent;
                } else {
                    break;
                }
            }
        }
    })
    .await;
}

/// Download a fixture file
pub async fn download_fixture(Path(fixture_id): Path<String>) -> impl IntoResponse {
    // Find and read the fixture file
    match download_fixture_by_id(&fixture_id).await {
        Ok((content, file_name)) => (
            StatusCode::OK,
            [
                (http::header::CONTENT_TYPE, "application/json".to_string()),
                (
                    http::header::CONTENT_DISPOSITION,
                    format!("attachment; filename=\"{}\"", file_name),
                ),
            ],
            content,
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to download fixture {}: {}", fixture_id, e);
            let error_response = format!(r#"{{"error": "Failed to download fixture: {}"}}"#, e);
            (
                StatusCode::NOT_FOUND,
                [(http::header::CONTENT_TYPE, "application/json".to_string())],
                error_response,
            )
                .into_response()
        }
    }
}

/// Download a fixture file by ID
async fn download_fixture_by_id(fixture_id: &str) -> Result<(String, String)> {
    // Find the fixture file by ID
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        return Err(Error::generic(format!("Fixtures directory does not exist: {}", fixtures_dir)));
    }

    let file_path = find_fixture_file_by_id(fixtures_path, fixture_id)?;

    // Read the file content using spawn_blocking
    let file_path_clone = file_path.clone();
    let (content, file_name) = tokio::task::spawn_blocking(move || {
        let content = std::fs::read_to_string(&file_path_clone)
            .map_err(|e| Error::generic(format!("Failed to read fixture file: {}", e)))?;

        let file_name = file_path_clone
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("fixture.json")
            .to_string();

        Ok::<_, Error>((content, file_name))
    })
    .await
    .map_err(|e| Error::generic(format!("Task join error: {}", e)))??;

    tracing::info!("Downloaded fixture file: {} ({} bytes)", file_path.display(), content.len());
    Ok((content, file_name))
}

/// Rename a fixture
pub async fn rename_fixture(
    Path(fixture_id): Path<String>,
    Json(payload): Json<FixtureRenameRequest>,
) -> Json<ApiResponse<String>> {
    match rename_fixture_by_id(&fixture_id, &payload.new_name).await {
        Ok(new_path) => {
            tracing::info!("Successfully renamed fixture: {} -> {}", fixture_id, payload.new_name);
            Json(ApiResponse::success(format!("Fixture renamed successfully to: {}", new_path)))
        }
        Err(e) => {
            tracing::error!("Failed to rename fixture {}: {}", fixture_id, e);
            Json(ApiResponse::error(format!("Failed to rename fixture: {}", e)))
        }
    }
}

/// Rename a fixture by ID
async fn rename_fixture_by_id(fixture_id: &str, new_name: &str) -> Result<String> {
    // Validate new name
    if new_name.is_empty() {
        return Err(Error::generic("New name cannot be empty".to_string()));
    }

    // Ensure new name ends with .json
    let new_name = if new_name.ends_with(".json") {
        new_name.to_string()
    } else {
        format!("{}.json", new_name)
    };

    // Find the fixture file
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        return Err(Error::generic(format!("Fixtures directory does not exist: {}", fixtures_dir)));
    }

    let old_path = find_fixture_file_by_id(fixtures_path, fixture_id)?;

    // Get the parent directory and construct new path
    let parent = old_path
        .parent()
        .ok_or_else(|| Error::generic("Could not determine parent directory".to_string()))?;

    let new_path = parent.join(&new_name);

    // Check if target already exists
    if new_path.exists() {
        return Err(Error::generic(format!(
            "A fixture with name '{}' already exists in the same directory",
            new_name
        )));
    }

    // Rename the file using spawn_blocking
    let old_path_clone = old_path.clone();
    let new_path_clone = new_path.clone();
    tokio::task::spawn_blocking(move || {
        std::fs::rename(&old_path_clone, &new_path_clone)
            .map_err(|e| Error::generic(format!("Failed to rename fixture file: {}", e)))
    })
    .await
    .map_err(|e| Error::generic(format!("Task join error: {}", e)))??;

    tracing::info!("Renamed fixture file: {} -> {}", old_path.display(), new_path.display());

    // Return relative path for display
    Ok(new_path
        .strip_prefix(fixtures_path)
        .unwrap_or(&new_path)
        .to_string_lossy()
        .to_string())
}

/// Move a fixture to a new path
pub async fn move_fixture(
    Path(fixture_id): Path<String>,
    Json(payload): Json<FixtureMoveRequest>,
) -> Json<ApiResponse<String>> {
    match move_fixture_by_id(&fixture_id, &payload.new_path).await {
        Ok(new_location) => {
            tracing::info!("Successfully moved fixture: {} -> {}", fixture_id, payload.new_path);
            Json(ApiResponse::success(format!("Fixture moved successfully to: {}", new_location)))
        }
        Err(e) => {
            tracing::error!("Failed to move fixture {}: {}", fixture_id, e);
            Json(ApiResponse::error(format!("Failed to move fixture: {}", e)))
        }
    }
}

/// Move a fixture by ID to a new path
async fn move_fixture_by_id(fixture_id: &str, new_path: &str) -> Result<String> {
    // Validate new path
    if new_path.is_empty() {
        return Err(Error::generic("New path cannot be empty".to_string()));
    }

    // Find the fixture file
    let fixtures_dir =
        std::env::var("MOCKFORGE_FIXTURES_DIR").unwrap_or_else(|_| "fixtures".to_string());
    let fixtures_path = std::path::Path::new(&fixtures_dir);

    if !fixtures_path.exists() {
        return Err(Error::generic(format!("Fixtures directory does not exist: {}", fixtures_dir)));
    }

    let old_path = find_fixture_file_by_id(fixtures_path, fixture_id)?;

    // Construct the new path - can be either relative to fixtures_dir or absolute within it
    let new_full_path = if new_path.starts_with('/') {
        // Absolute path within fixtures directory
        fixtures_path.join(new_path.trim_start_matches('/'))
    } else {
        // Relative path from fixtures directory
        fixtures_path.join(new_path)
    };

    // Ensure target ends with .json if it doesn't already
    let new_full_path = if new_full_path.extension().and_then(|s| s.to_str()) == Some("json") {
        new_full_path
    } else {
        // If the path is a directory or doesn't have .json extension, append the original filename
        if new_full_path.is_dir() || !new_path.contains('.') {
            let file_name = old_path.file_name().ok_or_else(|| {
                Error::generic("Could not determine original file name".to_string())
            })?;
            new_full_path.join(file_name)
        } else {
            new_full_path.with_extension("json")
        }
    };

    // Check if target already exists
    if new_full_path.exists() {
        return Err(Error::generic(format!(
            "A fixture already exists at path: {}",
            new_full_path.display()
        )));
    }

    // Create parent directories and move file using spawn_blocking
    let old_path_clone = old_path.clone();
    let new_full_path_clone = new_full_path.clone();
    tokio::task::spawn_blocking(move || {
        // Create parent directories if they don't exist
        if let Some(parent) = new_full_path_clone.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| Error::generic(format!("Failed to create target directory: {}", e)))?;
        }

        // Move the file
        std::fs::rename(&old_path_clone, &new_full_path_clone)
            .map_err(|e| Error::generic(format!("Failed to move fixture file: {}", e)))
    })
    .await
    .map_err(|e| Error::generic(format!("Task join error: {}", e)))??;

    tracing::info!("Moved fixture file: {} -> {}", old_path.display(), new_full_path.display());

    // Clean up empty directories from the old location
    cleanup_empty_directories(&old_path).await;

    // Return relative path for display
    Ok(new_full_path
        .strip_prefix(fixtures_path)
        .unwrap_or(&new_full_path)
        .to_string_lossy()
        .to_string())
}

/// Get current validation settings
pub async fn get_validation(
    State(state): State<AdminState>,
) -> Json<ApiResponse<ValidationSettings>> {
    // Get real validation settings from configuration
    let config_state = state.get_config().await;

    Json(ApiResponse::success(config_state.validation_settings))
}

/// Update validation settings
pub async fn update_validation(
    State(state): State<AdminState>,
    Json(update): Json<ValidationUpdate>,
) -> Json<ApiResponse<String>> {
    // Validate the mode
    match update.mode.as_str() {
        "enforce" | "warn" | "off" => {}
        _ => {
            return Json(ApiResponse::error(
                "Invalid validation mode. Must be 'enforce', 'warn', or 'off'".to_string(),
            ))
        }
    }

    // Update the actual validation configuration
    let mode = update.mode.clone();
    state
        .update_validation_config(
            update.mode,
            update.aggregate_errors,
            update.validate_responses,
            update.overrides.unwrap_or_default(),
        )
        .await;

    tracing::info!(
        "Updated validation settings: mode={}, aggregate_errors={}",
        mode,
        update.aggregate_errors
    );

    Json(ApiResponse::success("Validation settings updated".to_string()))
}

/// Get environment variables
pub async fn get_env_vars() -> Json<ApiResponse<HashMap<String, String>>> {
    // Get actual environment variables that are relevant to MockForge
    let mut env_vars = HashMap::new();

    let relevant_vars = [
        // Core functionality
        "MOCKFORGE_LATENCY_ENABLED",
        "MOCKFORGE_FAILURES_ENABLED",
        "MOCKFORGE_PROXY_ENABLED",
        "MOCKFORGE_RECORD_ENABLED",
        "MOCKFORGE_REPLAY_ENABLED",
        "MOCKFORGE_LOG_LEVEL",
        "MOCKFORGE_CONFIG_FILE",
        "RUST_LOG",
        // HTTP server configuration
        "MOCKFORGE_HTTP_PORT",
        "MOCKFORGE_HTTP_HOST",
        "MOCKFORGE_HTTP_OPENAPI_SPEC",
        "MOCKFORGE_CORS_ENABLED",
        "MOCKFORGE_REQUEST_TIMEOUT_SECS",
        // WebSocket server configuration
        "MOCKFORGE_WS_PORT",
        "MOCKFORGE_WS_HOST",
        "MOCKFORGE_WS_REPLAY_FILE",
        "MOCKFORGE_WS_CONNECTION_TIMEOUT_SECS",
        // gRPC server configuration
        "MOCKFORGE_GRPC_PORT",
        "MOCKFORGE_GRPC_HOST",
        // Admin UI configuration
        "MOCKFORGE_ADMIN_ENABLED",
        "MOCKFORGE_ADMIN_PORT",
        "MOCKFORGE_ADMIN_HOST",
        "MOCKFORGE_ADMIN_MOUNT_PATH",
        "MOCKFORGE_ADMIN_API_ENABLED",
        // Template and validation
        "MOCKFORGE_RESPONSE_TEMPLATE_EXPAND",
        "MOCKFORGE_REQUEST_VALIDATION",
        "MOCKFORGE_AGGREGATE_ERRORS",
        "MOCKFORGE_RESPONSE_VALIDATION",
        "MOCKFORGE_VALIDATION_STATUS",
        // Data generation
        "MOCKFORGE_RAG_ENABLED",
        "MOCKFORGE_FAKE_TOKENS",
        // Other settings
        "MOCKFORGE_FIXTURES_DIR",
    ];

    for var_name in &relevant_vars {
        if let Ok(value) = std::env::var(var_name) {
            env_vars.insert(var_name.to_string(), value);
        }
    }

    Json(ApiResponse::success(env_vars))
}

/// Update environment variable
pub async fn update_env_var(Json(update): Json<EnvVarUpdate>) -> Json<ApiResponse<String>> {
    // Set the environment variable (runtime only - not persisted)
    std::env::set_var(&update.key, &update.value);

    tracing::info!("Updated environment variable: {}={}", update.key, update.value);

    // Note: Environment variables set at runtime are not persisted
    // In a production system, you might want to write to a .env file or config file
    Json(ApiResponse::success(format!(
        "Environment variable {} updated to '{}'. Note: This change is not persisted and will be lost on restart.",
        update.key, update.value
    )))
}

/// Get file content
pub async fn get_file_content(
    Json(request): Json<FileContentRequest>,
) -> Json<ApiResponse<String>> {
    // Validate the file path for security
    if let Err(e) = validate_file_path(&request.file_path) {
        return Json(ApiResponse::error(format!("Invalid file path: {}", e)));
    }

    // Read the actual file content
    match tokio::fs::read_to_string(&request.file_path).await {
        Ok(content) => {
            // Validate the file content for security
            if let Err(e) = validate_file_content(&content) {
                return Json(ApiResponse::error(format!("Invalid file content: {}", e)));
            }
            Json(ApiResponse::success(content))
        }
        Err(e) => Json(ApiResponse::error(format!("Failed to read file: {}", e))),
    }
}

/// Save file content
pub async fn save_file_content(Json(request): Json<FileSaveRequest>) -> Json<ApiResponse<String>> {
    match save_file_to_filesystem(&request.file_path, &request.content).await {
        Ok(_) => {
            tracing::info!("Successfully saved file: {}", request.file_path);
            Json(ApiResponse::success("File saved successfully".to_string()))
        }
        Err(e) => {
            tracing::error!("Failed to save file {}: {}", request.file_path, e);
            Json(ApiResponse::error(format!("Failed to save file: {}", e)))
        }
    }
}

/// Save content to a file on the filesystem
async fn save_file_to_filesystem(file_path: &str, content: &str) -> Result<()> {
    // Validate the file path for security
    validate_file_path(file_path)?;

    // Validate the file content for security
    validate_file_content(content)?;

    // Convert to PathBuf and clone data for spawn_blocking
    let path = std::path::PathBuf::from(file_path);
    let content = content.to_string();

    // Perform file operations using spawn_blocking
    let path_clone = path.clone();
    let content_clone = content.clone();
    tokio::task::spawn_blocking(move || {
        // Create parent directories if they don't exist
        if let Some(parent) = path_clone.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                Error::generic(format!("Failed to create directory {}: {}", parent.display(), e))
            })?;
        }

        // Write the content to the file
        std::fs::write(&path_clone, &content_clone).map_err(|e| {
            Error::generic(format!("Failed to write file {}: {}", path_clone.display(), e))
        })?;

        // Verify the file was written correctly
        let written_content = std::fs::read_to_string(&path_clone).map_err(|e| {
            Error::generic(format!("Failed to verify written file {}: {}", path_clone.display(), e))
        })?;

        if written_content != content_clone {
            return Err(Error::generic(format!(
                "File content verification failed for {}",
                path_clone.display()
            )));
        }

        Ok::<_, Error>(())
    })
    .await
    .map_err(|e| Error::generic(format!("Task join error: {}", e)))??;

    tracing::info!("File saved successfully: {} ({} bytes)", path.display(), content.len());
    Ok(())
}

/// Validate file path for security
fn validate_file_path(file_path: &str) -> Result<()> {
    // Check for path traversal attacks
    if file_path.contains("..") {
        return Err(Error::generic("Path traversal detected in file path".to_string()));
    }

    // Check for absolute paths that might be outside allowed directories
    let path = std::path::Path::new(file_path);
    if path.is_absolute() {
        // For absolute paths, ensure they're within allowed directories
        let allowed_dirs = [
            std::env::current_dir().unwrap_or_default(),
            std::path::PathBuf::from("."),
            std::path::PathBuf::from("fixtures"),
            std::path::PathBuf::from("config"),
        ];

        let mut is_allowed = false;
        for allowed_dir in &allowed_dirs {
            if path.starts_with(allowed_dir) {
                is_allowed = true;
                break;
            }
        }

        if !is_allowed {
            return Err(Error::generic("File path is outside allowed directories".to_string()));
        }
    }

    // Check for dangerous file extensions or names
    let dangerous_extensions = ["exe", "bat", "cmd", "sh", "ps1", "scr", "com"];
    if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
        if dangerous_extensions.contains(&extension.to_lowercase().as_str()) {
            return Err(Error::generic(format!(
                "Dangerous file extension not allowed: {}",
                extension
            )));
        }
    }

    Ok(())
}

/// Validate file content for security
fn validate_file_content(content: &str) -> Result<()> {
    // Check for reasonable file size (prevent DoS)
    if content.len() > 10 * 1024 * 1024 {
        // 10MB limit
        return Err(Error::generic("File content too large (max 10MB)".to_string()));
    }

    // Check for null bytes (potential security issue)
    if content.contains('\0') {
        return Err(Error::generic("File content contains null bytes".to_string()));
    }

    Ok(())
}

/// Fixture delete request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureDeleteRequest {
    pub fixture_id: String,
}

/// Environment variable update
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvVarUpdate {
    pub key: String,
    pub value: String,
}

/// Fixture bulk delete request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureBulkDeleteRequest {
    pub fixture_ids: Vec<String>,
}

/// Fixture bulk delete result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureBulkDeleteResult {
    pub deleted_count: usize,
    pub total_requested: usize,
    pub errors: Vec<String>,
}

/// Fixture rename request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureRenameRequest {
    pub new_name: String,
}

/// Fixture move request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureMoveRequest {
    pub new_path: String,
}

/// File content request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileContentRequest {
    pub file_path: String,
    pub file_type: String,
}

/// File save request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSaveRequest {
    pub file_path: String,
    pub content: String,
}

/// Get smoke tests
pub async fn get_smoke_tests(
    State(state): State<AdminState>,
) -> Json<ApiResponse<Vec<SmokeTestResult>>> {
    let results = state.get_smoke_test_results().await;
    Json(ApiResponse::success(results))
}

/// Run smoke tests endpoint
pub async fn run_smoke_tests_endpoint(
    State(state): State<AdminState>,
) -> Json<ApiResponse<String>> {
    tracing::info!("Starting smoke test execution");

    // Spawn smoke test execution in background to avoid blocking
    let state_clone = state.clone();
    tokio::spawn(async move {
        if let Err(e) = execute_smoke_tests(&state_clone).await {
            tracing::error!("Smoke test execution failed: {}", e);
        } else {
            tracing::info!("Smoke test execution completed successfully");
        }
    });

    Json(ApiResponse::success(
        "Smoke tests started. Check results in the smoke tests section.".to_string(),
    ))
}

/// Execute smoke tests against fixtures
async fn execute_smoke_tests(state: &AdminState) -> Result<()> {
    // Get base URL from environment or use default
    let base_url =
        std::env::var("MOCKFORGE_BASE_URL").unwrap_or_else(|_| "http://localhost:3000".to_string());

    let context = SmokeTestContext {
        base_url,
        timeout_seconds: 30,
        parallel: true,
    };

    // Get all fixtures to create smoke tests from
    let fixtures = scan_fixtures_directory()?;

    // Filter for HTTP fixtures only (smoke tests are typically HTTP)
    let http_fixtures: Vec<&FixtureInfo> =
        fixtures.iter().filter(|f| f.protocol == "http").collect();

    if http_fixtures.is_empty() {
        tracing::warn!("No HTTP fixtures found for smoke testing");
        return Ok(());
    }

    tracing::info!("Running smoke tests for {} HTTP fixtures", http_fixtures.len());

    // Create smoke test results from fixtures
    let mut test_results = Vec::new();

    for fixture in http_fixtures {
        let test_result = create_smoke_test_from_fixture(fixture);
        test_results.push(test_result);
    }

    // Execute tests
    let mut executed_results = Vec::new();
    for mut test_result in test_results {
        // Update status to running
        test_result.status = "running".to_string();
        state.update_smoke_test_result(test_result.clone()).await;

        // Execute the test
        let start_time = std::time::Instant::now();
        match execute_single_smoke_test(&test_result, &context).await {
            Ok((status_code, response_time_ms)) => {
                test_result.status = "passed".to_string();
                test_result.status_code = Some(status_code);
                test_result.response_time_ms = Some(response_time_ms);
                test_result.error_message = None;
            }
            Err(e) => {
                test_result.status = "failed".to_string();
                test_result.error_message = Some(e.to_string());
                test_result.status_code = None;
                test_result.response_time_ms = None;
            }
        }

        let duration = start_time.elapsed();
        test_result.duration_seconds = Some(duration.as_secs_f64());
        test_result.last_run = Some(Utc::now());

        executed_results.push(test_result.clone());
        state.update_smoke_test_result(test_result).await;
    }

    tracing::info!("Smoke test execution completed: {} tests run", executed_results.len());
    Ok(())
}

/// Create a smoke test result from a fixture
fn create_smoke_test_from_fixture(fixture: &FixtureInfo) -> SmokeTestResult {
    let test_name = format!("{} {}", fixture.method, fixture.path);
    let description = format!("Smoke test for {} endpoint", fixture.path);

    SmokeTestResult {
        id: format!("smoke_{}", fixture.id),
        name: test_name,
        method: fixture.method.clone(),
        path: fixture.path.clone(),
        description,
        last_run: None,
        status: "pending".to_string(),
        response_time_ms: None,
        error_message: None,
        status_code: None,
        duration_seconds: None,
    }
}

/// Execute a single smoke test
async fn execute_single_smoke_test(
    test: &SmokeTestResult,
    context: &SmokeTestContext,
) -> Result<(u16, u64)> {
    let url = format!("{}{}", context.base_url, test.path);
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(context.timeout_seconds))
        .build()
        .map_err(|e| Error::generic(format!("Failed to create HTTP client: {}", e)))?;

    let start_time = std::time::Instant::now();

    let response = match test.method.as_str() {
        "GET" => client.get(&url).send().await,
        "POST" => client.post(&url).send().await,
        "PUT" => client.put(&url).send().await,
        "DELETE" => client.delete(&url).send().await,
        "PATCH" => client.patch(&url).send().await,
        "HEAD" => client.head(&url).send().await,
        "OPTIONS" => client.request(reqwest::Method::OPTIONS, &url).send().await,
        _ => {
            return Err(Error::generic(format!("Unsupported HTTP method: {}", test.method)));
        }
    };

    let response_time = start_time.elapsed();
    let response_time_ms = response_time.as_millis() as u64;

    match response {
        Ok(resp) => {
            let status_code = resp.status().as_u16();
            if (200..400).contains(&status_code) {
                Ok((status_code, response_time_ms))
            } else {
                Err(Error::generic(format!(
                    "HTTP error: {} {}",
                    status_code,
                    resp.status().canonical_reason().unwrap_or("Unknown")
                )))
            }
        }
        Err(e) => Err(Error::generic(format!("Request failed: {}", e))),
    }
}

#[derive(Debug, Deserialize)]
pub struct PluginInstallRequest {
    pub source: String,
    #[serde(default)]
    pub force: bool,
    #[serde(default)]
    pub skip_validation: bool,
    #[serde(default)]
    pub no_verify: bool,
    pub checksum: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct PluginValidateRequest {
    pub source: String,
}

fn find_plugin_directory(path: &std::path::Path) -> Option<std::path::PathBuf> {
    if path.join("plugin.yaml").exists() {
        return Some(path.to_path_buf());
    }

    let entries = std::fs::read_dir(path).ok()?;
    for entry in entries.filter_map(|e| e.ok()) {
        let child = entry.path();
        if child.is_dir() && child.join("plugin.yaml").exists() {
            return Some(child);
        }
    }

    None
}

async fn resolve_plugin_source_path(
    source: PluginSource,
    checksum: Option<&str>,
) -> std::result::Result<std::path::PathBuf, String> {
    match source {
        PluginSource::Local(path) => Ok(path),
        PluginSource::Url { url, .. } => {
            let loader = RemotePluginLoader::new(RemotePluginConfig::default())
                .map_err(|e| format!("Failed to initialize remote plugin loader: {}", e))?;
            loader
                .download_with_checksum(&url, checksum)
                .await
                .map_err(|e| format!("Failed to download plugin from URL: {}", e))
        }
        PluginSource::Git(git_source) => {
            let loader = GitPluginLoader::new(GitPluginConfig::default())
                .map_err(|e| format!("Failed to initialize git plugin loader: {}", e))?;
            loader
                .clone_from_git(&git_source)
                .await
                .map_err(|e| format!("Failed to clone plugin from git: {}", e))
        }
        PluginSource::Registry { name, version } => Err(format!(
            "Registry plugin installation is not yet supported from the admin API (requested {}@{})",
            name,
            version.unwrap_or_else(|| "latest".to_string())
        )),
    }
}

/// Install a plugin from a path, URL, or Git source and register it in-process.
pub async fn install_plugin(
    State(state): State<AdminState>,
    Json(request): Json<PluginInstallRequest>,
) -> impl IntoResponse {
    let source = request.source.trim().to_string();
    if source.is_empty() {
        return Json(json!({
            "success": false,
            "error": "Plugin source is required"
        }));
    }

    if request.skip_validation {
        return Json(json!({
            "success": false,
            "error": "Skipping validation is not supported in admin install flow."
        }));
    }

    if request.no_verify {
        return Json(json!({
            "success": false,
            "error": "Disabling signature verification is not supported in admin install flow."
        }));
    }

    let force = request.force;
    let checksum = request.checksum.clone();
    let state_for_install = state.clone();

    let install_result = tokio::task::spawn_blocking(
        move || -> std::result::Result<(String, String, String), String> {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| format!("Failed to initialize install runtime: {}", e))?;

            let (plugin_instance, plugin_id, plugin_name, plugin_version) =
                runtime.block_on(async move {
                    let parsed_source = PluginSource::parse(&source)
                        .map_err(|e| format!("Invalid plugin source: {}", e))?;

                    let source_path =
                        resolve_plugin_source_path(parsed_source, checksum.as_deref()).await?;

                    let plugin_root = if source_path.is_dir() {
                        find_plugin_directory(&source_path).unwrap_or(source_path.clone())
                    } else {
                        source_path.clone()
                    };

                    if !plugin_root.exists() || !plugin_root.is_dir() {
                        return Err(format!(
                            "Resolved plugin path is not a directory: {}",
                            plugin_root.display()
                        ));
                    }

                    let loader = PluginLoader::new(PluginLoaderConfig::default());
                    let manifest = loader
                        .validate_plugin(&plugin_root)
                        .await
                        .map_err(|e| format!("Failed to validate plugin: {}", e))?;

                    let plugin_id = manifest.info.id.clone();
                    let plugin_name = manifest.info.name.clone();
                    let plugin_version = manifest.info.version.to_string();

                    let parent_dir = plugin_root
                        .parent()
                        .unwrap_or_else(|| std::path::Path::new("."))
                        .to_string_lossy()
                        .to_string();

                    let runtime_loader = PluginLoader::new(PluginLoaderConfig {
                        plugin_dirs: vec![parent_dir],
                        ..PluginLoaderConfig::default()
                    });

                    runtime_loader
                        .load_plugin(&plugin_id)
                        .await
                        .map_err(|e| format!("Failed to load plugin into runtime: {}", e))?;

                    let plugin_instance =
                        runtime_loader.get_plugin(&plugin_id).await.ok_or_else(|| {
                            "Plugin loaded but instance was not retrievable from loader".to_string()
                        })?;

                    Ok::<_, String>((
                        plugin_instance,
                        plugin_id.to_string(),
                        plugin_name,
                        plugin_version,
                    ))
                })?;

            let mut registry = state_for_install.plugin_registry.blocking_write();

            if let Some(existing_id) =
                registry.list_plugins().into_iter().find(|id| id.as_str() == plugin_id)
            {
                if force {
                    registry.remove_plugin(&existing_id).map_err(|e| {
                        format!("Failed to remove existing plugin before reinstall: {}", e)
                    })?;
                } else {
                    return Err(format!(
                        "Plugin '{}' is already installed. Use force=true to reinstall.",
                        plugin_id
                    ));
                }
            }

            registry
                .add_plugin(plugin_instance)
                .map_err(|e| format!("Failed to register plugin in admin registry: {}", e))?;

            Ok((plugin_id, plugin_name, plugin_version))
        },
    )
    .await;

    let (plugin_id, plugin_name, plugin_version) = match install_result {
        Ok(Ok(result)) => result,
        Ok(Err(err)) => {
            return Json(json!({
                "success": false,
                "error": err
            }))
        }
        Err(err) => {
            return Json(json!({
                "success": false,
                "error": format!("Plugin installation task failed: {}", err)
            }))
        }
    };

    Json(json!({
        "success": true,
        "data": {
            "plugin_id": plugin_id,
            "name": plugin_name,
            "version": plugin_version
        },
        "message": "Plugin installed and registered in runtime."
    }))
}

/// Validate a plugin source without installing it.
pub async fn validate_plugin(Json(request): Json<PluginValidateRequest>) -> impl IntoResponse {
    let source = request.source.trim();
    if source.is_empty() {
        return Json(json!({
            "success": false,
            "error": "Plugin source is required"
        }));
    }

    let source = match PluginSource::parse(source) {
        Ok(source) => source,
        Err(e) => {
            return Json(json!({
                "success": false,
                "error": format!("Invalid plugin source: {}", e)
            }));
        }
    };

    let path = match source.clone() {
        PluginSource::Local(path) => path,
        PluginSource::Url { .. } | PluginSource::Git(_) => {
            match resolve_plugin_source_path(source, None).await {
                Ok(path) => path,
                Err(err) => {
                    return Json(json!({
                        "success": false,
                        "error": err
                    }))
                }
            }
        }
        PluginSource::Registry { .. } => {
            return Json(json!({
                "success": false,
                "error": "Registry plugin validation is not yet supported from the admin API."
            }))
        }
    };

    let plugin_root = if path.is_dir() {
        find_plugin_directory(&path).unwrap_or(path.clone())
    } else {
        path
    };

    let loader = PluginLoader::new(PluginLoaderConfig::default());
    match loader.validate_plugin(&plugin_root).await {
        Ok(manifest) => Json(json!({
            "success": true,
            "data": {
                "valid": true,
                "id": manifest.info.id.to_string(),
                "name": manifest.info.name,
                "version": manifest.info.version.to_string()
            }
        })),
        Err(e) => Json(json!({
            "success": false,
            "data": { "valid": false },
            "error": format!("Plugin validation failed: {}", e)
        })),
    }
}

// Missing handler functions that routes.rs expects
pub async fn update_traffic_shaping(
    State(state): State<AdminState>,
    Json(config): Json<TrafficShapingConfig>,
) -> Json<ApiResponse<String>> {
    if config.burst_loss.burst_probability > 1.0
        || config.burst_loss.loss_rate_during_burst > 1.0
        || config.burst_loss.burst_probability < 0.0
        || config.burst_loss.loss_rate_during_burst < 0.0
    {
        return Json(ApiResponse::error(
            "Burst loss probabilities must be between 0.0 and 1.0".to_string(),
        ));
    }

    {
        let mut cfg = state.config.write().await;
        cfg.traffic_shaping = config.clone();
    }

    if let Some(ref chaos_api_state) = state.chaos_api_state {
        let mut chaos_config = chaos_api_state.config.write().await;
        chaos_config.traffic_shaping = Some(mockforge_chaos::config::TrafficShapingConfig {
            enabled: config.enabled,
            bandwidth_limit_bps: config.bandwidth.max_bytes_per_sec,
            packet_loss_percent: config.burst_loss.loss_rate_during_burst * 100.0,
            max_connections: 0,
            connection_timeout_ms: 30000,
        });
    }

    Json(ApiResponse::success("Traffic shaping updated".to_string()))
}

pub async fn import_postman(
    State(state): State<AdminState>,
    Json(request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    use mockforge_core::workspace_import::{import_postman_to_workspace, WorkspaceImportConfig};
    use uuid::Uuid;

    let content = request.get("content").and_then(|v| v.as_str()).unwrap_or("");
    let filename = request.get("filename").and_then(|v| v.as_str());
    let environment = request.get("environment").and_then(|v| v.as_str());
    let base_url = request.get("base_url").and_then(|v| v.as_str());

    // Import the collection
    let import_result = match mockforge_core::import::import_postman_collection(content, base_url) {
        Ok(result) => result,
        Err(e) => {
            // Record failed import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "postman".to_string(),
                timestamp: Utc::now(),
                routes_count: 0,
                variables_count: 0,
                warnings_count: 0,
                success: false,
                filename: filename.map(|s| s.to_string()),
                environment: environment.map(|s| s.to_string()),
                base_url: base_url.map(|s| s.to_string()),
                error_message: Some(e.clone()),
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            return Json(ApiResponse::error(format!("Postman import failed: {}", e)));
        }
    };

    // Create workspace from imported routes
    let workspace_name = filename
        .and_then(|f| f.split('.').next())
        .unwrap_or("Imported Postman Collection");

    let config = WorkspaceImportConfig {
        create_folders: true,
        base_folder_name: None,
        preserve_hierarchy: true,
        max_depth: 5,
    };

    // Convert MockForgeRoute to ImportRoute
    let routes: Vec<ImportRoute> = import_result
        .routes
        .into_iter()
        .map(|route| ImportRoute {
            method: route.method,
            path: route.path,
            headers: route.headers,
            body: route.body,
            response: ImportResponse {
                status: route.response.status,
                headers: route.response.headers,
                body: route.response.body,
            },
        })
        .collect();

    match import_postman_to_workspace(routes, workspace_name.to_string(), config) {
        Ok(workspace_result) => {
            // Save the workspace to persistent storage
            if let Err(e) =
                state.workspace_persistence.save_workspace(&workspace_result.workspace).await
            {
                tracing::error!("Failed to save workspace: {}", e);
                return Json(ApiResponse::error(format!(
                    "Import succeeded but failed to save workspace: {}",
                    e
                )));
            }

            // Record successful import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "postman".to_string(),
                timestamp: Utc::now(),
                routes_count: workspace_result.request_count,
                variables_count: import_result.variables.len(),
                warnings_count: workspace_result.warnings.len(),
                success: true,
                filename: filename.map(|s| s.to_string()),
                environment: environment.map(|s| s.to_string()),
                base_url: base_url.map(|s| s.to_string()),
                error_message: None,
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            Json(ApiResponse::success(format!(
                "Successfully imported {} routes into workspace '{}'",
                workspace_result.request_count, workspace_name
            )))
        }
        Err(e) => {
            // Record failed import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "postman".to_string(),
                timestamp: Utc::now(),
                routes_count: 0,
                variables_count: 0,
                warnings_count: 0,
                success: false,
                filename: filename.map(|s| s.to_string()),
                environment: environment.map(|s| s.to_string()),
                base_url: base_url.map(|s| s.to_string()),
                error_message: Some(e.to_string()),
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            Json(ApiResponse::error(format!("Failed to create workspace: {}", e)))
        }
    }
}

pub async fn import_insomnia(
    State(state): State<AdminState>,
    Json(request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    use uuid::Uuid;

    let content = request.get("content").and_then(|v| v.as_str()).unwrap_or("");
    let filename = request.get("filename").and_then(|v| v.as_str());
    let environment = request.get("environment").and_then(|v| v.as_str());
    let base_url = request.get("base_url").and_then(|v| v.as_str());

    // Import the export
    let import_result = match mockforge_core::import::import_insomnia_export(content, environment) {
        Ok(result) => result,
        Err(e) => {
            // Record failed import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "insomnia".to_string(),
                timestamp: Utc::now(),
                routes_count: 0,
                variables_count: 0,
                warnings_count: 0,
                success: false,
                filename: filename.map(|s| s.to_string()),
                environment: environment.map(|s| s.to_string()),
                base_url: base_url.map(|s| s.to_string()),
                error_message: Some(e.clone()),
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            return Json(ApiResponse::error(format!("Insomnia import failed: {}", e)));
        }
    };

    // Create workspace from imported routes
    let workspace_name = filename
        .and_then(|f| f.split('.').next())
        .unwrap_or("Imported Insomnia Collection");

    let _config = WorkspaceImportConfig {
        create_folders: true,
        base_folder_name: None,
        preserve_hierarchy: true,
        max_depth: 5,
    };

    // Extract variables count before moving import_result
    let variables_count = import_result.variables.len();

    match mockforge_core::workspace_import::create_workspace_from_insomnia(
        import_result,
        Some(workspace_name.to_string()),
    ) {
        Ok(workspace_result) => {
            // Save the workspace to persistent storage
            if let Err(e) =
                state.workspace_persistence.save_workspace(&workspace_result.workspace).await
            {
                tracing::error!("Failed to save workspace: {}", e);
                return Json(ApiResponse::error(format!(
                    "Import succeeded but failed to save workspace: {}",
                    e
                )));
            }

            // Record successful import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "insomnia".to_string(),
                timestamp: Utc::now(),
                routes_count: workspace_result.request_count,
                variables_count,
                warnings_count: workspace_result.warnings.len(),
                success: true,
                filename: filename.map(|s| s.to_string()),
                environment: environment.map(|s| s.to_string()),
                base_url: base_url.map(|s| s.to_string()),
                error_message: None,
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            Json(ApiResponse::success(format!(
                "Successfully imported {} routes into workspace '{}'",
                workspace_result.request_count, workspace_name
            )))
        }
        Err(e) => {
            // Record failed import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "insomnia".to_string(),
                timestamp: Utc::now(),
                routes_count: 0,
                variables_count: 0,
                warnings_count: 0,
                success: false,
                filename: filename.map(|s| s.to_string()),
                environment: environment.map(|s| s.to_string()),
                base_url: base_url.map(|s| s.to_string()),
                error_message: Some(e.to_string()),
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            Json(ApiResponse::error(format!("Failed to create workspace: {}", e)))
        }
    }
}

pub async fn import_openapi(
    State(_state): State<AdminState>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("OpenAPI import completed".to_string()))
}

pub async fn import_curl(
    State(state): State<AdminState>,
    Json(request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    use uuid::Uuid;

    let content = request.get("content").and_then(|v| v.as_str()).unwrap_or("");
    let filename = request.get("filename").and_then(|v| v.as_str());
    let base_url = request.get("base_url").and_then(|v| v.as_str());

    // Import the commands
    let import_result = match mockforge_core::import::import_curl_commands(content, base_url) {
        Ok(result) => result,
        Err(e) => {
            // Record failed import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "curl".to_string(),
                timestamp: Utc::now(),
                routes_count: 0,
                variables_count: 0,
                warnings_count: 0,
                success: false,
                filename: filename.map(|s| s.to_string()),
                environment: None,
                base_url: base_url.map(|s| s.to_string()),
                error_message: Some(e.clone()),
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            return Json(ApiResponse::error(format!("Curl import failed: {}", e)));
        }
    };

    // Create workspace from imported routes
    let workspace_name =
        filename.and_then(|f| f.split('.').next()).unwrap_or("Imported Curl Commands");

    match mockforge_core::workspace_import::create_workspace_from_curl(
        import_result,
        Some(workspace_name.to_string()),
    ) {
        Ok(workspace_result) => {
            // Save the workspace to persistent storage
            if let Err(e) =
                state.workspace_persistence.save_workspace(&workspace_result.workspace).await
            {
                tracing::error!("Failed to save workspace: {}", e);
                return Json(ApiResponse::error(format!(
                    "Import succeeded but failed to save workspace: {}",
                    e
                )));
            }

            // Record successful import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "curl".to_string(),
                timestamp: Utc::now(),
                routes_count: workspace_result.request_count,
                variables_count: 0, // Curl doesn't have variables
                warnings_count: workspace_result.warnings.len(),
                success: true,
                filename: filename.map(|s| s.to_string()),
                environment: None,
                base_url: base_url.map(|s| s.to_string()),
                error_message: None,
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            Json(ApiResponse::success(format!(
                "Successfully imported {} routes into workspace '{}'",
                workspace_result.request_count, workspace_name
            )))
        }
        Err(e) => {
            // Record failed import
            let entry = ImportHistoryEntry {
                id: Uuid::new_v4().to_string(),
                format: "curl".to_string(),
                timestamp: Utc::now(),
                routes_count: 0,
                variables_count: 0,
                warnings_count: 0,
                success: false,
                filename: filename.map(|s| s.to_string()),
                environment: None,
                base_url: base_url.map(|s| s.to_string()),
                error_message: Some(e.to_string()),
            };
            let mut history = state.import_history.write().await;
            history.push(entry);

            Json(ApiResponse::error(format!("Failed to create workspace: {}", e)))
        }
    }
}

pub async fn preview_import(
    State(_state): State<AdminState>,
    Json(request): Json<serde_json::Value>,
) -> Json<ApiResponse<serde_json::Value>> {
    use mockforge_core::import::{
        import_curl_commands, import_insomnia_export, import_postman_collection,
    };

    let content = request.get("content").and_then(|v| v.as_str()).unwrap_or("");
    let filename = request.get("filename").and_then(|v| v.as_str());
    let environment = request.get("environment").and_then(|v| v.as_str());
    let base_url = request.get("base_url").and_then(|v| v.as_str());

    // Detect format from filename or content
    let format = if let Some(fname) = filename {
        if fname.to_lowercase().contains("postman")
            || fname.to_lowercase().ends_with(".postman_collection")
        {
            "postman"
        } else if fname.to_lowercase().contains("insomnia")
            || fname.to_lowercase().ends_with(".insomnia")
        {
            "insomnia"
        } else if fname.to_lowercase().contains("curl")
            || fname.to_lowercase().ends_with(".sh")
            || fname.to_lowercase().ends_with(".curl")
        {
            "curl"
        } else {
            "unknown"
        }
    } else {
        "unknown"
    };

    match format {
        "postman" => match import_postman_collection(content, base_url) {
            Ok(import_result) => {
                let routes: Vec<serde_json::Value> = import_result
                    .routes
                    .into_iter()
                    .map(|route| {
                        serde_json::json!({
                            "method": route.method,
                            "path": route.path,
                            "headers": route.headers,
                            "body": route.body,
                            "status_code": route.response.status,
                            "response": serde_json::json!({
                                "status": route.response.status,
                                "headers": route.response.headers,
                                "body": route.response.body
                            })
                        })
                    })
                    .collect();

                let response = serde_json::json!({
                    "routes": routes,
                    "variables": import_result.variables,
                    "warnings": import_result.warnings
                });

                Json(ApiResponse::success(response))
            }
            Err(e) => Json(ApiResponse::error(format!("Postman import failed: {}", e))),
        },
        "insomnia" => match import_insomnia_export(content, environment) {
            Ok(import_result) => {
                let routes: Vec<serde_json::Value> = import_result
                    .routes
                    .into_iter()
                    .map(|route| {
                        serde_json::json!({
                            "method": route.method,
                            "path": route.path,
                            "headers": route.headers,
                            "body": route.body,
                            "status_code": route.response.status,
                            "response": serde_json::json!({
                                "status": route.response.status,
                                "headers": route.response.headers,
                                "body": route.response.body
                            })
                        })
                    })
                    .collect();

                let response = serde_json::json!({
                    "routes": routes,
                    "variables": import_result.variables,
                    "warnings": import_result.warnings
                });

                Json(ApiResponse::success(response))
            }
            Err(e) => Json(ApiResponse::error(format!("Insomnia import failed: {}", e))),
        },
        "curl" => match import_curl_commands(content, base_url) {
            Ok(import_result) => {
                let routes: Vec<serde_json::Value> = import_result
                    .routes
                    .into_iter()
                    .map(|route| {
                        serde_json::json!({
                            "method": route.method,
                            "path": route.path,
                            "headers": route.headers,
                            "body": route.body,
                            "status_code": route.response.status,
                            "response": serde_json::json!({
                                "status": route.response.status,
                                "headers": route.response.headers,
                                "body": route.response.body
                            })
                        })
                    })
                    .collect();

                let response = serde_json::json!({
                    "routes": routes,
                    "variables": serde_json::json!({}),
                    "warnings": import_result.warnings
                });

                Json(ApiResponse::success(response))
            }
            Err(e) => Json(ApiResponse::error(format!("Curl import failed: {}", e))),
        },
        _ => Json(ApiResponse::error("Unsupported import format".to_string())),
    }
}

pub async fn get_import_history(
    State(state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    let history = state.import_history.read().await;
    let total = history.len();

    let imports: Vec<serde_json::Value> = history
        .iter()
        .rev()
        .take(50)
        .map(|entry| {
            serde_json::json!({
                "id": entry.id,
                "format": entry.format,
                "timestamp": entry.timestamp.to_rfc3339(),
                "routes_count": entry.routes_count,
                "variables_count": entry.variables_count,
                "warnings_count": entry.warnings_count,
                "success": entry.success,
                "filename": entry.filename,
                "environment": entry.environment,
                "base_url": entry.base_url,
                "error_message": entry.error_message
            })
        })
        .collect();

    let response = serde_json::json!({
        "imports": imports,
        "total": total
    });

    Json(ApiResponse::success(response))
}

pub async fn get_admin_api_state(
    State(_state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "status": "active"
    })))
}

pub async fn get_admin_api_replay(
    State(_state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "replay": []
    })))
}

pub async fn get_sse_status(
    State(_state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "available": true,
        "endpoint": "/sse",
        "config": {
            "event_type": "status",
            "interval_ms": 1000,
            "data_template": "{}"
        }
    })))
}

pub async fn get_sse_connections(
    State(_state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "active_connections": 0
    })))
}

// Workspace management functions
pub async fn get_workspaces(
    State(_state): State<AdminState>,
) -> Json<ApiResponse<Vec<serde_json::Value>>> {
    Json(ApiResponse::success(vec![]))
}

pub async fn create_workspace(
    State(_state): State<AdminState>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Workspace created".to_string()))
}

pub async fn open_workspace_from_directory(
    State(_state): State<AdminState>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Workspace opened from directory".to_string()))
}

// Reality Slider API handlers

/// Get current reality level
pub async fn get_reality_level(
    State(state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    let engine = state.reality_engine.read().await;
    let level = engine.get_level().await;
    let config = engine.get_config().await;

    Json(ApiResponse::success(serde_json::json!({
        "level": level.value(),
        "level_name": level.name(),
        "description": level.description(),
        "chaos": {
            "enabled": config.chaos.enabled,
            "error_rate": config.chaos.error_rate,
            "delay_rate": config.chaos.delay_rate,
        },
        "latency": {
            "base_ms": config.latency.base_ms,
            "jitter_ms": config.latency.jitter_ms,
        },
        "mockai": {
            "enabled": config.mockai.enabled,
        },
    })))
}

/// Set reality level
#[derive(Deserialize)]
pub struct SetRealityLevelRequest {
    level: u8,
}

pub async fn set_reality_level(
    State(state): State<AdminState>,
    Json(request): Json<SetRealityLevelRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let level = match mockforge_core::RealityLevel::from_value(request.level) {
        Some(l) => l,
        None => {
            return Json(ApiResponse::error(format!(
                "Invalid reality level: {}. Must be between 1 and 5.",
                request.level
            )));
        }
    };

    // Update reality engine
    let engine = state.reality_engine.write().await;
    engine.set_level(level).await;
    let config = engine.get_config().await;
    drop(engine); // Release lock early

    // Apply hot-reload updates to subsystems
    let mut update_errors = Vec::new();

    // Update chaos config if available
    if let Some(ref chaos_api_state) = state.chaos_api_state {
        let mut chaos_config = chaos_api_state.config.write().await;

        // Convert reality config to chaos config using helper function
        // This ensures proper mapping of all fields
        use mockforge_chaos::config::{FaultInjectionConfig, LatencyConfig};

        let latency_config = if config.latency.base_ms > 0 {
            Some(LatencyConfig {
                enabled: true,
                fixed_delay_ms: Some(config.latency.base_ms),
                random_delay_range_ms: config
                    .latency
                    .max_ms
                    .map(|max| (config.latency.min_ms, max)),
                jitter_percent: if config.latency.jitter_ms > 0 {
                    (config.latency.jitter_ms as f64 / config.latency.base_ms as f64).min(1.0)
                } else {
                    0.0
                },
                probability: 1.0,
            })
        } else {
            None
        };

        let fault_injection_config = if config.chaos.enabled {
            Some(FaultInjectionConfig {
                enabled: true,
                http_errors: config.chaos.status_codes.clone(),
                http_error_probability: config.chaos.error_rate,
                connection_errors: false,
                connection_error_probability: 0.0,
                timeout_errors: config.chaos.inject_timeouts,
                timeout_ms: config.chaos.timeout_ms,
                timeout_probability: if config.chaos.inject_timeouts {
                    config.chaos.error_rate
                } else {
                    0.0
                },
                partial_responses: false,
                partial_response_probability: 0.0,
                payload_corruption: false,
                payload_corruption_probability: 0.0,
                corruption_type: mockforge_chaos::config::CorruptionType::None,
                error_pattern: Some(mockforge_chaos::config::ErrorPattern::Random {
                    probability: config.chaos.error_rate,
                }),
                mockai_enabled: false,
            })
        } else {
            None
        };

        // Update chaos config from converted config
        chaos_config.enabled = config.chaos.enabled;
        chaos_config.latency = latency_config;
        chaos_config.fault_injection = fault_injection_config;

        drop(chaos_config);
        tracing::info!("✅ Updated chaos config for reality level {}", level.value());

        // Update middleware injectors if middleware is accessible
        // Note: The middleware reads from shared config, so injectors will be updated
        // on next request, but we can also trigger an update if middleware is stored
        // For now, the middleware reads config directly, so this is sufficient
    }

    // Update latency injector if available
    if let Some(ref latency_injector) = state.latency_injector {
        match mockforge_core::latency::LatencyInjector::update_profile_async(
            latency_injector,
            config.latency.clone(),
        )
        .await
        {
            Ok(_) => {
                tracing::info!("✅ Updated latency injector for reality level {}", level.value());
            }
            Err(e) => {
                let error_msg = format!("Failed to update latency injector: {}", e);
                tracing::warn!("{}", error_msg);
                update_errors.push(error_msg);
            }
        }
    }

    // Update MockAI if available
    if let Some(ref mockai) = state.mockai {
        match mockforge_core::intelligent_behavior::MockAI::update_config_async(
            mockai,
            config.mockai.clone(),
        )
        .await
        {
            Ok(_) => {
                tracing::info!("✅ Updated MockAI config for reality level {}", level.value());
            }
            Err(e) => {
                let error_msg = format!("Failed to update MockAI: {}", e);
                tracing::warn!("{}", error_msg);
                update_errors.push(error_msg);
            }
        }
    }

    // Build response
    let mut response = serde_json::json!({
        "level": level.value(),
        "level_name": level.name(),
        "description": level.description(),
        "chaos": {
            "enabled": config.chaos.enabled,
            "error_rate": config.chaos.error_rate,
            "delay_rate": config.chaos.delay_rate,
        },
        "latency": {
            "base_ms": config.latency.base_ms,
            "jitter_ms": config.latency.jitter_ms,
        },
        "mockai": {
            "enabled": config.mockai.enabled,
        },
    });

    // Add warnings if any updates failed
    if !update_errors.is_empty() {
        response["warnings"] = serde_json::json!(update_errors);
        tracing::warn!(
            "Reality level updated to {} but some subsystems failed to update: {:?}",
            level.value(),
            update_errors
        );
    } else {
        tracing::info!(
            "✅ Reality level successfully updated to {} (hot-reload applied)",
            level.value()
        );
    }

    Json(ApiResponse::success(response))
}

/// List all available reality presets
pub async fn list_reality_presets(
    State(state): State<AdminState>,
) -> Json<ApiResponse<Vec<serde_json::Value>>> {
    let persistence = &state.workspace_persistence;
    match persistence.list_reality_presets().await {
        Ok(preset_paths) => {
            let presets: Vec<serde_json::Value> = preset_paths
                .iter()
                .map(|path| {
                    serde_json::json!({
                        "id": path.file_name().and_then(|n| n.to_str()).unwrap_or("unknown"),
                        "path": path.to_string_lossy(),
                        "name": path.file_stem().and_then(|n| n.to_str()).unwrap_or("unknown"),
                    })
                })
                .collect();
            Json(ApiResponse::success(presets))
        }
        Err(e) => Json(ApiResponse::error(format!("Failed to list presets: {}", e))),
    }
}

/// Import a reality preset
#[derive(Deserialize)]
pub struct ImportPresetRequest {
    path: String,
}

pub async fn import_reality_preset(
    State(state): State<AdminState>,
    Json(request): Json<ImportPresetRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let persistence = &state.workspace_persistence;
    let path = std::path::Path::new(&request.path);

    match persistence.import_reality_preset(path).await {
        Ok(preset) => {
            // Apply the preset to the reality engine
            let engine = state.reality_engine.write().await;
            engine.apply_preset(preset.clone()).await;

            Json(ApiResponse::success(serde_json::json!({
                "name": preset.name,
                "description": preset.description,
                "level": preset.config.level.value(),
                "level_name": preset.config.level.name(),
            })))
        }
        Err(e) => Json(ApiResponse::error(format!("Failed to import preset: {}", e))),
    }
}

/// Export current reality configuration as a preset
#[derive(Deserialize)]
pub struct ExportPresetRequest {
    name: String,
    description: Option<String>,
}

pub async fn export_reality_preset(
    State(state): State<AdminState>,
    Json(request): Json<ExportPresetRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let engine = state.reality_engine.read().await;
    let preset = engine.create_preset(request.name.clone(), request.description.clone()).await;

    let persistence = &state.workspace_persistence;
    let presets_dir = persistence.presets_dir();
    let filename = format!("{}.json", request.name.replace(' ', "_").to_lowercase());
    let output_path = presets_dir.join(&filename);

    match persistence.export_reality_preset(&preset, &output_path).await {
        Ok(_) => Json(ApiResponse::success(serde_json::json!({
            "name": preset.name,
            "description": preset.description,
            "path": output_path.to_string_lossy(),
            "level": preset.config.level.value(),
        }))),
        Err(e) => Json(ApiResponse::error(format!("Failed to export preset: {}", e))),
    }
}

// Reality Continuum API handlers

/// Get current blend ratio for a path
pub async fn get_continuum_ratio(
    State(state): State<AdminState>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<serde_json::Value>> {
    let path = params.get("path").cloned().unwrap_or_else(|| "/".to_string());
    let engine = state.continuum_engine.read().await;
    let ratio = engine.get_blend_ratio(&path).await;
    let config = engine.get_config().await;
    let enabled = engine.is_enabled().await;

    Json(ApiResponse::success(serde_json::json!({
        "path": path,
        "blend_ratio": ratio,
        "enabled": enabled,
        "transition_mode": format!("{:?}", config.transition_mode),
        "merge_strategy": format!("{:?}", config.merge_strategy),
        "default_ratio": config.default_ratio,
    })))
}

/// Set blend ratio for a path
#[derive(Deserialize)]
pub struct SetContinuumRatioRequest {
    path: String,
    ratio: f64,
}

pub async fn set_continuum_ratio(
    State(state): State<AdminState>,
    Json(request): Json<SetContinuumRatioRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let ratio = request.ratio.clamp(0.0, 1.0);
    let engine = state.continuum_engine.read().await;
    engine.set_blend_ratio(&request.path, ratio).await;

    Json(ApiResponse::success(serde_json::json!({
        "path": request.path,
        "blend_ratio": ratio,
    })))
}

/// Get time schedule
pub async fn get_continuum_schedule(
    State(state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    let engine = state.continuum_engine.read().await;
    let schedule = engine.get_time_schedule().await;

    match schedule {
        Some(s) => Json(ApiResponse::success(serde_json::json!({
            "start_time": s.start_time.to_rfc3339(),
            "end_time": s.end_time.to_rfc3339(),
            "start_ratio": s.start_ratio,
            "end_ratio": s.end_ratio,
            "curve": format!("{:?}", s.curve),
            "duration_days": s.duration().num_days(),
        }))),
        None => Json(ApiResponse::success(serde_json::json!(null))),
    }
}

/// Update time schedule
#[derive(Deserialize)]
pub struct SetContinuumScheduleRequest {
    start_time: String,
    end_time: String,
    start_ratio: f64,
    end_ratio: f64,
    curve: Option<String>,
}

pub async fn set_continuum_schedule(
    State(state): State<AdminState>,
    Json(request): Json<SetContinuumScheduleRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let start_time = chrono::DateTime::parse_from_rfc3339(&request.start_time)
        .map_err(|e| format!("Invalid start_time: {}", e))
        .map(|dt| dt.with_timezone(&Utc));

    let end_time = chrono::DateTime::parse_from_rfc3339(&request.end_time)
        .map_err(|e| format!("Invalid end_time: {}", e))
        .map(|dt| dt.with_timezone(&Utc));

    match (start_time, end_time) {
        (Ok(start), Ok(end)) => {
            let curve = request
                .curve
                .as_deref()
                .map(|c| match c {
                    "linear" => mockforge_core::TransitionCurve::Linear,
                    "exponential" => mockforge_core::TransitionCurve::Exponential,
                    "sigmoid" => mockforge_core::TransitionCurve::Sigmoid,
                    _ => mockforge_core::TransitionCurve::Linear,
                })
                .unwrap_or(mockforge_core::TransitionCurve::Linear);

            let schedule = mockforge_core::TimeSchedule::with_curve(
                start,
                end,
                request.start_ratio.clamp(0.0, 1.0),
                request.end_ratio.clamp(0.0, 1.0),
                curve,
            );

            let engine = state.continuum_engine.read().await;
            engine.set_time_schedule(schedule.clone()).await;

            Json(ApiResponse::success(serde_json::json!({
                "start_time": schedule.start_time.to_rfc3339(),
                "end_time": schedule.end_time.to_rfc3339(),
                "start_ratio": schedule.start_ratio,
                "end_ratio": schedule.end_ratio,
                "curve": format!("{:?}", schedule.curve),
            })))
        }
        (Err(e), _) | (_, Err(e)) => Json(ApiResponse::error(e)),
    }
}

/// Manually advance blend ratio
#[derive(Deserialize)]
pub struct AdvanceContinuumRatioRequest {
    increment: Option<f64>,
}

pub async fn advance_continuum_ratio(
    State(state): State<AdminState>,
    Json(request): Json<AdvanceContinuumRatioRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let increment = request.increment.unwrap_or(0.1);
    let engine = state.continuum_engine.read().await;
    engine.advance_ratio(increment).await;
    let config = engine.get_config().await;

    Json(ApiResponse::success(serde_json::json!({
        "default_ratio": config.default_ratio,
        "increment": increment,
    })))
}

/// Enable or disable continuum
#[derive(Deserialize)]
pub struct SetContinuumEnabledRequest {
    enabled: bool,
}

pub async fn set_continuum_enabled(
    State(state): State<AdminState>,
    Json(request): Json<SetContinuumEnabledRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
    let engine = state.continuum_engine.read().await;
    engine.set_enabled(request.enabled).await;

    Json(ApiResponse::success(serde_json::json!({
        "enabled": request.enabled,
    })))
}

/// Get all manual overrides
pub async fn get_continuum_overrides(
    State(state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    let engine = state.continuum_engine.read().await;
    let overrides = engine.get_manual_overrides().await;

    Json(ApiResponse::success(serde_json::json!(overrides)))
}

/// Clear all manual overrides
pub async fn clear_continuum_overrides(
    State(state): State<AdminState>,
) -> Json<ApiResponse<serde_json::Value>> {
    let engine = state.continuum_engine.read().await;
    engine.clear_manual_overrides().await;

    Json(ApiResponse::success(serde_json::json!({
        "message": "All manual overrides cleared",
    })))
}

pub async fn get_workspace(
    State(_state): State<AdminState>,
    Path(workspace_id): Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "workspace": {
            "summary": {
                "id": workspace_id,
                "name": "Mock Workspace",
                "description": "A mock workspace"
            },
            "folders": [],
            "requests": []
        }
    })))
}

pub async fn delete_workspace(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Workspace deleted".to_string()))
}

pub async fn set_active_workspace(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Workspace activated".to_string()))
}

pub async fn create_folder(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Folder created".to_string()))
}

pub async fn create_request(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Request created".to_string()))
}

pub async fn execute_workspace_request(
    State(_state): State<AdminState>,
    Path((_workspace_id, _request_id)): Path<(String, String)>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "status": "executed",
        "response": {}
    })))
}

pub async fn get_request_history(
    State(_state): State<AdminState>,
    Path((_workspace_id, _request_id)): Path<(String, String)>,
) -> Json<ApiResponse<Vec<serde_json::Value>>> {
    Json(ApiResponse::success(vec![]))
}

pub async fn get_folder(
    State(_state): State<AdminState>,
    Path((_workspace_id, folder_id)): Path<(String, String)>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "folder": {
            "summary": {
                "id": folder_id,
                "name": "Mock Folder",
                "description": "A mock folder"
            },
            "requests": []
        }
    })))
}

pub async fn import_to_workspace(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Import to workspace completed".to_string()))
}

pub async fn export_workspaces(
    State(_state): State<AdminState>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Workspaces exported".to_string()))
}

// Environment management functions
pub async fn get_environments(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
    // Return a default global environment
    let environments = vec![serde_json::json!({
        "id": "global",
        "name": "Global",
        "description": "Global environment variables",
        "variable_count": 0,
        "is_global": true,
        "active": true,
        "order": 0
    })];

    Json(ApiResponse::success(serde_json::json!({
        "environments": environments,
        "total": 1
    })))
}

pub async fn create_environment(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment created".to_string()))
}

pub async fn update_environment(
    State(_state): State<AdminState>,
    Path((_workspace_id, _environment_id)): Path<(String, String)>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment updated".to_string()))
}

pub async fn delete_environment(
    State(_state): State<AdminState>,
    Path((_workspace_id, _environment_id)): Path<(String, String)>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment deleted".to_string()))
}

pub async fn set_active_environment(
    State(_state): State<AdminState>,
    Path((_workspace_id, _environment_id)): Path<(String, String)>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment activated".to_string()))
}

pub async fn update_environments_order(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment order updated".to_string()))
}

pub async fn get_environment_variables(
    State(_state): State<AdminState>,
    Path((_workspace_id, _environment_id)): Path<(String, String)>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "variables": []
    })))
}

pub async fn set_environment_variable(
    State(_state): State<AdminState>,
    Path((_workspace_id, _environment_id)): Path<(String, String)>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment variable set".to_string()))
}

pub async fn remove_environment_variable(
    State(_state): State<AdminState>,
    Path((_workspace_id, _environment_id, _variable_name)): Path<(String, String, String)>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Environment variable removed".to_string()))
}

// Autocomplete functions
pub async fn get_autocomplete_suggestions(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "suggestions": [],
        "start_position": 0,
        "end_position": 0
    })))
}

// Sync management functions
pub async fn get_sync_status(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
    Json(ApiResponse::success(serde_json::json!({
        "status": "disabled"
    })))
}

pub async fn configure_sync(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Sync configured".to_string()))
}

pub async fn disable_sync(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Sync disabled".to_string()))
}

pub async fn trigger_sync(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Sync triggered".to_string()))
}

pub async fn get_sync_changes(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
) -> Json<ApiResponse<Vec<serde_json::Value>>> {
    Json(ApiResponse::success(vec![]))
}

pub async fn confirm_sync_changes(
    State(_state): State<AdminState>,
    Path(_workspace_id): Path<String>,
    Json(_request): Json<serde_json::Value>,
) -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Sync changes confirmed".to_string()))
}

// Missing functions that routes.rs expects
pub async fn clear_import_history(State(state): State<AdminState>) -> Json<ApiResponse<String>> {
    let mut history = state.import_history.write().await;
    history.clear();
    Json(ApiResponse::success("Import history cleared".to_string()))
}

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

    #[test]
    fn test_request_metrics_creation() {
        use std::collections::HashMap;

        let metrics = RequestMetrics {
            total_requests: 100,
            active_connections: 5,
            requests_by_endpoint: HashMap::new(),
            response_times: vec![10, 20, 30],
            response_times_by_endpoint: HashMap::new(),
            errors_by_endpoint: HashMap::new(),
            last_request_by_endpoint: HashMap::new(),
        };

        assert_eq!(metrics.total_requests, 100);
        assert_eq!(metrics.active_connections, 5);
        assert_eq!(metrics.response_times.len(), 3);
    }

    #[test]
    fn test_system_metrics_creation() {
        let metrics = SystemMetrics {
            cpu_usage_percent: 45.5,
            memory_usage_mb: 100,
            active_threads: 10,
        };

        assert_eq!(metrics.active_threads, 10);
        assert!(metrics.cpu_usage_percent > 0.0);
        assert_eq!(metrics.memory_usage_mb, 100);
    }

    #[test]
    fn test_time_series_point() {
        let point = TimeSeriesPoint {
            timestamp: Utc::now(),
            value: 42.5,
        };

        assert_eq!(point.value, 42.5);
    }

    #[test]
    fn test_restart_status() {
        let status = RestartStatus {
            in_progress: true,
            initiated_at: Some(Utc::now()),
            reason: Some("Manual restart".to_string()),
            success: None,
        };

        assert!(status.in_progress);
        assert!(status.reason.is_some());
    }

    #[test]
    fn test_configuration_state() {
        use std::collections::HashMap;

        let state = ConfigurationState {
            latency_profile: LatencyProfile {
                name: "default".to_string(),
                base_ms: 100,
                jitter_ms: 10,
                tag_overrides: HashMap::new(),
            },
            fault_config: FaultConfig {
                enabled: false,
                failure_rate: 0.0,
                status_codes: vec![],
                active_failures: 0,
            },
            proxy_config: ProxyConfig {
                enabled: false,
                upstream_url: None,
                timeout_seconds: 30,
                requests_proxied: 0,
            },
            validation_settings: ValidationSettings {
                mode: "off".to_string(),
                aggregate_errors: false,
                validate_responses: false,
                overrides: HashMap::new(),
            },
            traffic_shaping: TrafficShapingConfig {
                enabled: false,
                bandwidth: crate::models::BandwidthConfig {
                    enabled: false,
                    max_bytes_per_sec: 1_048_576,
                    burst_capacity_bytes: 10_485_760,
                    tag_overrides: HashMap::new(),
                },
                burst_loss: crate::models::BurstLossConfig {
                    enabled: false,
                    burst_probability: 0.1,
                    burst_duration_ms: 5000,
                    loss_rate_during_burst: 0.5,
                    recovery_time_ms: 30000,
                    tag_overrides: HashMap::new(),
                },
            },
        };

        assert_eq!(state.latency_profile.name, "default");
        assert!(!state.fault_config.enabled);
        assert!(!state.proxy_config.enabled);
    }

    #[test]
    fn test_admin_state_new() {
        let http_addr: std::net::SocketAddr = "127.0.0.1:3000".parse().unwrap();
        let state = AdminState::new(
            Some(http_addr),
            None,
            None,
            None,
            true,
            8080,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );

        assert_eq!(state.http_server_addr, Some(http_addr));
        assert!(state.api_enabled);
        assert_eq!(state.admin_port, 8080);
    }
}