mockforge-http 0.3.116

HTTP/REST protocol support for MockForge
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
//! # MockForge HTTP
//!
//! HTTP/REST API mocking library for MockForge.
//!
//! This crate provides HTTP-specific functionality for creating mock REST APIs,
//! including OpenAPI integration, request validation, AI-powered response generation,
//! and management endpoints.
//!
//! ## Overview
//!
//! MockForge HTTP enables you to:
//!
//! - **Serve OpenAPI specs**: Automatically generate mock endpoints from OpenAPI/Swagger
//! - **Validate requests**: Enforce schema validation with configurable modes
//! - **AI-powered responses**: Generate intelligent responses using LLMs
//! - **Management API**: Real-time monitoring, configuration, and control
//! - **Request logging**: Comprehensive HTTP request/response logging
//! - **Metrics collection**: Track performance and usage statistics
//! - **Server-Sent Events**: Stream logs and metrics to clients
//!
//! ## Quick Start
//!
//! ### Basic HTTP Server from OpenAPI
//!
//! ```rust,no_run
//! use axum::Router;
//! use mockforge_core::openapi_routes::ValidationMode;
//! use mockforge_core::ValidationOptions;
//! use mockforge_http::build_router;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Build router from OpenAPI specification
//!     let router = build_router(
//!         Some("./api-spec.json".to_string()),
//!         Some(ValidationOptions {
//!             request_mode: ValidationMode::Enforce,
//!             ..ValidationOptions::default()
//!         }),
//!         None,
//!     ).await;
//!
//!     // Start the server
//!     let addr: std::net::SocketAddr = "0.0.0.0:3000".parse()?;
//!     let listener = tokio::net::TcpListener::bind(addr).await?;
//!     axum::serve(listener, router).await?;
//!
//!     Ok(())
//! }
//! ```
//!
//! ### With Management API
//!
//! Enable real-time monitoring and configuration:
//!
//! ```rust,no_run
//! use mockforge_http::{management_router, ManagementState};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let state = ManagementState::new(None, None, 3000);
//!
//! // Build management router
//! let mgmt_router = management_router(state);
//!
//! // Mount under your main router
//! let app = axum::Router::new()
//!     .nest("/__mockforge", mgmt_router);
//! # Ok(())
//! # }
//! ```
//!
//! ### AI-Powered Responses
//!
//! Generate intelligent responses based on request context:
//!
//! ```rust,no_run
//! use mockforge_data::intelligent_mock::{IntelligentMockConfig, ResponseMode};
//! use mockforge_http::{process_response_with_ai, AiResponseConfig};
//! use serde_json::json;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let ai_config = AiResponseConfig {
//!     intelligent: Some(
//!         IntelligentMockConfig::new(ResponseMode::Intelligent)
//!             .with_prompt("Generate realistic user data".to_string()),
//!     ),
//!     drift: None,
//! };
//!
//! let response = process_response_with_ai(
//!     Some(json!({"name": "Alice"})),
//!     ai_config
//!         .intelligent
//!         .clone()
//!         .map(serde_json::to_value)
//!         .transpose()?,
//!     ai_config
//!         .drift
//!         .clone()
//!         .map(serde_json::to_value)
//!         .transpose()?,
//! )
//! .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Key Features
//!
//! ### OpenAPI Integration
//! - Automatic endpoint generation from specs
//! - Request/response validation
//! - Schema-based mock data generation
//!
//! ### Management & Monitoring
//! - [`management`]: REST API for server control and monitoring
//! - [`management_ws`]: WebSocket API for real-time updates
//! - [`sse`]: Server-Sent Events for log streaming
//! - [`request_logging`]: Comprehensive request/response logging
//! - [`metrics_middleware`]: Performance metrics collection
//!
//! ### Advanced Features
//! - [`ai_handler`]: AI-powered response generation
//! - [`auth`]: Authentication and authorization
//! - [`chain_handlers`]: Multi-step request workflows
//! - [`latency_profiles`]: Configurable latency simulation
//! - [`replay_listing`]: Fixture management
//!
//! ## Middleware
//!
//! MockForge HTTP includes several middleware layers:
//!
//! - **Request Tracing**: [`http_tracing_middleware`] - Distributed tracing integration
//! - **Metrics Collection**: [`metrics_middleware`] - Prometheus-compatible metrics
//! - **Operation Metadata**: [`op_middleware`] - OpenAPI operation tracking
//!
//! ## Management API Endpoints
//!
//! When using the management router, these endpoints are available:
//!
//! - `GET /health` - Health check
//! - `GET /stats` - Server statistics
//! - `GET /logs` - Request logs (SSE stream)
//! - `GET /metrics` - Performance metrics
//! - `GET /fixtures` - List available fixtures
//! - `POST /config/*` - Update configuration
//!
//! ## Examples
//!
//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
//! for complete working examples.
//!
//! ## Related Crates
//!
//! - [`mockforge-core`](https://docs.rs/mockforge-core): Core mocking functionality
//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
//!
//! ## Documentation
//!
//! - [MockForge Book](https://docs.mockforge.dev/)
//! - [HTTP Mocking Guide](https://docs.mockforge.dev/user-guide/http-mocking.html)
//! - [API Reference](https://docs.rs/mockforge-http)

pub mod ai_handler;
pub mod auth;
pub mod chain_handlers;
/// Cross-protocol consistency engine integration for HTTP
pub mod consistency;
/// Contract diff middleware for automatic request capture
pub mod contract_diff_middleware;
pub mod coverage;
pub mod database;
/// File generation service for creating mock PDF, CSV, JSON files
pub mod file_generator;
/// File serving for generated mock files
pub mod file_server;
/// Kubernetes-native health check endpoints (liveness, readiness, startup probes)
pub mod health;
pub mod http_tracing_middleware;
/// Latency profile configuration for HTTP request simulation
pub mod latency_profiles;
/// Management API for server control and monitoring
pub mod management;
/// WebSocket-based management API for real-time updates
pub mod management_ws;
pub mod metrics_middleware;
pub mod middleware;
pub mod op_middleware;
/// Unified protocol server lifecycle implementation
pub mod protocol_server;
/// Browser/Mobile Proxy Server
pub mod proxy_server;
/// Quick mock generation utilities
pub mod quick_mock;
/// RAG-powered AI response generation
pub mod rag_ai_generator;
/// Replay listing and fixture management
pub mod replay_listing;
pub mod request_logging;
/// Specification import API for OpenAPI and AsyncAPI
pub mod spec_import;
/// Server-Sent Events for streaming logs and metrics
pub mod sse;
/// State machine API for scenario state machines
pub mod state_machine_api;
/// TLS/HTTPS support
pub mod tls;
/// Token response utilities
pub mod token_response;
/// UI Builder API for low-code mock endpoint creation
pub mod ui_builder;
/// Verification API for request verification
pub mod verification;

// Access review handlers
pub mod handlers;

// Re-export AI handler utilities
pub use ai_handler::{process_response_with_ai, AiResponseConfig, AiResponseHandler};
// Re-export health check utilities
pub use health::{HealthManager, ServiceStatus};

// Re-export management API utilities
pub use management::{
    management_router, management_router_with_ui_builder, ManagementState, MockConfig,
    ServerConfig, ServerStats,
};

// Re-export UI Builder utilities
pub use ui_builder::{create_ui_builder_router, EndpointConfig, UIBuilderState};

// Re-export management WebSocket utilities
pub use management_ws::{ws_management_router, MockEvent, WsManagementState};

// Re-export verification API utilities
pub use verification::verification_router;

// Re-export metrics middleware
pub use metrics_middleware::collect_http_metrics;

// Re-export tracing middleware
pub use http_tracing_middleware::http_tracing_middleware;

// Re-export coverage utilities
pub use coverage::{calculate_coverage, CoverageReport, MethodCoverage, RouteCoverage};

/// Helper function to load persona from config file
/// Tries to load from common config locations: config.yaml, mockforge.yaml, tools/mockforge/config.yaml
async fn load_persona_from_config() -> Option<Arc<Persona>> {
    use mockforge_core::config::load_config;

    // Try common config file locations
    let config_paths = [
        "config.yaml",
        "mockforge.yaml",
        "tools/mockforge/config.yaml",
        "../tools/mockforge/config.yaml",
    ];

    for path in &config_paths {
        if let Ok(config) = load_config(path).await {
            // Access intelligent_behavior through mockai config
            // Note: Config structure is mockai.intelligent_behavior.personas
            if let Some(persona) = config.mockai.intelligent_behavior.personas.get_active_persona()
            {
                tracing::info!(
                    "Loaded active persona '{}' from config file: {}",
                    persona.name,
                    path
                );
                return Some(Arc::new(persona.clone()));
            } else {
                tracing::debug!(
                    "No active persona found in config file: {} (personas count: {})",
                    path,
                    config.mockai.intelligent_behavior.personas.personas.len()
                );
            }
        } else {
            tracing::debug!("Could not load config from: {}", path);
        }
    }

    tracing::debug!("No persona found in config files, persona-based generation will be disabled");
    None
}

use axum::extract::State;
use axum::middleware::from_fn_with_state;
use axum::response::Json;
use axum::Router;
use mockforge_chaos::core_failure_injection::{FailureConfig, FailureInjector};
use mockforge_core::intelligent_behavior::config::Persona;
use mockforge_core::latency::LatencyInjector;
use mockforge_core::openapi::OpenApiSpec;
use mockforge_core::openapi_routes::OpenApiRouteRegistry;
use mockforge_core::openapi_routes::ValidationOptions;
use std::sync::Arc;
use tower_http::cors::{Any, CorsLayer};

use mockforge_core::LatencyProfile;
#[cfg(feature = "data-faker")]
use mockforge_data::provider::register_core_faker_provider;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::Path;
use tokio::fs;
use tokio::sync::RwLock;
use tracing::*;

/// Route info for storing in state
#[derive(Clone)]
pub struct RouteInfo {
    /// HTTP method (GET, POST, PUT, etc.)
    pub method: String,
    /// API path pattern (e.g., "/api/users/{id}")
    pub path: String,
    /// OpenAPI operation ID if available
    pub operation_id: Option<String>,
    /// Operation summary from OpenAPI spec
    pub summary: Option<String>,
    /// Operation description from OpenAPI spec
    pub description: Option<String>,
    /// List of parameter names for this route
    pub parameters: Vec<String>,
}

/// Shared state for tracking OpenAPI routes
#[derive(Clone)]
pub struct HttpServerState {
    /// List of registered routes from OpenAPI spec
    pub routes: Vec<RouteInfo>,
    /// Optional global rate limiter for request throttling
    pub rate_limiter: Option<Arc<middleware::rate_limit::GlobalRateLimiter>>,
    /// Production headers to add to all responses (for deceptive deploy)
    pub production_headers: Option<Arc<HashMap<String, String>>>,
}

impl Default for HttpServerState {
    fn default() -> Self {
        Self::new()
    }
}

impl HttpServerState {
    /// Create a new empty HTTP server state
    pub fn new() -> Self {
        Self {
            routes: Vec::new(),
            rate_limiter: None,
            production_headers: None,
        }
    }

    /// Create HTTP server state with pre-configured routes
    pub fn with_routes(routes: Vec<RouteInfo>) -> Self {
        Self {
            routes,
            rate_limiter: None,
            production_headers: None,
        }
    }

    /// Add a rate limiter to the HTTP server state
    pub fn with_rate_limiter(
        mut self,
        rate_limiter: Arc<middleware::rate_limit::GlobalRateLimiter>,
    ) -> Self {
        self.rate_limiter = Some(rate_limiter);
        self
    }

    /// Add production headers to the HTTP server state
    pub fn with_production_headers(mut self, headers: Arc<HashMap<String, String>>) -> Self {
        self.production_headers = Some(headers);
        self
    }
}

/// Handler to return OpenAPI routes information
async fn get_routes_handler(State(state): State<HttpServerState>) -> Json<serde_json::Value> {
    let route_info: Vec<serde_json::Value> = state
        .routes
        .iter()
        .map(|route| {
            serde_json::json!({
                "method": route.method,
                "path": route.path,
                "operation_id": route.operation_id,
                "summary": route.summary,
                "description": route.description,
                "parameters": route.parameters
            })
        })
        .collect();

    Json(serde_json::json!({
        "routes": route_info,
        "total": state.routes.len()
    }))
}

/// Handler to serve the Scalar API docs page
async fn get_docs_handler() -> axum::response::Html<&'static str> {
    axum::response::Html(include_str!("../static/docs.html"))
}

/// Build the base HTTP router, optionally from an OpenAPI spec.
pub async fn build_router(
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    failure_config: Option<FailureConfig>,
) -> Router {
    build_router_with_multi_tenant(
        spec_path,
        options,
        failure_config,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await
}

/// Apply CORS middleware to the router based on configuration
fn apply_cors_middleware(
    app: Router,
    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
) -> Router {
    use http::Method;
    use tower_http::cors::AllowOrigin;

    if let Some(config) = cors_config {
        if !config.enabled {
            return app;
        }

        let mut cors_layer = CorsLayer::new();
        let is_wildcard_origin;

        // Configure allowed origins
        if config.allowed_origins.contains(&"*".to_string()) {
            cors_layer = cors_layer.allow_origin(Any);
            is_wildcard_origin = true;
        } else if !config.allowed_origins.is_empty() {
            // Try to parse each origin, fallback to permissive if parsing fails
            let origins: Vec<_> = config
                .allowed_origins
                .iter()
                .filter_map(|origin| {
                    origin.parse::<http::HeaderValue>().ok().map(AllowOrigin::exact)
                })
                .collect();

            if origins.is_empty() {
                // If no valid origins, use permissive for development
                warn!("No valid CORS origins configured, using permissive CORS");
                cors_layer = cors_layer.allow_origin(Any);
                is_wildcard_origin = true;
            } else {
                // Use the first origin as exact match (tower-http limitation)
                // For multiple origins, we'd need a custom implementation
                if origins.len() == 1 {
                    cors_layer = cors_layer.allow_origin(origins[0].clone());
                    is_wildcard_origin = false;
                } else {
                    // Multiple origins - use permissive for now
                    warn!(
                        "Multiple CORS origins configured, using permissive CORS. \
                        Consider using '*' for all origins."
                    );
                    cors_layer = cors_layer.allow_origin(Any);
                    is_wildcard_origin = true;
                }
            }
        } else {
            // No origins specified, use permissive for development
            cors_layer = cors_layer.allow_origin(Any);
            is_wildcard_origin = true;
        }

        // Configure allowed methods
        if !config.allowed_methods.is_empty() {
            let methods: Vec<Method> =
                config.allowed_methods.iter().filter_map(|m| m.parse().ok()).collect();
            if !methods.is_empty() {
                cors_layer = cors_layer.allow_methods(methods);
            }
        } else {
            // Default to common HTTP methods
            cors_layer = cors_layer.allow_methods([
                Method::GET,
                Method::POST,
                Method::PUT,
                Method::DELETE,
                Method::PATCH,
                Method::OPTIONS,
            ]);
        }

        // Configure allowed headers
        if !config.allowed_headers.is_empty() {
            let headers: Vec<_> = config
                .allowed_headers
                .iter()
                .filter_map(|h| h.parse::<http::HeaderName>().ok())
                .collect();
            if !headers.is_empty() {
                cors_layer = cors_layer.allow_headers(headers);
            }
        } else {
            // Default headers
            cors_layer =
                cors_layer.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);
        }

        // Configure credentials - cannot allow credentials with wildcard origin
        // Determine if credentials should be allowed
        // Cannot allow credentials with wildcard origin per CORS spec
        let should_allow_credentials = if is_wildcard_origin {
            // Wildcard origin - credentials must be false
            false
        } else {
            // Specific origins - use config value (defaults to false)
            config.allow_credentials
        };

        cors_layer = cors_layer.allow_credentials(should_allow_credentials);

        info!(
            "CORS middleware enabled with configured settings (credentials: {})",
            should_allow_credentials
        );
        app.layer(cors_layer)
    } else {
        // No CORS config provided - use permissive CORS for development
        // Note: permissive() allows credentials, but since it uses wildcard origin,
        // we need to disable credentials to avoid CORS spec violation
        debug!("No CORS config provided, using permissive CORS for development");
        // Create a permissive CORS layer but disable credentials to avoid CORS spec violation
        // (cannot combine credentials with wildcard origin)
        app.layer(CorsLayer::permissive().allow_credentials(false))
    }
}

/// Build the base HTTP router with multi-tenant workspace support
#[allow(clippy::too_many_arguments)]
pub async fn build_router_with_multi_tenant(
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    failure_config: Option<FailureConfig>,
    multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
    _route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
    ai_generator: Option<Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>>,
    smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
    mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
    deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
) -> Router {
    use std::time::Instant;

    let startup_start = Instant::now();

    // Set up the basic router
    let mut app = Router::new();

    // Initialize rate limiter with default configuration
    // Can be customized via environment variables or config
    let mut rate_limit_config = middleware::RateLimitConfig {
        requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(1000),
        burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(2000),
        per_ip: true,
        per_endpoint: false,
    };

    // Apply deceptive deploy configuration if enabled
    let mut final_cors_config = cors_config;
    let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
    // Auth config from deceptive deploy OAuth (if configured)
    let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;

    if let Some(deploy_config) = &deceptive_deploy_config {
        if deploy_config.enabled {
            info!("Deceptive deploy mode enabled - applying production-like configuration");

            // Override CORS config if provided
            if let Some(prod_cors) = &deploy_config.cors {
                final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
                    enabled: true,
                    allowed_origins: prod_cors.allowed_origins.clone(),
                    allowed_methods: prod_cors.allowed_methods.clone(),
                    allowed_headers: prod_cors.allowed_headers.clone(),
                    allow_credentials: prod_cors.allow_credentials,
                });
                info!("Applied production-like CORS configuration");
            }

            // Override rate limit config if provided
            if let Some(prod_rate_limit) = &deploy_config.rate_limit {
                rate_limit_config = middleware::RateLimitConfig {
                    requests_per_minute: prod_rate_limit.requests_per_minute,
                    burst: prod_rate_limit.burst,
                    per_ip: prod_rate_limit.per_ip,
                    per_endpoint: false,
                };
                info!(
                    "Applied production-like rate limiting: {} req/min, burst: {}",
                    prod_rate_limit.requests_per_minute, prod_rate_limit.burst
                );
            }

            // Set production headers
            if !deploy_config.headers.is_empty() {
                let headers_map: HashMap<String, String> = deploy_config.headers.clone();
                production_headers = Some(std::sync::Arc::new(headers_map));
                info!("Configured {} production headers", deploy_config.headers.len());
            }

            // Integrate OAuth config from deceptive deploy
            if let Some(prod_oauth) = &deploy_config.oauth {
                let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
                deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
                    oauth2: Some(oauth2_config),
                    ..Default::default()
                });
                info!("Applied production-like OAuth configuration for deceptive deploy");
            }
        }
    }

    let rate_limiter =
        std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));

    let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());

    // Add production headers to state if configured
    if let Some(headers) = production_headers.clone() {
        state = state.with_production_headers(headers);
    }

    // Clone spec_path for later use
    let spec_path_for_mgmt = spec_path.clone();

    // If an OpenAPI spec is provided, integrate it
    if let Some(spec_path) = spec_path {
        tracing::debug!("Processing OpenAPI spec path: {}", spec_path);

        // Measure OpenAPI spec loading
        let spec_load_start = Instant::now();
        match OpenApiSpec::from_file(&spec_path).await {
            Ok(openapi) => {
                let spec_load_duration = spec_load_start.elapsed();
                info!(
                    "Successfully loaded OpenAPI spec from {} (took {:?})",
                    spec_path, spec_load_duration
                );

                // Measure route registry creation
                tracing::debug!("Creating OpenAPI route registry...");
                let registry_start = Instant::now();

                // Try to load persona from config if available
                let persona = load_persona_from_config().await;

                let registry = if let Some(opts) = options {
                    tracing::debug!("Using custom validation options");
                    if let Some(ref persona) = persona {
                        tracing::info!("Using persona '{}' for route generation", persona.name);
                    }
                    OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
                } else {
                    tracing::debug!("Using environment-based options");
                    if let Some(ref persona) = persona {
                        tracing::info!("Using persona '{}' for route generation", persona.name);
                    }
                    OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
                };
                let registry_duration = registry_start.elapsed();
                info!(
                    "Created OpenAPI route registry with {} routes (took {:?})",
                    registry.routes().len(),
                    registry_duration
                );

                // Measure route extraction
                let extract_start = Instant::now();
                let route_info: Vec<RouteInfo> = registry
                    .routes()
                    .iter()
                    .map(|route| RouteInfo {
                        method: route.method.clone(),
                        path: route.path.clone(),
                        operation_id: route.operation.operation_id.clone(),
                        summary: route.operation.summary.clone(),
                        description: route.operation.description.clone(),
                        parameters: route.parameters.clone(),
                    })
                    .collect();
                state.routes = route_info;
                let extract_duration = extract_start.elapsed();
                debug!("Extracted route information (took {:?})", extract_duration);

                // Measure overrides loading
                let overrides = if std::env::var("MOCKFORGE_HTTP_OVERRIDES_GLOB").is_ok() {
                    tracing::debug!("Loading overrides from environment variable");
                    let overrides_start = Instant::now();
                    match mockforge_core::Overrides::load_from_globs(&[]).await {
                        Ok(overrides) => {
                            let overrides_duration = overrides_start.elapsed();
                            info!(
                                "Loaded {} override rules (took {:?})",
                                overrides.rules().len(),
                                overrides_duration
                            );
                            Some(overrides)
                        }
                        Err(e) => {
                            tracing::warn!("Failed to load overrides: {}", e);
                            None
                        }
                    }
                } else {
                    None
                };

                // Measure router building
                let router_build_start = Instant::now();
                let overrides_enabled = overrides.is_some();
                let openapi_router = if let Some(mockai_instance) = &mockai {
                    tracing::debug!("Building router with MockAI support");
                    registry.build_router_with_mockai(Some(mockai_instance.clone()))
                } else if let Some(ai_generator) = &ai_generator {
                    tracing::debug!("Building router with AI generator support");
                    registry.build_router_with_ai(Some(ai_generator.clone()))
                } else if let Some(failure_config) = &failure_config {
                    tracing::debug!("Building router with failure injection and overrides");
                    let failure_injector = FailureInjector::new(Some(failure_config.clone()), true);
                    registry.build_router_with_injectors_and_overrides(
                        LatencyInjector::default(),
                        Some(failure_injector),
                        overrides,
                        overrides_enabled,
                    )
                } else {
                    tracing::debug!("Building router with overrides");
                    registry.build_router_with_injectors_and_overrides(
                        LatencyInjector::default(),
                        None,
                        overrides,
                        overrides_enabled,
                    )
                };
                let router_build_duration = router_build_start.elapsed();
                debug!("Built OpenAPI router (took {:?})", router_build_duration);

                tracing::debug!("Merging OpenAPI router with main router");
                app = app.merge(openapi_router);
                tracing::debug!("Router built successfully");
            }
            Err(e) => {
                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
            }
        }
    }

    // Add basic health check endpoint
    app = app.route(
        "/health",
        axum::routing::get(|| async {
            use mockforge_core::server_utils::health::HealthStatus;
            {
                // HealthStatus should always serialize, but handle errors gracefully
                match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
                    Ok(value) => Json(value),
                    Err(e) => {
                        // Log error but return a simple healthy response
                        tracing::error!("Failed to serialize health status: {}", e);
                        Json(serde_json::json!({
                            "status": "healthy",
                            "service": "mockforge-http",
                            "uptime_seconds": 0
                        }))
                    }
                }
            }
        }),
    )
    // Add SSE endpoints
    .merge(sse::sse_router())
    // Add file serving endpoints for generated mock files
    .merge(file_server::file_serving_router());

    // Clone state for routes_router since we'll use it for middleware too
    let state_for_routes = state.clone();

    // Create a router with state for the routes and coverage endpoints
    let routes_router = Router::new()
        .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
        .route("/__mockforge/coverage", axum::routing::get(coverage::get_coverage_handler))
        .with_state(state_for_routes);

    // Merge the routes router with the main app
    app = app.merge(routes_router);

    // Add API docs page (Scalar-powered interactive explorer)
    app = app.route("/__mockforge/docs", axum::routing::get(get_docs_handler));

    // Add static coverage UI
    // Determine the path to the coverage.html file
    let coverage_html_path = std::env::var("MOCKFORGE_COVERAGE_UI_PATH")
        .unwrap_or_else(|_| "crates/mockforge-http/static/coverage.html".to_string());

    // Check if the file exists before serving it
    if Path::new(&coverage_html_path).exists() {
        app = app.nest_service(
            "/__mockforge/coverage.html",
            tower_http::services::ServeFile::new(&coverage_html_path),
        );
        debug!("Serving coverage UI from: {}", coverage_html_path);
    } else {
        debug!(
            "Coverage UI file not found at: {}. Skipping static file serving.",
            coverage_html_path
        );
    }

    // Add management API endpoints
    // Load spec for ManagementState so /__mockforge/api/spec can serve it
    let mgmt_spec = if let Some(ref sp) = spec_path_for_mgmt {
        match OpenApiSpec::from_file(sp).await {
            Ok(s) => Some(Arc::new(s)),
            Err(e) => {
                debug!("Failed to load OpenAPI spec for management API: {}", e);
                None
            }
        }
    } else {
        None
    };
    let mgmt_port = std::env::var("PORT")
        .or_else(|_| std::env::var("MOCKFORGE_HTTP_PORT"))
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(3000);
    let management_state = ManagementState::new(mgmt_spec, spec_path_for_mgmt, mgmt_port);

    // Create WebSocket state and connect it to management state
    use std::sync::Arc;
    let ws_state = WsManagementState::new();
    let ws_broadcast = Arc::new(ws_state.tx.clone());
    let management_state = management_state.with_ws_broadcast(ws_broadcast);

    // Note: ProxyConfig not available in this build function path
    // Migration endpoints will work once ProxyConfig is passed to build_router_with_chains_and_multi_tenant

    #[cfg(feature = "smtp")]
    let management_state = {
        if let Some(smtp_reg) = smtp_registry {
            match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
                Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
                Err(e) => {
                    error!(
                        "Invalid SMTP registry type passed to HTTP management state: {:?}",
                        e.type_id()
                    );
                    management_state
                }
            }
        } else {
            management_state
        }
    };
    #[cfg(not(feature = "smtp"))]
    let management_state = management_state;
    #[cfg(not(feature = "smtp"))]
    let _ = smtp_registry;
    app = app.nest("/__mockforge/api", management_router(management_state));

    // Add verification API endpoint
    app = app.merge(verification_router());

    // Add OIDC well-known endpoints
    use crate::auth::oidc::oidc_router;
    app = app.merge(oidc_router());

    // Add access review API if enabled
    {
        use mockforge_core::security::get_global_access_review_service;
        if let Some(service) = get_global_access_review_service().await {
            use crate::handlers::access_review::{access_review_router, AccessReviewState};
            let review_state = AccessReviewState { service };
            app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
            debug!("Access review API mounted at /api/v1/security/access-reviews");
        }
    }

    // Add privileged access API if enabled
    {
        use mockforge_core::security::get_global_privileged_access_manager;
        if let Some(manager) = get_global_privileged_access_manager().await {
            use crate::handlers::privileged_access::{
                privileged_access_router, PrivilegedAccessState,
            };
            let privileged_state = PrivilegedAccessState { manager };
            app = app.nest(
                "/api/v1/security/privileged-access",
                privileged_access_router(privileged_state),
            );
            debug!("Privileged access API mounted at /api/v1/security/privileged-access");
        }
    }

    // Add change management API if enabled
    {
        use mockforge_core::security::get_global_change_management_engine;
        if let Some(engine) = get_global_change_management_engine().await {
            use crate::handlers::change_management::{
                change_management_router, ChangeManagementState,
            };
            let change_state = ChangeManagementState { engine };
            app = app.nest("/api/v1/change-management", change_management_router(change_state));
            debug!("Change management API mounted at /api/v1/change-management");
        }
    }

    // Add risk assessment API if enabled
    {
        use mockforge_core::security::get_global_risk_assessment_engine;
        if let Some(engine) = get_global_risk_assessment_engine().await {
            use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
            let risk_state = RiskAssessmentState { engine };
            app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
            debug!("Risk assessment API mounted at /api/v1/security/risks");
        }
    }

    // Add token lifecycle API
    {
        use crate::auth::token_lifecycle::TokenLifecycleManager;
        use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
        let lifecycle_state = TokenLifecycleState {
            manager: lifecycle_manager,
        };
        app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
        debug!("Token lifecycle API mounted at /api/v1/auth");
    }

    // Add OAuth2 server endpoints
    {
        use crate::auth::oidc::load_oidc_state;
        use crate::auth::token_lifecycle::TokenLifecycleManager;
        use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
        // Load OIDC state from configuration (environment variables or config file)
        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
        let oauth2_state = OAuth2ServerState {
            oidc_state,
            lifecycle_manager,
            auth_codes: Arc::new(RwLock::new(HashMap::new())),
            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
        };
        app = app.merge(oauth2_server_router(oauth2_state));
        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
    }

    // Add consent screen endpoints
    {
        use crate::auth::oidc::load_oidc_state;
        use crate::auth::risk_engine::RiskEngine;
        use crate::auth::token_lifecycle::TokenLifecycleManager;
        use crate::handlers::consent::{consent_router, ConsentState};
        use crate::handlers::oauth2_server::OAuth2ServerState;
        // Load OIDC state from configuration (environment variables or config file)
        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
        let oauth2_state = OAuth2ServerState {
            oidc_state: oidc_state.clone(),
            lifecycle_manager: lifecycle_manager.clone(),
            auth_codes: Arc::new(RwLock::new(HashMap::new())),
            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
        };
        let risk_engine = Arc::new(RiskEngine::default());
        let consent_state = ConsentState {
            oauth2_state,
            risk_engine,
        };
        app = app.merge(consent_router(consent_state));
        debug!("Consent screen endpoints mounted at /consent");
    }

    // Add risk simulation API
    {
        use crate::auth::risk_engine::RiskEngine;
        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
        let risk_engine = Arc::new(RiskEngine::default());
        let risk_state = RiskSimulationState { risk_engine };
        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
        debug!("Risk simulation API mounted at /api/v1/auth/risk");
    }

    // Add management WebSocket endpoint
    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));

    // Add request logging middleware to capture all requests
    app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));

    // Add security middleware for security event tracking (after logging, before contract diff)
    app = app.layer(axum::middleware::from_fn(middleware::security_middleware));

    // Add contract diff middleware for automatic request capture
    // This captures requests for contract diff analysis (after logging)
    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));

    // Add rate limiting middleware (before logging to rate limit early)
    app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));

    // Add production headers middleware if configured
    if state.production_headers.is_some() {
        app =
            app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
    }

    // Add authentication middleware if OAuth is configured via deceptive deploy
    if let Some(auth_config) = deceptive_deploy_auth_config {
        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
        use std::collections::HashMap;
        use std::sync::Arc;
        use tokio::sync::RwLock;

        // Create OAuth2 client if configured
        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
            match create_oauth2_client(oauth2_config) {
                Ok(client) => Some(client),
                Err(e) => {
                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
                    None
                }
            }
        } else {
            None
        };

        // Create auth state
        let auth_state = AuthState {
            config: auth_config,
            spec: None, // OpenAPI spec not available in this context
            oauth2_client,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        // Apply auth middleware
        app = app.layer(from_fn_with_state(auth_state, auth_middleware));
        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
    }

    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
    app = apply_cors_middleware(app, final_cors_config);

    // Add workspace routing middleware if multi-tenant is enabled
    if let Some(mt_config) = multi_tenant_config {
        if mt_config.enabled {
            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
            use std::sync::Arc;

            info!(
                "Multi-tenant mode enabled with {} routing strategy",
                match mt_config.routing_strategy {
                    mockforge_core::RoutingStrategy::Path => "path-based",
                    mockforge_core::RoutingStrategy::Port => "port-based",
                    mockforge_core::RoutingStrategy::Both => "hybrid",
                }
            );

            // Create the multi-tenant workspace registry
            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());

            // Register the default workspace before wrapping in Arc
            let default_workspace =
                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
            if let Err(e) =
                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
            {
                warn!("Failed to register default workspace: {}", e);
            } else {
                info!("Registered default workspace: '{}'", mt_config.default_workspace);
            }

            // Auto-discover and register workspaces if configured
            if mt_config.auto_discover {
                if let Some(config_dir) = &mt_config.config_directory {
                    let config_path = Path::new(config_dir);
                    if config_path.exists() && config_path.is_dir() {
                        match fs::read_dir(config_path).await {
                            Ok(mut entries) => {
                                while let Ok(Some(entry)) = entries.next_entry().await {
                                    let path = entry.path();
                                    if path.extension() == Some(OsStr::new("yaml")) {
                                        match fs::read_to_string(&path).await {
                                            Ok(content) => {
                                                match serde_yaml::from_str::<
                                                    mockforge_core::Workspace,
                                                >(
                                                    &content
                                                ) {
                                                    Ok(workspace) => {
                                                        if let Err(e) = registry.register_workspace(
                                                            workspace.id.clone(),
                                                            workspace,
                                                        ) {
                                                            warn!("Failed to register auto-discovered workspace from {:?}: {}", path, e);
                                                        } else {
                                                            info!("Auto-registered workspace from {:?}", path);
                                                        }
                                                    }
                                                    Err(e) => {
                                                        warn!("Failed to parse workspace from {:?}: {}", path, e);
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                warn!(
                                                    "Failed to read workspace file {:?}: {}",
                                                    path, e
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                warn!("Failed to read config directory {:?}: {}", config_path, e);
                            }
                        }
                    } else {
                        warn!(
                            "Config directory {:?} does not exist or is not a directory",
                            config_path
                        );
                    }
                }
            }

            // Wrap registry in Arc for shared access
            let registry = Arc::new(registry);

            // Create workspace router and wrap the app with workspace middleware
            let _workspace_router = WorkspaceRouter::new(registry);

            // Note: The actual middleware integration would need to be implemented
            // in the WorkspaceRouter to work with Axum's middleware system
            info!("Workspace routing middleware initialized for HTTP server");
        }
    }

    let total_startup_duration = startup_start.elapsed();
    info!("HTTP router startup completed (total time: {:?})", total_startup_duration);

    app
}

/// Build the base HTTP router with authentication and latency support
pub async fn build_router_with_auth_and_latency(
    spec_path: Option<String>,
    _options: Option<()>,
    auth_config: Option<mockforge_core::config::AuthConfig>,
    latency_injector: Option<LatencyInjector>,
) -> Router {
    // Build auth router first, then layer latency on top
    let mut app = build_router_with_auth(spec_path.clone(), None, auth_config).await;

    // Apply latency injection middleware if configured
    if let Some(injector) = latency_injector {
        let injector = Arc::new(injector);
        app = app.layer(axum::middleware::from_fn(move |req, next: axum::middleware::Next| {
            let injector = injector.clone();
            async move {
                let _ = injector.inject_latency(&[]).await;
                next.run(req).await
            }
        }));
    }

    app
}

/// Build the base HTTP router with latency injection support
pub async fn build_router_with_latency(
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    latency_injector: Option<LatencyInjector>,
) -> Router {
    if let Some(spec) = &spec_path {
        match OpenApiSpec::from_file(spec).await {
            Ok(openapi) => {
                let registry = if let Some(opts) = options {
                    OpenApiRouteRegistry::new_with_options(openapi, opts)
                } else {
                    OpenApiRouteRegistry::new_with_env(openapi)
                };

                if let Some(injector) = latency_injector {
                    return registry.build_router_with_latency(injector);
                } else {
                    return registry.build_router();
                }
            }
            Err(e) => {
                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec, e);
            }
        }
    }

    build_router(None, None, None).await
}

/// Build the base HTTP router with authentication support
pub async fn build_router_with_auth(
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    auth_config: Option<mockforge_core::config::AuthConfig>,
) -> Router {
    use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
    use std::sync::Arc;

    // If richer faker is available, register provider once (idempotent)
    #[cfg(feature = "data-faker")]
    {
        register_core_faker_provider();
    }

    // Set up authentication state
    let spec = if let Some(spec_path) = &spec_path {
        match OpenApiSpec::from_file(&spec_path).await {
            Ok(spec) => Some(Arc::new(spec)),
            Err(e) => {
                warn!("Failed to load OpenAPI spec for auth: {}", e);
                None
            }
        }
    } else {
        None
    };

    // Create OAuth2 client if configured
    let oauth2_client = if let Some(auth_config) = &auth_config {
        if let Some(oauth2_config) = &auth_config.oauth2 {
            match create_oauth2_client(oauth2_config) {
                Ok(client) => Some(client),
                Err(e) => {
                    warn!("Failed to create OAuth2 client: {}", e);
                    None
                }
            }
        } else {
            None
        }
    } else {
        None
    };

    let auth_state = AuthState {
        config: auth_config.unwrap_or_default(),
        spec,
        oauth2_client,
        introspection_cache: Arc::new(RwLock::new(HashMap::new())),
    };

    // Set up the basic router with auth state
    let mut app = Router::new().with_state(auth_state.clone());

    // If an OpenAPI spec is provided, integrate it
    if let Some(spec_path) = spec_path {
        match OpenApiSpec::from_file(&spec_path).await {
            Ok(openapi) => {
                info!("Loaded OpenAPI spec from {}", spec_path);
                let registry = if let Some(opts) = options {
                    OpenApiRouteRegistry::new_with_options(openapi, opts)
                } else {
                    OpenApiRouteRegistry::new_with_env(openapi)
                };

                app = registry.build_router();
            }
            Err(e) => {
                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
            }
        }
    }

    // Add basic health check endpoint
    app = app.route(
        "/health",
        axum::routing::get(|| async {
            use mockforge_core::server_utils::health::HealthStatus;
            {
                // HealthStatus should always serialize, but handle errors gracefully
                match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
                    Ok(value) => Json(value),
                    Err(e) => {
                        // Log error but return a simple healthy response
                        tracing::error!("Failed to serialize health status: {}", e);
                        Json(serde_json::json!({
                            "status": "healthy",
                            "service": "mockforge-http",
                            "uptime_seconds": 0
                        }))
                    }
                }
            }
        }),
    )
    // Add SSE endpoints
    .merge(sse::sse_router())
    // Add file serving endpoints for generated mock files
    .merge(file_server::file_serving_router())
    // Add authentication middleware (before logging)
    .layer(from_fn_with_state(auth_state.clone(), auth_middleware))
    // Add request logging middleware
    .layer(axum::middleware::from_fn(request_logging::log_http_requests));

    app
}

/// Serve a provided router on the given port.
pub async fn serve_router(
    port: u16,
    app: Router,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    serve_router_with_tls(port, app, None).await
}

/// Serve a provided router on the given port with optional TLS support.
pub async fn serve_router_with_tls(
    port: u16,
    app: Router,
    tls_config: Option<mockforge_core::config::HttpTlsConfig>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use std::net::SocketAddr;

    let addr = mockforge_core::wildcard_socket_addr(port);

    if let Some(ref tls) = tls_config {
        if tls.enabled {
            info!("HTTPS listening on {}", addr);
            return serve_with_tls(addr, app, tls).await;
        }
    }

    info!("HTTP listening on {}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
        format!(
            "Failed to bind HTTP server to port {}: {}\n\
             Hint: The port may already be in use. Try using a different port with --http-port or check if another process is using this port with: lsof -i :{} or netstat -tulpn | grep {}",
            port, e, port, port
        )
    })?;

    // Wrap the Router with OData URI rewrite.
    // Router::layer() only applies to matched routes, so we must wrap at the service level
    // to rewrite URIs BEFORE route matching occurs.
    let odata_app = tower::ServiceBuilder::new()
        .layer(mockforge_core::odata_rewrite::ODataRewriteLayer)
        .service(app);
    let make_svc = axum::ServiceExt::<axum::http::Request<axum::body::Body>>::into_make_service_with_connect_info::<SocketAddr>(odata_app);
    axum::serve(listener, make_svc).await?;
    Ok(())
}

/// Serve router with TLS/HTTPS support using axum-server
///
/// This function implements native TLS serving using axum-server and tokio-rustls.
/// It supports standard TLS and mutual TLS (mTLS) based on the configuration.
async fn serve_with_tls(
    addr: std::net::SocketAddr,
    app: Router,
    tls_config: &mockforge_core::config::HttpTlsConfig,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use axum_server::tls_rustls::RustlsConfig;
    use std::net::SocketAddr;

    // Initialize the rustls crypto provider (must be called before TLS operations)
    tls::init_crypto_provider();

    info!("Loading TLS configuration for HTTPS server");

    // Load TLS server configuration (supports mTLS)
    let server_config = tls::load_tls_server_config(tls_config)?;

    // Create RustlsConfig from the ServerConfig
    // Note: axum-server's RustlsConfig can be created from a ServerConfig
    let rustls_config = RustlsConfig::from_config(server_config);

    info!("Starting HTTPS server on {}", addr);

    // Wrap the Router with OData URI rewrite (same as the non-TLS path).
    // Router::layer() only applies to matched routes, so we must wrap at the service level
    // to rewrite URIs BEFORE route matching occurs.
    let odata_app = tower::ServiceBuilder::new()
        .layer(mockforge_core::odata_rewrite::ODataRewriteLayer)
        .service(app);
    let make_svc = axum::ServiceExt::<axum::http::Request<axum::body::Body>>::into_make_service_with_connect_info::<SocketAddr>(odata_app);

    // Serve with TLS using axum-server
    axum_server::bind_rustls(addr, rustls_config)
        .serve(make_svc)
        .await
        .map_err(|e| format!("HTTPS server error: {}", e).into())
}

/// Backwards-compatible start that builds + serves the base router.
pub async fn start(
    port: u16,
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    start_with_latency(port, spec_path, options, None).await
}

/// Start HTTP server with authentication and latency support
pub async fn start_with_auth_and_latency(
    port: u16,
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    auth_config: Option<mockforge_core::config::AuthConfig>,
    latency_profile: Option<LatencyProfile>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
        .await
}

/// Start HTTP server with authentication and injectors support
pub async fn start_with_auth_and_injectors(
    port: u16,
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    auth_config: Option<mockforge_core::config::AuthConfig>,
    _latency_profile: Option<LatencyProfile>,
    _failure_injector: Option<FailureInjector>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // For now, ignore latency and failure injectors and just use auth
    let app = build_router_with_auth(spec_path, options, auth_config).await;
    serve_router(port, app).await
}

/// Start HTTP server with latency injection support
pub async fn start_with_latency(
    port: u16,
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    latency_profile: Option<LatencyProfile>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let latency_injector =
        latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));

    let app = build_router_with_latency(spec_path, options, latency_injector).await;
    serve_router(port, app).await
}

/// Build the base HTTP router with chaining support
pub async fn build_router_with_chains(
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
) -> Router {
    build_router_with_chains_and_multi_tenant(
        spec_path,
        options,
        circling_config,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        false,
        None, // health_manager
        None, // mockai
        None, // deceptive_deploy_config
        None, // proxy_config
    )
    .await
}

// Template expansion is now handled by mockforge_core::template_expansion
// which is explicitly isolated from the templating module to avoid Send issues

/// Helper function to apply route chaos injection (fault injection and latency)
/// This is extracted to avoid capturing RouteChaosInjector in the closure, which causes Send issues
/// Uses mockforge-route-chaos crate which is isolated from mockforge-core to avoid Send issues
/// Uses the RouteChaosInjectorTrait from mockforge-core to avoid circular dependency
async fn apply_route_chaos(
    injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
    method: &http::Method,
    uri: &http::Uri,
) -> Option<axum::response::Response> {
    use axum::http::StatusCode;
    use axum::response::IntoResponse;

    if let Some(injector) = injector {
        // Check for fault injection first
        if let Some(fault_response) = injector.get_fault_response(method, uri) {
            // Return fault response
            let mut response = Json(serde_json::json!({
                "error": fault_response.error_message,
                "fault_type": fault_response.fault_type,
            }))
            .into_response();
            *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            return Some(response);
        }

        // Inject latency if configured (this is async and may delay the request)
        if let Err(e) = injector.inject_latency(method, uri).await {
            tracing::warn!("Failed to inject latency: {}", e);
        }
    }

    None // No fault response, processing should continue
}

/// Build the base HTTP router with chaining and multi-tenant support
#[allow(clippy::too_many_arguments)]
pub async fn build_router_with_chains_and_multi_tenant(
    spec_path: Option<String>,
    options: Option<ValidationOptions>,
    _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
    multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
    route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
    _ai_generator: Option<Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>>,
    smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
    mqtt_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
    traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
    traffic_shaping_enabled: bool,
    health_manager: Option<Arc<HealthManager>>,
    _mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
    deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
    proxy_config: Option<mockforge_core::proxy::config::ProxyConfig>,
) -> Router {
    use crate::latency_profiles::LatencyProfiles;
    use crate::op_middleware::Shared;
    use mockforge_core::Overrides;

    // Extract template expansion setting before options is moved (used in OpenAPI routes and custom routes)
    let template_expand =
        options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
            std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false)
        });

    let _shared = Shared {
        profiles: LatencyProfiles::default(),
        overrides: Overrides::default(),
        failure_injector: None,
        traffic_shaper,
        overrides_enabled: false,
        traffic_shaping_enabled,
    };

    // Start with basic router
    let mut app = Router::new();
    let mut include_default_health = true;
    let mut captured_routes: Vec<RouteInfo> = Vec::new();

    // If an OpenAPI spec is provided, integrate it
    if let Some(ref spec) = spec_path {
        match OpenApiSpec::from_file(&spec).await {
            Ok(openapi) => {
                info!("Loaded OpenAPI spec from {}", spec);

                // Try to load persona from config if available
                let persona = load_persona_from_config().await;

                let mut registry = if let Some(opts) = options {
                    tracing::debug!("Using custom validation options");
                    if let Some(ref persona) = persona {
                        tracing::info!("Using persona '{}' for route generation", persona.name);
                    }
                    OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
                } else {
                    tracing::debug!("Using environment-based options");
                    if let Some(ref persona) = persona {
                        tracing::info!("Using persona '{}' for route generation", persona.name);
                    }
                    OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
                };

                // Load custom fixtures if enabled
                let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
                    .unwrap_or_else(|_| "/app/fixtures".to_string());
                let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
                    .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                    .unwrap_or(true); // Enabled by default

                if custom_fixtures_enabled {
                    use mockforge_core::CustomFixtureLoader;
                    use std::path::PathBuf;
                    use std::sync::Arc;

                    let fixtures_path = PathBuf::from(&fixtures_dir);
                    let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);

                    if let Err(e) = custom_loader.load_fixtures().await {
                        tracing::warn!("Failed to load custom fixtures: {}", e);
                    } else {
                        tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
                        registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
                    }
                }

                if registry
                    .routes()
                    .iter()
                    .any(|route| route.method == "GET" && route.path == "/health")
                {
                    include_default_health = false;
                }
                // Capture route info for the /__mockforge/routes endpoint
                captured_routes = registry
                    .routes()
                    .iter()
                    .map(|r| RouteInfo {
                        method: r.method.clone(),
                        path: r.path.clone(),
                        operation_id: r.operation.operation_id.clone(),
                        summary: r.operation.summary.clone(),
                        description: r.operation.description.clone(),
                        parameters: r.parameters.clone(),
                    })
                    .collect();

                // Store routes in the global route store so the admin server
                // can serve them without proxying back to the HTTP server.
                {
                    let global_routes: Vec<mockforge_core::request_logger::GlobalRouteInfo> =
                        captured_routes
                            .iter()
                            .map(|r| mockforge_core::request_logger::GlobalRouteInfo {
                                method: r.method.clone(),
                                path: r.path.clone(),
                                operation_id: r.operation_id.clone(),
                                summary: r.summary.clone(),
                                description: r.description.clone(),
                                parameters: r.parameters.clone(),
                            })
                            .collect();
                    mockforge_core::request_logger::set_global_routes(global_routes);
                    tracing::info!("Stored {} routes in global route store", captured_routes.len());
                }

                // Use MockAI if available, otherwise use standard router
                let spec_router = if let Some(ref mockai_instance) = _mockai {
                    tracing::debug!("Building router with MockAI support");
                    registry.build_router_with_mockai(Some(mockai_instance.clone()))
                } else {
                    registry.build_router()
                };
                app = app.merge(spec_router);
            }
            Err(e) => {
                warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
            }
        }
    }

    // Register custom routes from config with advanced routing features
    // Create RouteChaosInjector for advanced fault injection and latency
    // Store as trait object to avoid circular dependency (RouteChaosInjectorTrait is in mockforge-core)
    let route_chaos_injector: Option<
        std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
    > = if let Some(ref route_configs) = route_configs {
        if !route_configs.is_empty() {
            // Convert to the type expected by RouteChaosInjector
            // Note: Both use the same mockforge-core, but we need to ensure type compatibility
            let route_configs_converted: Vec<mockforge_core::config::RouteConfig> =
                route_configs.to_vec();
            match mockforge_route_chaos::RouteChaosInjector::new(route_configs_converted) {
                Ok(injector) => {
                    info!(
                        "Initialized advanced routing features for {} route(s)",
                        route_configs.len()
                    );
                    // RouteChaosInjector implements RouteChaosInjectorTrait, so we can cast it
                    // The trait is implemented in mockforge-route-chaos/src/lib.rs
                    Some(std::sync::Arc::new(injector)
                        as std::sync::Arc<
                            dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
                        >)
                }
                Err(e) => {
                    warn!(
                        "Failed to initialize advanced routing features: {}. Using basic routing.",
                        e
                    );
                    None
                }
            }
        } else {
            None
        }
    } else {
        None
    };

    if let Some(route_configs) = route_configs {
        use axum::http::StatusCode;
        use axum::response::IntoResponse;

        if !route_configs.is_empty() {
            info!("Registering {} custom route(s) from config", route_configs.len());
        }

        let injector = route_chaos_injector.clone();
        for route_config in route_configs {
            let status = route_config.response.status;
            let body = route_config.response.body.clone();
            let headers = route_config.response.headers.clone();
            let path = route_config.path.clone();
            let method = route_config.method.clone();

            // Create handler that returns the configured response with template expansion
            // Supports both basic templates ({{uuid}}, {{now}}) and request-aware templates
            // ({{request.query.name}}, {{request.path.id}}, {{request.headers.name}})
            // Register route using `any()` since we need full Request access for template expansion
            let expected_method = method.to_uppercase();
            // Clone Arc for the closure - Arc is Send-safe
            // Note: RouteChaosInjector is marked as Send+Sync via unsafe impl, but the compiler
            // is conservative because rng() is available in the rand crate, even though we use thread_rng()
            let injector_clone = injector.clone();
            app = app.route(
                &path,
                #[allow(clippy::non_send_fields_in_send_ty)]
                axum::routing::any(move |req: http::Request<axum::body::Body>| {
                    let body = body.clone();
                    let headers = headers.clone();
                    let expand = template_expand;
                    let expected = expected_method.clone();
                    let status_code = status;
                    // Clone Arc again for the async block
                    let injector_for_chaos = injector_clone.clone();

                    async move {
                        // Check if request method matches expected method
                        if req.method().as_str() != expected.as_str() {
                            // Return 405 Method Not Allowed for wrong method
                            return axum::response::Response::builder()
                                .status(StatusCode::METHOD_NOT_ALLOWED)
                                .header("Allow", &expected)
                                .body(axum::body::Body::empty())
                                .unwrap()
                                .into_response();
                        }

                        // Apply advanced routing features (fault injection and latency) if available
                        // Use helper function to avoid capturing RouteChaosInjector in closure
                        // Pass the Arc as a reference to the helper function
                        if let Some(fault_response) = apply_route_chaos(
                            injector_for_chaos.as_deref(),
                            req.method(),
                            req.uri(),
                        )
                        .await
                        {
                            return fault_response;
                        }

                        // Create JSON response from body, or empty object if None
                        let mut body_value = body.unwrap_or(serde_json::json!({}));

                        // Apply template expansion if enabled
                        // Use mockforge-template-expansion crate which is completely isolated
                        // from mockforge-core to avoid Send issues (no rng() in dependency chain)
                        if expand {
                            use mockforge_template_expansion::RequestContext;
                            use serde_json::Value;
                            use std::collections::HashMap;

                            // Extract request data for template expansion
                            let method = req.method().to_string();
                            let path = req.uri().path().to_string();

                            // Extract query parameters
                            let query_params: HashMap<String, Value> = req
                                .uri()
                                .query()
                                .map(|q| {
                                    url::form_urlencoded::parse(q.as_bytes())
                                        .into_owned()
                                        .map(|(k, v)| (k, Value::String(v)))
                                        .collect()
                                })
                                .unwrap_or_default();

                            // Extract headers
                            let headers: HashMap<String, Value> = req
                                .headers()
                                .iter()
                                .map(|(k, v)| {
                                    (
                                        k.to_string(),
                                        Value::String(v.to_str().unwrap_or_default().to_string()),
                                    )
                                })
                                .collect();

                            // Create RequestContext for expand_prompt_template
                            // Using RequestContext from mockforge-template-expansion (not mockforge-core)
                            // to avoid bringing rng() into scope
                            let context = RequestContext {
                                method,
                                path,
                                query_params,
                                headers,
                                body: None, // Body extraction would require reading the request stream
                                path_params: HashMap::new(),
                                multipart_fields: HashMap::new(),
                                multipart_files: HashMap::new(),
                            };

                            // Perform template expansion in spawn_blocking to ensure Send safety
                            // The template expansion crate is completely isolated from mockforge-core
                            // and doesn't have rng() in its dependency chain
                            let body_value_clone = body_value.clone();
                            let context_clone = context.clone();
                            body_value = match tokio::task::spawn_blocking(move || {
                                mockforge_template_expansion::expand_templates_in_json(
                                    body_value_clone,
                                    &context_clone,
                                )
                            })
                            .await
                            {
                                Ok(result) => result,
                                Err(_) => body_value, // Fallback to original on error
                            };
                        }

                        let mut response = Json(body_value).into_response();

                        // Set status code
                        *response.status_mut() =
                            StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);

                        // Add custom headers
                        for (key, value) in headers {
                            if let Ok(header_name) = http::HeaderName::from_bytes(key.as_bytes()) {
                                if let Ok(header_value) = http::HeaderValue::from_str(&value) {
                                    response.headers_mut().insert(header_name, header_value);
                                }
                            }
                        }

                        response
                    }
                }),
            );

            debug!("Registered route: {} {}", method, path);
        }
    }

    // Add health check endpoints
    if let Some(health) = health_manager {
        // Use comprehensive health check router with all probe endpoints
        app = app.merge(health::health_router(health));
        info!(
            "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
        );
    } else if include_default_health {
        // Fallback to basic health endpoint for backwards compatibility
        app = app.route(
            "/health",
            axum::routing::get(|| async {
                use mockforge_core::server_utils::health::HealthStatus;
                {
                    // HealthStatus should always serialize, but handle errors gracefully
                    match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
                        Ok(value) => Json(value),
                        Err(e) => {
                            // Log error but return a simple healthy response
                            tracing::error!("Failed to serialize health status: {}", e);
                            Json(serde_json::json!({
                                "status": "healthy",
                                "service": "mockforge-http",
                                "uptime_seconds": 0
                            }))
                        }
                    }
                }
            }),
        );
    }

    app = app.merge(sse::sse_router());
    // Add file serving endpoints for generated mock files
    app = app.merge(file_server::file_serving_router());

    // Add management API endpoints
    // Load spec for ManagementState so /__mockforge/api/spec can serve it
    let mgmt_spec = if let Some(ref sp) = spec_path {
        match OpenApiSpec::from_file(sp).await {
            Ok(s) => Some(Arc::new(s)),
            Err(e) => {
                debug!("Failed to load OpenAPI spec for management API: {}", e);
                None
            }
        }
    } else {
        None
    };
    let spec_path_clone = spec_path.clone();
    let mgmt_port = std::env::var("PORT")
        .or_else(|_| std::env::var("MOCKFORGE_HTTP_PORT"))
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(3000);
    let management_state = ManagementState::new(mgmt_spec, spec_path_clone, mgmt_port);

    // Create WebSocket state and connect it to management state
    use std::sync::Arc;
    let ws_state = WsManagementState::new();
    let ws_broadcast = Arc::new(ws_state.tx.clone());
    let management_state = management_state.with_ws_broadcast(ws_broadcast);

    // Add proxy config to management state if available
    let management_state = if let Some(proxy_cfg) = proxy_config {
        use tokio::sync::RwLock;
        let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
        management_state.with_proxy_config(proxy_config_arc)
    } else {
        management_state
    };

    #[cfg(feature = "smtp")]
    let management_state = {
        if let Some(smtp_reg) = smtp_registry {
            match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
                Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
                Err(e) => {
                    error!(
                        "Invalid SMTP registry type passed to HTTP management state: {:?}",
                        e.type_id()
                    );
                    management_state
                }
            }
        } else {
            management_state
        }
    };
    #[cfg(not(feature = "smtp"))]
    let management_state = {
        let _ = smtp_registry;
        management_state
    };
    #[cfg(feature = "mqtt")]
    let management_state = {
        if let Some(broker) = mqtt_broker {
            match broker.downcast::<mockforge_mqtt::MqttBroker>() {
                Ok(broker) => management_state.with_mqtt_broker(broker),
                Err(e) => {
                    error!(
                        "Invalid MQTT broker passed to HTTP management state: {:?}",
                        e.type_id()
                    );
                    management_state
                }
            }
        } else {
            management_state
        }
    };
    #[cfg(not(feature = "mqtt"))]
    let management_state = {
        let _ = mqtt_broker;
        management_state
    };
    app = app.nest("/__mockforge/api", management_router(management_state));

    // Add verification API endpoint
    app = app.merge(verification_router());

    // Add OIDC well-known endpoints
    use crate::auth::oidc::oidc_router;
    app = app.merge(oidc_router());

    // Add access review API if enabled
    {
        use mockforge_core::security::get_global_access_review_service;
        if let Some(service) = get_global_access_review_service().await {
            use crate::handlers::access_review::{access_review_router, AccessReviewState};
            let review_state = AccessReviewState { service };
            app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
            debug!("Access review API mounted at /api/v1/security/access-reviews");
        }
    }

    // Add privileged access API if enabled
    {
        use mockforge_core::security::get_global_privileged_access_manager;
        if let Some(manager) = get_global_privileged_access_manager().await {
            use crate::handlers::privileged_access::{
                privileged_access_router, PrivilegedAccessState,
            };
            let privileged_state = PrivilegedAccessState { manager };
            app = app.nest(
                "/api/v1/security/privileged-access",
                privileged_access_router(privileged_state),
            );
            debug!("Privileged access API mounted at /api/v1/security/privileged-access");
        }
    }

    // Add change management API if enabled
    {
        use mockforge_core::security::get_global_change_management_engine;
        if let Some(engine) = get_global_change_management_engine().await {
            use crate::handlers::change_management::{
                change_management_router, ChangeManagementState,
            };
            let change_state = ChangeManagementState { engine };
            app = app.nest("/api/v1/change-management", change_management_router(change_state));
            debug!("Change management API mounted at /api/v1/change-management");
        }
    }

    // Add risk assessment API if enabled
    {
        use mockforge_core::security::get_global_risk_assessment_engine;
        if let Some(engine) = get_global_risk_assessment_engine().await {
            use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
            let risk_state = RiskAssessmentState { engine };
            app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
            debug!("Risk assessment API mounted at /api/v1/security/risks");
        }
    }

    // Add token lifecycle API
    {
        use crate::auth::token_lifecycle::TokenLifecycleManager;
        use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
        let lifecycle_state = TokenLifecycleState {
            manager: lifecycle_manager,
        };
        app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
        debug!("Token lifecycle API mounted at /api/v1/auth");
    }

    // Add OAuth2 server endpoints
    {
        use crate::auth::oidc::load_oidc_state;
        use crate::auth::token_lifecycle::TokenLifecycleManager;
        use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
        // Load OIDC state from configuration (environment variables or config file)
        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
        let oauth2_state = OAuth2ServerState {
            oidc_state,
            lifecycle_manager,
            auth_codes: Arc::new(RwLock::new(HashMap::new())),
            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
        };
        app = app.merge(oauth2_server_router(oauth2_state));
        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
    }

    // Add consent screen endpoints
    {
        use crate::auth::oidc::load_oidc_state;
        use crate::auth::risk_engine::RiskEngine;
        use crate::auth::token_lifecycle::TokenLifecycleManager;
        use crate::handlers::consent::{consent_router, ConsentState};
        use crate::handlers::oauth2_server::OAuth2ServerState;
        // Load OIDC state from configuration (environment variables or config file)
        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
        let oauth2_state = OAuth2ServerState {
            oidc_state: oidc_state.clone(),
            lifecycle_manager: lifecycle_manager.clone(),
            auth_codes: Arc::new(RwLock::new(HashMap::new())),
            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
        };
        let risk_engine = Arc::new(RiskEngine::default());
        let consent_state = ConsentState {
            oauth2_state,
            risk_engine,
        };
        app = app.merge(consent_router(consent_state));
        debug!("Consent screen endpoints mounted at /consent");
    }

    // Add risk simulation API
    {
        use crate::auth::risk_engine::RiskEngine;
        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
        let risk_engine = Arc::new(RiskEngine::default());
        let risk_state = RiskSimulationState { risk_engine };
        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
        debug!("Risk simulation API mounted at /api/v1/auth/risk");
    }

    // Initialize database connection (optional)
    let database = {
        use crate::database::Database;
        let database_url = std::env::var("DATABASE_URL").ok();
        match Database::connect_optional(database_url.as_deref()).await {
            Ok(db) => {
                if db.is_connected() {
                    // Run migrations if database is connected
                    if let Err(e) = db.migrate_if_connected().await {
                        warn!("Failed to run database migrations: {}", e);
                    } else {
                        info!("Database connected and migrations applied");
                    }
                }
                Some(db)
            }
            Err(e) => {
                warn!("Failed to connect to database: {}. Continuing without database support.", e);
                None
            }
        }
    };

    // Add drift budget and incident management endpoints
    // Initialize shared components for drift tracking and protocol contracts
    let (drift_engine, incident_manager, drift_config) = {
        use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
        use mockforge_core::incidents::{IncidentManager, IncidentStore};
        use std::sync::Arc;

        // Initialize drift budget engine with default config
        let drift_config = DriftBudgetConfig::default();
        let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));

        // Initialize incident store and manager
        let incident_store = Arc::new(IncidentStore::default());
        let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));

        (drift_engine, incident_manager, drift_config)
    };

    {
        use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
        use crate::middleware::drift_tracking::DriftTrackingState;
        use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
        use mockforge_core::consumer_contracts::{ConsumerBreakingChangeDetector, UsageRecorder};
        use std::sync::Arc;

        // Initialize usage recorder and consumer detector
        let usage_recorder = Arc::new(UsageRecorder::default());
        let consumer_detector =
            Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));

        // Initialize contract diff analyzer if enabled
        let diff_analyzer = if drift_config.enabled {
            match ContractDiffAnalyzer::new(
                mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
            ) {
                Ok(analyzer) => Some(Arc::new(analyzer)),
                Err(e) => {
                    warn!("Failed to create contract diff analyzer: {}", e);
                    None
                }
            }
        } else {
            None
        };

        // Get OpenAPI spec if available
        // Note: Load from spec_path if available, or leave as None for manual configuration.
        let spec = if let Some(ref spec_path) = spec_path {
            match OpenApiSpec::from_file(spec_path).await {
                Ok(s) => Some(Arc::new(s)),
                Err(e) => {
                    debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
                    None
                }
            }
        } else {
            None
        };

        // Create drift tracking state
        let drift_tracking_state = DriftTrackingState {
            diff_analyzer,
            spec,
            drift_engine: drift_engine.clone(),
            incident_manager: incident_manager.clone(),
            usage_recorder,
            consumer_detector,
            enabled: drift_config.enabled,
        };

        // Add response body buffering middleware (before drift tracking)
        app = app.layer(axum::middleware::from_fn(middleware::buffer_response_middleware));

        // Add drift tracking middleware (after response buffering)
        // Use a wrapper that inserts state into extensions before calling the middleware
        let drift_tracking_state_clone = drift_tracking_state.clone();
        app = app.layer(axum::middleware::from_fn(
            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
                let state = drift_tracking_state_clone.clone();
                async move {
                    // Insert state into extensions if not already present
                    if req.extensions().get::<DriftTrackingState>().is_none() {
                        req.extensions_mut().insert(state);
                    }
                    // Call the middleware function
                    middleware::drift_tracking::drift_tracking_middleware_with_extensions(req, next)
                        .await
                }
            },
        ));

        let drift_state = DriftBudgetState {
            engine: drift_engine.clone(),
            incident_manager: incident_manager.clone(),
            gitops_handler: None, // Can be initialized later if GitOps is configured
        };

        app = app.merge(drift_budget_router(drift_state));
        debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
    }

    // Add pipeline management endpoints (MockOps)
    #[cfg(feature = "pipelines")]
    {
        use crate::handlers::pipelines::{pipeline_router, PipelineState};

        let pipeline_state = PipelineState::new();
        app = app.merge(pipeline_router(pipeline_state));
        debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
    }

    // Add governance endpoints (forecasting, semantic drift, threat modeling, contract health)
    {
        use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
        use crate::handlers::forecasting::{forecasting_router, ForecastingState};
        use crate::handlers::semantic_drift::{semantic_drift_router, SemanticDriftState};
        use crate::handlers::threat_modeling::{threat_modeling_router, ThreatModelingState};
        use mockforge_core::contract_drift::forecasting::{Forecaster, ForecastingConfig};
        use mockforge_core::contract_drift::threat_modeling::{
            ThreatAnalyzer, ThreatModelingConfig,
        };
        use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
        use std::sync::Arc;

        // Initialize forecasting
        let forecasting_config = ForecastingConfig::default();
        let forecaster = Arc::new(Forecaster::new(forecasting_config));
        let forecasting_state = ForecastingState {
            forecaster,
            database: database.clone(),
        };

        // Initialize semantic drift manager
        let semantic_manager = Arc::new(SemanticIncidentManager::new());
        let semantic_state = SemanticDriftState {
            manager: semantic_manager,
            database: database.clone(),
        };

        // Initialize threat analyzer
        let threat_config = ThreatModelingConfig::default();
        let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
            Ok(analyzer) => Arc::new(analyzer),
            Err(e) => {
                warn!("Failed to create threat analyzer: {}. Using default.", e);
                Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
                    |_| {
                        // Fallback to a minimal config if default also fails
                        ThreatAnalyzer::new(ThreatModelingConfig {
                            enabled: false,
                            ..Default::default()
                        })
                        .expect("Failed to create fallback threat analyzer")
                    },
                ))
            }
        };
        // Load webhook configs from ServerConfig
        let mut webhook_configs = Vec::new();
        let config_paths = [
            "config.yaml",
            "mockforge.yaml",
            "tools/mockforge/config.yaml",
            "../tools/mockforge/config.yaml",
        ];

        for path in &config_paths {
            if let Ok(config) = mockforge_core::config::load_config(path).await {
                if !config.incidents.webhooks.is_empty() {
                    webhook_configs = config.incidents.webhooks.clone();
                    info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
                    break;
                }
            }
        }

        if webhook_configs.is_empty() {
            debug!("No webhook configs found in config files, using empty list");
        }

        let threat_state = ThreatModelingState {
            analyzer: threat_analyzer,
            webhook_configs,
            database: database.clone(),
        };

        // Initialize contract health state
        let contract_health_state = ContractHealthState {
            incident_manager: incident_manager.clone(),
            semantic_manager: Arc::new(SemanticIncidentManager::new()),
            database: database.clone(),
        };

        // Register routers
        app = app.merge(forecasting_router(forecasting_state));
        debug!("Forecasting endpoints mounted at /api/v1/forecasts");

        app = app.merge(semantic_drift_router(semantic_state));
        debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");

        app = app.merge(threat_modeling_router(threat_state));
        debug!("Threat modeling endpoints mounted at /api/v1/threats");

        app = app.merge(contract_health_router(contract_health_state));
        debug!("Contract health endpoints mounted at /api/v1/contract-health");
    }

    // Add protocol contracts endpoints with fitness registry initialization
    {
        use crate::handlers::protocol_contracts::{
            protocol_contracts_router, ProtocolContractState,
        };
        use mockforge_core::contract_drift::{
            ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
        };
        use std::sync::Arc;
        use tokio::sync::RwLock;

        // Initialize protocol contract registry
        let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));

        // Initialize fitness function registry and load from config
        let mut fitness_registry = FitnessFunctionRegistry::new();

        // Try to load config and populate fitness rules
        let config_paths = [
            "config.yaml",
            "mockforge.yaml",
            "tools/mockforge/config.yaml",
            "../tools/mockforge/config.yaml",
        ];

        let mut config_loaded = false;
        for path in &config_paths {
            if let Ok(config) = mockforge_core::config::load_config(path).await {
                if !config.contracts.fitness_rules.is_empty() {
                    if let Err(e) =
                        fitness_registry.load_from_config(&config.contracts.fitness_rules)
                    {
                        warn!("Failed to load fitness rules from config {}: {}", path, e);
                    } else {
                        info!(
                            "Loaded {} fitness rules from config: {}",
                            config.contracts.fitness_rules.len(),
                            path
                        );
                        config_loaded = true;
                        break;
                    }
                }
            }
        }

        if !config_loaded {
            debug!("No fitness rules found in config files, using empty registry");
        }

        let fitness_registry = Arc::new(RwLock::new(fitness_registry));

        // Reuse drift engine and incident manager from drift budget section

        // Initialize consumer impact analyzer
        let consumer_mapping_registry =
            mockforge_core::contract_drift::ConsumerMappingRegistry::new();
        let consumer_analyzer =
            Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));

        let protocol_state = ProtocolContractState {
            registry: contract_registry,
            drift_engine: Some(drift_engine.clone()),
            incident_manager: Some(incident_manager.clone()),
            fitness_registry: Some(fitness_registry),
            consumer_analyzer: Some(consumer_analyzer),
        };

        app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
        debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
    }

    // Add behavioral cloning middleware (optional - applies learned behavior to requests)
    #[cfg(feature = "behavioral-cloning")]
    {
        use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
        use std::path::PathBuf;

        // Determine database path (defaults to ./recordings.db)
        let db_path = std::env::var("RECORDER_DATABASE_PATH")
            .ok()
            .map(PathBuf::from)
            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));

        let bc_middleware_state = if let Some(path) = db_path {
            BehavioralCloningMiddlewareState::with_database_path(path)
        } else {
            BehavioralCloningMiddlewareState::new()
        };

        // Only enable if BEHAVIORAL_CLONING_ENABLED is set to true
        let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
            .ok()
            .and_then(|v| v.parse::<bool>().ok())
            .unwrap_or(false);

        if enabled {
            let bc_state_clone = bc_middleware_state.clone();
            app = app.layer(axum::middleware::from_fn(
                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
                    let state = bc_state_clone.clone();
                    async move {
                        // Insert state into extensions if not already present
                        if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
                            req.extensions_mut().insert(state);
                        }
                        // Call the middleware function
                        crate::middleware::behavioral_cloning::behavioral_cloning_middleware(
                            req, next,
                        )
                        .await
                    }
                },
            ));
            debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
        }
    }

    // Add consumer contracts endpoints
    {
        use crate::handlers::consumer_contracts::{
            consumer_contracts_router, ConsumerContractsState,
        };
        use mockforge_core::consumer_contracts::{
            ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
        };
        use std::sync::Arc;

        // Initialize consumer registry
        let registry = Arc::new(ConsumerRegistry::default());

        // Initialize usage recorder
        let usage_recorder = Arc::new(UsageRecorder::default());

        // Initialize breaking change detector
        let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));

        let consumer_state = ConsumerContractsState {
            registry,
            usage_recorder,
            detector,
            violations: Arc::new(RwLock::new(HashMap::new())),
        };

        app = app.merge(consumer_contracts_router(consumer_state));
        debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
    }

    // Add behavioral cloning endpoints
    #[cfg(feature = "behavioral-cloning")]
    {
        use crate::handlers::behavioral_cloning::{
            behavioral_cloning_router, BehavioralCloningState,
        };
        use std::path::PathBuf;

        // Determine database path (defaults to ./recordings.db)
        let db_path = std::env::var("RECORDER_DATABASE_PATH")
            .ok()
            .map(PathBuf::from)
            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));

        let bc_state = if let Some(path) = db_path {
            BehavioralCloningState::with_database_path(path)
        } else {
            BehavioralCloningState::new()
        };

        app = app.merge(behavioral_cloning_router(bc_state));
        debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
    }

    // Add consistency engine and cross-protocol state management
    {
        use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
        use crate::handlers::consistency::{consistency_router, ConsistencyState};
        use mockforge_core::consistency::ConsistencyEngine;
        use std::sync::Arc;

        // Initialize consistency engine
        let consistency_engine = Arc::new(ConsistencyEngine::new());

        // Create and register HTTP adapter
        let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
        consistency_engine.register_adapter(http_adapter.clone()).await;

        // Create consistency state for handlers
        let consistency_state = ConsistencyState {
            engine: consistency_engine.clone(),
        };

        // Create X-Ray state first (needed for middleware)
        use crate::handlers::xray::XRayState;
        let xray_state = Arc::new(XRayState {
            engine: consistency_engine.clone(),
            request_contexts: std::sync::Arc::new(RwLock::new(HashMap::new())),
        });

        // Create consistency middleware state
        let consistency_middleware_state = ConsistencyMiddlewareState {
            engine: consistency_engine.clone(),
            adapter: http_adapter,
            xray_state: Some(xray_state.clone()),
        };

        // Add consistency middleware (before other middleware to inject state early)
        let consistency_middleware_state_clone = consistency_middleware_state.clone();
        app = app.layer(axum::middleware::from_fn(
            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
                let state = consistency_middleware_state_clone.clone();
                async move {
                    // Insert state into extensions if not already present
                    if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
                        req.extensions_mut().insert(state);
                    }
                    // Call the middleware function
                    consistency::middleware::consistency_middleware(req, next).await
                }
            },
        ));

        // Add consistency API endpoints
        app = app.merge(consistency_router(consistency_state));
        debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");

        // Add fidelity score endpoints
        {
            use crate::handlers::fidelity::{fidelity_router, FidelityState};
            let fidelity_state = FidelityState::new();
            app = app.merge(fidelity_router(fidelity_state));
            debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
        }

        // Add scenario studio endpoints
        {
            use crate::handlers::scenario_studio::{scenario_studio_router, ScenarioStudioState};
            let scenario_studio_state = ScenarioStudioState::new();
            app = app.merge(scenario_studio_router(scenario_studio_state));
            debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
        }

        // Add performance mode endpoints
        {
            use crate::handlers::performance::{performance_router, PerformanceState};
            let performance_state = PerformanceState::new();
            app = app.nest("/api/performance", performance_router(performance_state));
            debug!("Performance mode endpoints mounted at /api/performance");
        }

        // Add world state endpoints
        {
            use crate::handlers::world_state::{world_state_router, WorldStateState};
            use mockforge_world_state::WorldStateEngine;
            use std::sync::Arc;
            use tokio::sync::RwLock;

            let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
            let world_state_state = WorldStateState {
                engine: world_state_engine,
            };
            app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
            debug!("World state endpoints mounted at /api/world-state");
        }

        // Add snapshot management endpoints
        {
            use crate::handlers::snapshots::{snapshot_router, SnapshotState};
            use mockforge_core::snapshots::SnapshotManager;
            use std::path::PathBuf;

            let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
            let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));

            let snapshot_state = SnapshotState {
                manager: snapshot_manager,
                consistency_engine: Some(consistency_engine.clone()),
                workspace_persistence: None, // Can be initialized later if workspace persistence is available
                vbr_engine: None, // Can be initialized when VBR engine is available in server state
                recorder: None,   // Can be initialized when Recorder is available in server state
            };

            app = app.merge(snapshot_router(snapshot_state));
            debug!("Snapshot management endpoints mounted at /api/v1/snapshots");

            // Add X-Ray API endpoints for browser extension
            {
                use crate::handlers::xray::xray_router;
                app = app.merge(xray_router((*xray_state).clone()));
                debug!("X-Ray API endpoints mounted at /api/v1/xray");
            }
        }

        // Add A/B testing endpoints and middleware
        {
            use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
            use crate::middleware::ab_testing::ab_testing_middleware;

            let ab_testing_state = ABTestingState::new();

            // Add A/B testing middleware (before other response middleware)
            let ab_testing_state_clone = ab_testing_state.clone();
            app = app.layer(axum::middleware::from_fn(
                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
                    let state = ab_testing_state_clone.clone();
                    async move {
                        // Insert state into extensions if not already present
                        if req.extensions().get::<ABTestingState>().is_none() {
                            req.extensions_mut().insert(state);
                        }
                        // Call the middleware function
                        ab_testing_middleware(req, next).await
                    }
                },
            ));

            // Add A/B testing API endpoints
            app = app.merge(ab_testing_router(ab_testing_state));
            debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
        }
    }

    // Add PR generation endpoints (optional - only if configured)
    {
        use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
        use mockforge_core::pr_generation::{PRGenerator, PRProvider};
        use std::sync::Arc;

        // Load PR generation config from environment or use default
        let pr_config = mockforge_core::pr_generation::PRGenerationConfig::from_env();

        let generator = if pr_config.enabled && pr_config.token.is_some() {
            let token = pr_config.token.as_ref().unwrap().clone();
            let generator = match pr_config.provider {
                PRProvider::GitHub => PRGenerator::new_github(
                    pr_config.owner.clone(),
                    pr_config.repo.clone(),
                    token,
                    pr_config.base_branch.clone(),
                ),
                PRProvider::GitLab => PRGenerator::new_gitlab(
                    pr_config.owner.clone(),
                    pr_config.repo.clone(),
                    token,
                    pr_config.base_branch.clone(),
                ),
            };
            Some(Arc::new(generator))
        } else {
            None
        };

        let pr_state = PRGenerationState {
            generator: generator.clone(),
        };

        app = app.merge(pr_generation_router(pr_state));
        if generator.is_some() {
            debug!(
                "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
                pr_config.provider
            );
        } else {
            debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
        }
    }

    // Add management WebSocket endpoint
    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));

    // Add workspace routing middleware if multi-tenant is enabled
    if let Some(mt_config) = multi_tenant_config {
        if mt_config.enabled {
            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
            use std::sync::Arc;

            info!(
                "Multi-tenant mode enabled with {} routing strategy",
                match mt_config.routing_strategy {
                    mockforge_core::RoutingStrategy::Path => "path-based",
                    mockforge_core::RoutingStrategy::Port => "port-based",
                    mockforge_core::RoutingStrategy::Both => "hybrid",
                }
            );

            // Create the multi-tenant workspace registry
            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());

            // Register the default workspace before wrapping in Arc
            let default_workspace =
                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
            if let Err(e) =
                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
            {
                warn!("Failed to register default workspace: {}", e);
            } else {
                info!("Registered default workspace: '{}'", mt_config.default_workspace);
            }

            // Wrap registry in Arc for shared access
            let registry = Arc::new(registry);

            // Create workspace router
            let _workspace_router = WorkspaceRouter::new(registry);
            info!("Workspace routing middleware initialized for HTTP server");
        }
    }

    // Apply deceptive deploy configuration if enabled
    let mut final_cors_config = cors_config;
    let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
    // Auth config from deceptive deploy OAuth (if configured)
    let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
    let mut rate_limit_config = middleware::RateLimitConfig {
        requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(1000),
        burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(2000),
        per_ip: true,
        per_endpoint: false,
    };

    if let Some(deploy_config) = &deceptive_deploy_config {
        if deploy_config.enabled {
            info!("Deceptive deploy mode enabled - applying production-like configuration");

            // Override CORS config if provided
            if let Some(prod_cors) = &deploy_config.cors {
                final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
                    enabled: true,
                    allowed_origins: prod_cors.allowed_origins.clone(),
                    allowed_methods: prod_cors.allowed_methods.clone(),
                    allowed_headers: prod_cors.allowed_headers.clone(),
                    allow_credentials: prod_cors.allow_credentials,
                });
                info!("Applied production-like CORS configuration");
            }

            // Override rate limit config if provided
            if let Some(prod_rate_limit) = &deploy_config.rate_limit {
                rate_limit_config = middleware::RateLimitConfig {
                    requests_per_minute: prod_rate_limit.requests_per_minute,
                    burst: prod_rate_limit.burst,
                    per_ip: prod_rate_limit.per_ip,
                    per_endpoint: false,
                };
                info!(
                    "Applied production-like rate limiting: {} req/min, burst: {}",
                    prod_rate_limit.requests_per_minute, prod_rate_limit.burst
                );
            }

            // Set production headers
            if !deploy_config.headers.is_empty() {
                let headers_map: HashMap<String, String> = deploy_config.headers.clone();
                production_headers = Some(std::sync::Arc::new(headers_map));
                info!("Configured {} production headers", deploy_config.headers.len());
            }

            // Integrate OAuth config from deceptive deploy
            if let Some(prod_oauth) = &deploy_config.oauth {
                let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
                deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
                    oauth2: Some(oauth2_config),
                    ..Default::default()
                });
                info!("Applied production-like OAuth configuration for deceptive deploy");
            }
        }
    }

    // Initialize rate limiter and state
    let rate_limiter =
        std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));

    let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());

    // Add production headers to state if configured
    if let Some(headers) = production_headers.clone() {
        state = state.with_production_headers(headers);
    }

    // Add rate limiting middleware
    app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));

    // Add production headers middleware if configured
    if state.production_headers.is_some() {
        app =
            app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
    }

    // Add authentication middleware if OAuth is configured via deceptive deploy
    if let Some(auth_config) = deceptive_deploy_auth_config {
        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
        use std::collections::HashMap;
        use std::sync::Arc;
        use tokio::sync::RwLock;

        // Create OAuth2 client if configured
        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
            match create_oauth2_client(oauth2_config) {
                Ok(client) => Some(client),
                Err(e) => {
                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
                    None
                }
            }
        } else {
            None
        };

        // Create auth state
        let auth_state = AuthState {
            config: auth_config,
            spec: None, // OpenAPI spec not available in this context
            oauth2_client,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        // Apply auth middleware
        app = app.layer(from_fn_with_state(auth_state, auth_middleware));
        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
    }

    // Add runtime daemon 404 detection middleware (if enabled)
    #[cfg(feature = "runtime-daemon")]
    {
        use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
        use std::sync::Arc;

        // Load runtime daemon config from environment
        let daemon_config = RuntimeDaemonConfig::from_env();

        if daemon_config.enabled {
            info!("Runtime daemon enabled - auto-creating mocks from 404s");

            // Determine management API URL (default to localhost:3000)
            let management_api_url =
                std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
                    let port =
                        std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
                    format!("http://localhost:{}", port)
                });

            // Create auto-generator
            let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));

            // Create detector and set generator
            let detector = NotFoundDetector::new(daemon_config.clone());
            detector.set_generator(generator).await;

            // Add middleware layer
            let detector_clone = detector.clone();
            app = app.layer(axum::middleware::from_fn(
                move |req: axum::extract::Request, next: axum::middleware::Next| {
                    let detector = detector_clone.clone();
                    async move { detector.detect_and_auto_create(req, next).await }
                },
            ));

            debug!("Runtime daemon 404 detection middleware added");
        }
    }

    // Add /__mockforge/routes endpoint so the admin UI can discover registered routes
    {
        let routes_state = HttpServerState::with_routes(captured_routes);
        let routes_router = Router::new()
            .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
            .with_state(routes_state);
        app = app.merge(routes_router);
    }

    // Add API docs page (Scalar-powered interactive explorer)
    app = app.route("/__mockforge/docs", axum::routing::get(get_docs_handler));

    // Note: OData URI rewrite is applied at the service level in serve_router_with_tls()
    // because Router::layer() only applies to matched routes, not unmatched ones.

    // Add request logging middleware to capture all requests for the admin dashboard
    app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));

    // Add contract diff middleware for automatic request capture
    // This captures requests for contract diff analysis
    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));

    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
    app = apply_cors_middleware(app, final_cors_config);

    app
}

// Note: start_with_traffic_shaping function removed due to compilation issues
// Use build_router_with_traffic_shaping_and_multi_tenant directly instead

#[test]
fn test_route_info_clone() {
    let route = RouteInfo {
        method: "POST".to_string(),
        path: "/users".to_string(),
        operation_id: Some("createUser".to_string()),
        summary: None,
        description: None,
        parameters: vec![],
    };

    let cloned = route.clone();
    assert_eq!(route.method, cloned.method);
    assert_eq!(route.path, cloned.path);
    assert_eq!(route.operation_id, cloned.operation_id);
}

#[test]
fn test_http_server_state_new() {
    let state = HttpServerState::new();
    assert_eq!(state.routes.len(), 0);
}

#[test]
fn test_http_server_state_with_routes() {
    let routes = vec![
        RouteInfo {
            method: "GET".to_string(),
            path: "/users".to_string(),
            operation_id: Some("getUsers".to_string()),
            summary: None,
            description: None,
            parameters: vec![],
        },
        RouteInfo {
            method: "POST".to_string(),
            path: "/users".to_string(),
            operation_id: Some("createUser".to_string()),
            summary: None,
            description: None,
            parameters: vec![],
        },
    ];

    let state = HttpServerState::with_routes(routes.clone());
    assert_eq!(state.routes.len(), 2);
    assert_eq!(state.routes[0].method, "GET");
    assert_eq!(state.routes[1].method, "POST");
}

#[test]
fn test_http_server_state_clone() {
    let routes = vec![RouteInfo {
        method: "GET".to_string(),
        path: "/test".to_string(),
        operation_id: None,
        summary: None,
        description: None,
        parameters: vec![],
    }];

    let state = HttpServerState::with_routes(routes);
    let cloned = state.clone();

    assert_eq!(state.routes.len(), cloned.routes.len());
    assert_eq!(state.routes[0].method, cloned.routes[0].method);
}

#[tokio::test]
async fn test_build_router_without_openapi() {
    let _router = build_router(None, None, None).await;
    // Should succeed without OpenAPI spec
}

#[tokio::test]
async fn test_build_router_with_nonexistent_spec() {
    let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
    // Should succeed but log a warning
}

#[tokio::test]
async fn test_build_router_with_auth_and_latency() {
    let _router = build_router_with_auth_and_latency(None, None, None, None).await;
    // Should succeed without parameters
}

#[tokio::test]
async fn test_build_router_with_latency() {
    let _router = build_router_with_latency(None, None, None).await;
    // Should succeed without parameters
}

#[tokio::test]
async fn test_build_router_with_auth() {
    let _router = build_router_with_auth(None, None, None).await;
    // Should succeed without parameters
}

#[tokio::test]
async fn test_build_router_with_chains() {
    let _router = build_router_with_chains(None, None, None).await;
    // Should succeed without parameters
}

#[test]
fn test_route_info_with_all_fields() {
    let route = RouteInfo {
        method: "PUT".to_string(),
        path: "/users/{id}".to_string(),
        operation_id: Some("updateUser".to_string()),
        summary: Some("Update user".to_string()),
        description: Some("Updates an existing user".to_string()),
        parameters: vec!["id".to_string(), "body".to_string()],
    };

    assert!(route.operation_id.is_some());
    assert!(route.summary.is_some());
    assert!(route.description.is_some());
    assert_eq!(route.parameters.len(), 2);
}

#[test]
fn test_route_info_with_minimal_fields() {
    let route = RouteInfo {
        method: "DELETE".to_string(),
        path: "/users/{id}".to_string(),
        operation_id: None,
        summary: None,
        description: None,
        parameters: vec![],
    };

    assert!(route.operation_id.is_none());
    assert!(route.summary.is_none());
    assert!(route.description.is_none());
    assert_eq!(route.parameters.len(), 0);
}

#[test]
fn test_http_server_state_empty_routes() {
    let state = HttpServerState::with_routes(vec![]);
    assert_eq!(state.routes.len(), 0);
}

#[test]
fn test_http_server_state_multiple_routes() {
    let routes = vec![
        RouteInfo {
            method: "GET".to_string(),
            path: "/users".to_string(),
            operation_id: Some("listUsers".to_string()),
            summary: Some("List all users".to_string()),
            description: None,
            parameters: vec![],
        },
        RouteInfo {
            method: "GET".to_string(),
            path: "/users/{id}".to_string(),
            operation_id: Some("getUser".to_string()),
            summary: Some("Get a user".to_string()),
            description: None,
            parameters: vec!["id".to_string()],
        },
        RouteInfo {
            method: "POST".to_string(),
            path: "/users".to_string(),
            operation_id: Some("createUser".to_string()),
            summary: Some("Create a user".to_string()),
            description: None,
            parameters: vec!["body".to_string()],
        },
    ];

    let state = HttpServerState::with_routes(routes);
    assert_eq!(state.routes.len(), 3);

    // Verify different HTTP methods
    let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
    assert!(methods.contains(&"GET"));
    assert!(methods.contains(&"POST"));
}

#[test]
fn test_http_server_state_with_rate_limiter() {
    use std::sync::Arc;

    let config = crate::middleware::RateLimitConfig::default();
    let rate_limiter = Arc::new(crate::middleware::GlobalRateLimiter::new(config));

    let state = HttpServerState::new().with_rate_limiter(rate_limiter);

    assert!(state.rate_limiter.is_some());
    assert_eq!(state.routes.len(), 0);
}

#[tokio::test]
async fn test_build_router_includes_rate_limiter() {
    let _router = build_router(None, None, None).await;
    // Router should be created successfully with rate limiter initialized
}