mockforge-core 0.3.115

Shared logic for MockForge - routing, validation, latency, proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
//! OpenAPI-based route generation for MockForge
//!
//! The authoritative `OpenApiRouteRegistry` and all `build_router_*` methods
//! are defined in this file. Sub-modules provide additional utilities:
//! - `builder`: Helper functions for building routers from specs
//! - `generation`: Route generation utilities
//! - `validation`: Request/response validation types and logic
//!
//! Note: `registry` sub-module contains an abandoned partial refactoring with a
//! duplicate `OpenApiRouteRegistry` type. Use the one from this module.

pub mod builder;
pub mod generation;
#[doc(hidden)]
pub mod registry;
pub mod validation;

use crate::ai_response::RequestContext;
use crate::openapi::response::AiGenerator;
use crate::openapi::{OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSpec};
use crate::reality_continuum::response_trace::ResponseGenerationTrace;
use crate::schema_diff::validation_diff;
use crate::templating::expand_tokens as core_expand_tokens;
use crate::{latency::LatencyInjector, overrides::Overrides, Error, Result};
use axum::extract::{Path as AxumPath, RawQuery};
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::routing::*;
use axum::{Json, Router};
pub use builder::*;
use chrono::Utc;
pub use generation::*;
use once_cell::sync::Lazy;
use openapiv3::ParameterSchemaOrContent;
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use tracing;
pub use validation::*;

/// OpenAPI route registry that manages generated routes
#[derive(Clone)]
pub struct OpenApiRouteRegistry {
    /// The OpenAPI specification
    spec: Arc<OpenApiSpec>,
    /// Generated routes
    routes: Vec<OpenApiRoute>,
    /// Validation options
    options: ValidationOptions,
    /// Custom fixture loader (optional)
    custom_fixture_loader: Option<Arc<crate::CustomFixtureLoader>>,
}

/// Validation mode for request/response validation
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
pub enum ValidationMode {
    /// Validation is disabled (no checks performed)
    Disabled,
    /// Validation warnings are logged but do not fail requests
    #[default]
    Warn,
    /// Validation failures return error responses
    Enforce,
}

/// Options for configuring validation behavior
#[derive(Debug, Clone)]
pub struct ValidationOptions {
    /// Validation mode for incoming requests
    pub request_mode: ValidationMode,
    /// Whether to aggregate multiple validation errors into a single response
    pub aggregate_errors: bool,
    /// Whether to validate outgoing responses against schemas
    pub validate_responses: bool,
    /// Per-operation validation mode overrides (operation ID -> mode)
    pub overrides: HashMap<String, ValidationMode>,
    /// Skip validation for request paths starting with any of these prefixes
    pub admin_skip_prefixes: Vec<String>,
    /// Expand templating tokens in responses/examples after generation
    pub response_template_expand: bool,
    /// HTTP status code to return for validation failures (e.g., 400 or 422)
    pub validation_status: Option<u16>,
}

impl Default for ValidationOptions {
    fn default() -> Self {
        Self {
            request_mode: ValidationMode::Enforce,
            aggregate_errors: true,
            validate_responses: false,
            overrides: HashMap::new(),
            admin_skip_prefixes: Vec::new(),
            response_template_expand: false,
            validation_status: None,
        }
    }
}

/// Shared context for all route handlers, encapsulating optional features.
///
/// Each `build_router_*` variant constructs a `RouterContext` with the appropriate
/// features enabled, then delegates to `build_router_with_context`.
#[derive(Clone)]
pub struct RouterContext {
    /// Custom fixture loader (highest priority response source)
    pub custom_fixture_loader: Option<Arc<crate::CustomFixtureLoader>>,
    /// Latency injector (per-operation-tag latency simulation)
    pub latency_injector: Option<LatencyInjector>,
    /// Failure injector (per-tag fault injection)
    pub failure_injector: Option<crate::FailureInjector>,
    /// Response overrides
    pub overrides: Option<Overrides>,
    /// Whether overrides are active
    pub overrides_enabled: bool,
    /// AI response generator
    pub ai_generator: Option<Arc<dyn crate::openapi::response::AiGenerator + Send + Sync>>,
    /// MockAI intelligent behavior engine
    pub mockai: Option<Arc<tokio::sync::RwLock<crate::intelligent_behavior::MockAI>>>,
    /// Enable full validation (422 enhanced responses, response validation, trace)
    pub enable_full_validation: bool,
    /// Enable template token expansion
    pub enable_template_expand: bool,
    /// Whether to add /openapi.json endpoint
    pub add_spec_endpoint: bool,
}

impl Default for RouterContext {
    fn default() -> Self {
        Self {
            custom_fixture_loader: None,
            latency_injector: None,
            failure_injector: None,
            overrides: None,
            overrides_enabled: false,
            ai_generator: None,
            mockai: None,
            enable_full_validation: false,
            enable_template_expand: false,
            add_spec_endpoint: true,
        }
    }
}

impl OpenApiRouteRegistry {
    /// Create a new registry from an OpenAPI spec
    pub fn new(spec: OpenApiSpec) -> Self {
        Self::new_with_env(spec)
    }

    /// Create a new registry from an OpenAPI spec with environment-based validation options
    ///
    /// Options are read from environment variables:
    /// - `MOCKFORGE_REQUEST_VALIDATION`: "off"/"warn"/"enforce" (default: "enforce")
    /// - `MOCKFORGE_AGGREGATE_ERRORS`: "1"/"true" to aggregate errors (default: true)
    /// - `MOCKFORGE_RESPONSE_VALIDATION`: "1"/"true" to validate responses (default: false)
    /// - `MOCKFORGE_RESPONSE_TEMPLATE_EXPAND`: "1"/"true" to expand templates (default: false)
    /// - `MOCKFORGE_VALIDATION_STATUS`: HTTP status code for validation failures (optional)
    pub fn new_with_env(spec: OpenApiSpec) -> Self {
        Self::new_with_env_and_persona(spec, None)
    }

    /// Create a new registry from an OpenAPI spec with environment-based validation options and persona
    pub fn new_with_env_and_persona(
        spec: OpenApiSpec,
        persona: Option<Arc<crate::intelligent_behavior::config::Persona>>,
    ) -> Self {
        tracing::debug!("Creating OpenAPI route registry");
        let spec = Arc::new(spec);
        let routes = Self::generate_routes_with_persona(&spec, persona);
        let options = ValidationOptions {
            request_mode: match std::env::var("MOCKFORGE_REQUEST_VALIDATION")
                .unwrap_or_else(|_| "enforce".into())
                .to_ascii_lowercase()
                .as_str()
            {
                "off" | "disable" | "disabled" => ValidationMode::Disabled,
                "warn" | "warning" => ValidationMode::Warn,
                _ => ValidationMode::Enforce,
            },
            aggregate_errors: std::env::var("MOCKFORGE_AGGREGATE_ERRORS")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(true),
            validate_responses: std::env::var("MOCKFORGE_RESPONSE_VALIDATION")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false),
            overrides: HashMap::new(),
            admin_skip_prefixes: Vec::new(),
            response_template_expand: std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false),
            validation_status: std::env::var("MOCKFORGE_VALIDATION_STATUS")
                .ok()
                .and_then(|s| s.parse::<u16>().ok()),
        };
        Self {
            spec,
            routes,
            options,
            custom_fixture_loader: None,
        }
    }

    /// Construct with explicit options
    pub fn new_with_options(spec: OpenApiSpec, options: ValidationOptions) -> Self {
        Self::new_with_options_and_persona(spec, options, None)
    }

    /// Construct with explicit options and persona
    pub fn new_with_options_and_persona(
        spec: OpenApiSpec,
        options: ValidationOptions,
        persona: Option<Arc<crate::intelligent_behavior::config::Persona>>,
    ) -> Self {
        tracing::debug!("Creating OpenAPI route registry with custom options");
        let spec = Arc::new(spec);
        let routes = Self::generate_routes_with_persona(&spec, persona);
        Self {
            spec,
            routes,
            options,
            custom_fixture_loader: None,
        }
    }

    /// Set custom fixture loader
    pub fn with_custom_fixture_loader(mut self, loader: Arc<crate::CustomFixtureLoader>) -> Self {
        self.custom_fixture_loader = Some(loader);
        self
    }

    /// Clone this registry for validation purposes (creates an independent copy)
    ///
    /// This is useful when you need a separate registry instance for validation
    /// that won't interfere with the main registry's state.
    pub fn clone_for_validation(&self) -> Self {
        OpenApiRouteRegistry {
            spec: self.spec.clone(),
            routes: self.routes.clone(),
            options: self.options.clone(),
            custom_fixture_loader: self.custom_fixture_loader.clone(),
        }
    }

    /// Generate routes from the OpenAPI specification with optional persona
    fn generate_routes_with_persona(
        spec: &Arc<OpenApiSpec>,
        persona: Option<Arc<crate::intelligent_behavior::config::Persona>>,
    ) -> Vec<OpenApiRoute> {
        let mut routes = Vec::new();

        let all_paths_ops = spec.all_paths_and_operations();
        tracing::debug!("Generating routes from OpenAPI spec with {} paths", all_paths_ops.len());

        for (path, operations) in all_paths_ops {
            tracing::debug!("Processing path: {}", path);
            for (method, operation) in operations {
                routes.push(OpenApiRoute::from_operation_with_persona(
                    &method,
                    path.clone(),
                    &operation,
                    spec.clone(),
                    persona.clone(),
                ));
            }
        }

        tracing::debug!("Generated {} total routes from OpenAPI spec", routes.len());
        routes
    }

    /// Get all routes
    pub fn routes(&self) -> &[OpenApiRoute] {
        &self.routes
    }

    /// Get the OpenAPI specification
    pub fn spec(&self) -> &OpenApiSpec {
        &self.spec
    }

    /// Normalize an Axum path for dedup by replacing all `{param}` with `{_}`.
    /// This ensures paths like `/func/{period}` and `/func/{date}` are treated as duplicates,
    /// since Axum/matchit treats all path parameters as equivalent for routing.
    fn normalize_path_for_dedup(path: &str) -> String {
        let mut result = String::with_capacity(path.len());
        let mut in_brace = false;
        for ch in path.chars() {
            if ch == '{' {
                in_brace = true;
                result.push_str("{_}");
            } else if ch == '}' {
                in_brace = false;
            } else if !in_brace {
                result.push(ch);
            }
        }
        result
    }

    /// Returns deduplicated routes with their resolved Axum-compatible paths.
    ///
    /// Handles path validation, canonical param-name resolution (to prevent matchit panics
    /// when two OpenAPI paths differ only in param names), and duplicate detection.
    /// This is the shared preamble extracted from all `build_router_*` variants.
    fn deduplicated_routes(&self) -> Vec<(String, &OpenApiRoute)> {
        let mut result = Vec::new();
        let mut registered_routes: HashSet<(String, String)> = HashSet::new();
        let mut canonical_paths: HashMap<String, String> = HashMap::new();

        for route in &self.routes {
            if !route.is_valid_axum_path() {
                tracing::warn!(
                    "Skipping route with unsupported path syntax: {} {}",
                    route.method,
                    route.path
                );
                continue;
            }
            let axum_path = route.axum_path();
            let normalized = Self::normalize_path_for_dedup(&axum_path);
            let axum_path = canonical_paths
                .entry(normalized.clone())
                .or_insert_with(|| axum_path.clone())
                .clone();
            let route_key = (route.method.clone(), normalized);
            if !registered_routes.insert(route_key) {
                tracing::debug!(
                    "Skipping duplicate route: {} {} (axum path: {})",
                    route.method,
                    route.path,
                    axum_path
                );
                continue;
            }
            result.push((axum_path, route));
        }
        result
    }

    /// Register a handler on a router for the given HTTP method.
    ///
    /// Shared epilogue extracted from all `build_router_*` variants.
    fn route_for_method<H, T>(router: Router, path: &str, method: &str, handler: H) -> Router
    where
        H: axum::handler::Handler<T, ()>,
        T: 'static,
    {
        match method {
            "GET" => router.route(path, get(handler)),
            "POST" => router.route(path, post(handler)),
            "PUT" => router.route(path, put(handler)),
            "DELETE" => router.route(path, delete(handler)),
            "PATCH" => router.route(path, patch(handler)),
            "HEAD" => router.route(path, head(handler)),
            "OPTIONS" => router.route(path, options(handler)),
            _ => router,
        }
    }

    /// Build an Axum router from the OpenAPI spec (simplified)
    pub fn build_router(self) -> Router {
        let ctx = RouterContext {
            custom_fixture_loader: self.custom_fixture_loader.clone(),
            enable_full_validation: true,
            enable_template_expand: true,
            add_spec_endpoint: true,
            ..Default::default()
        };
        self.build_router_with_context(ctx)
    }

    /// Build an Axum router using a shared RouterContext.
    ///
    /// This is the unified router builder that all `build_router_*` variants
    /// delegate to. The RouterContext controls which features are active.
    fn build_router_with_context(self, ctx: RouterContext) -> Router {
        let mut router = Router::new();
        tracing::debug!("Building router from {} routes", self.routes.len());

        let deduped = self.deduplicated_routes();
        let ctx = Arc::new(ctx);
        for (axum_path, route) in &deduped {
            tracing::debug!("Adding route: {} {}", route.method, route.path);
            let operation = route.operation.clone();
            let method = route.method.clone();
            let path_template = route.path.clone();
            let validator = self.clone_for_validation();
            let route_clone = (*route).clone();
            let ctx = ctx.clone();

            // Extract tags from operation for latency and failure injection
            let mut operation_tags = operation.tags.clone();
            if let Some(operation_id) = &operation.operation_id {
                operation_tags.push(operation_id.clone());
            }

            // Unified handler: fixture -> failure -> latency -> scenario/override -> mock -> validate -> expand -> overrides -> trace -> response
            let handler = move |AxumPath(path_params): AxumPath<HashMap<String, String>>,
                                RawQuery(raw_query): RawQuery,
                                headers: HeaderMap,
                                body: axum::body::Bytes| async move {
                tracing::debug!("Handling OpenAPI request: {} {}", method, path_template);

                // (a) Check for custom fixture first (highest priority)
                if let Some(ref loader) = ctx.custom_fixture_loader {
                    use crate::RequestFingerprint;
                    use axum::http::{Method, Uri};

                    // Reconstruct the full path from template and params
                    let mut request_path = path_template.clone();
                    for (key, value) in &path_params {
                        request_path = request_path.replace(&format!("{{{}}}", key), value);
                    }

                    // Normalize the path to match fixture normalization
                    let normalized_request_path =
                        crate::CustomFixtureLoader::normalize_path(&request_path);

                    // Build query string
                    let query_string =
                        raw_query.as_ref().map(|q| q.to_string()).unwrap_or_default();

                    // Create URI for fingerprint
                    // IMPORTANT: Use normalized path to match fixture paths
                    let uri_str = if query_string.is_empty() {
                        normalized_request_path.clone()
                    } else {
                        format!("{}?{}", normalized_request_path, query_string)
                    };

                    if let Ok(uri) = uri_str.parse::<Uri>() {
                        let http_method =
                            Method::from_bytes(method.as_bytes()).unwrap_or(Method::GET);
                        let body_slice = if body.is_empty() {
                            None
                        } else {
                            Some(body.as_ref())
                        };
                        let fingerprint =
                            RequestFingerprint::new(http_method, &uri, &headers, body_slice);

                        // Debug logging for fixture matching
                        tracing::debug!(
                            "Checking fixture for {} {} (template: '{}', request_path: '{}', normalized: '{}', fingerprint.path: '{}')",
                            method,
                            path_template,
                            path_template,
                            request_path,
                            normalized_request_path,
                            fingerprint.path
                        );

                        if let Some(custom_fixture) = loader.load_fixture(&fingerprint) {
                            tracing::debug!(
                                "Using custom fixture for {} {}",
                                method,
                                path_template
                            );

                            // Apply delay if specified
                            if custom_fixture.delay_ms > 0 {
                                tokio::time::sleep(tokio::time::Duration::from_millis(
                                    custom_fixture.delay_ms,
                                ))
                                .await;
                            }

                            // Convert response to JSON string if needed
                            let response_body = if custom_fixture.response.is_string() {
                                custom_fixture.response.as_str().unwrap().to_string()
                            } else {
                                serde_json::to_string(&custom_fixture.response)
                                    .unwrap_or_else(|_| "{}".to_string())
                            };

                            // Parse response body as JSON
                            let json_value: Value = serde_json::from_str(&response_body)
                                .unwrap_or_else(|_| serde_json::json!({}));

                            // Build response with status and JSON body
                            let status = axum::http::StatusCode::from_u16(custom_fixture.status)
                                .unwrap_or(axum::http::StatusCode::OK);

                            let mut response = (status, Json(json_value)).into_response();

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

                            // Ensure content-type is set if not already present
                            if !custom_fixture.headers.contains_key("content-type") {
                                response_headers.insert(
                                    axum::http::header::CONTENT_TYPE,
                                    axum::http::HeaderValue::from_static("application/json"),
                                );
                            }

                            return response;
                        }
                    }
                }

                // (b) Failure injection (if configured)
                if let Some(ref failure_injector) = ctx.failure_injector {
                    if let Some((status_code, error_message)) =
                        failure_injector.process_request(&operation_tags)
                    {
                        let payload = serde_json::json!({
                            "error": error_message,
                            "injected_failure": true
                        });
                        let body_bytes = serde_json::to_vec(&payload)
                            .unwrap_or_else(|_| br#"{"error":"injected failure"}"#.to_vec());
                        return axum::http::Response::builder()
                            .status(
                                axum::http::StatusCode::from_u16(status_code)
                                    .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR),
                            )
                            .header(axum::http::header::CONTENT_TYPE, "application/json")
                            .body(axum::body::Body::from(body_bytes))
                            .expect("Response builder should create valid response");
                    }
                }

                // (c) Latency injection (if configured)
                if let Some(ref injector) = ctx.latency_injector {
                    if let Err(e) = injector.inject_latency(&operation_tags).await {
                        tracing::warn!("Failed to inject latency: {}", e);
                    }
                }

                // (d) Scenario/status override from headers
                let scenario = headers
                    .get("X-Mockforge-Scenario")
                    .and_then(|v| v.to_str().ok())
                    .map(|s| s.to_string())
                    .or_else(|| std::env::var("MOCKFORGE_HTTP_SCENARIO").ok());

                let status_override = headers
                    .get("X-Mockforge-Response-Status")
                    .and_then(|v| v.to_str().ok())
                    .and_then(|s| s.parse::<u16>().ok());

                // (e) Generate mock response for this request with scenario support
                let (selected_status, mock_response) = route_clone
                    .mock_response_with_status_and_scenario_and_override(
                        scenario.as_deref(),
                        status_override,
                    );

                // (f) Validation (if full validation is enabled)
                if ctx.enable_full_validation {
                    // Build params maps
                    let mut path_map = Map::new();
                    for (k, v) in &path_params {
                        path_map.insert(k.clone(), Value::String(v.clone()));
                    }

                    // Query
                    let mut query_map = Map::new();
                    if let Some(ref q) = raw_query {
                        for (k, v) in url::form_urlencoded::parse(q.as_bytes()) {
                            query_map.insert(k.to_string(), Value::String(v.to_string()));
                        }
                    }

                    // Headers: only capture those declared on this operation
                    let mut header_map = Map::new();
                    for p_ref in &operation.parameters {
                        if let Some(openapiv3::Parameter::Header { parameter_data, .. }) =
                            p_ref.as_item()
                        {
                            let name_lc = parameter_data.name.to_ascii_lowercase();
                            if let Ok(hn) = axum::http::HeaderName::from_bytes(name_lc.as_bytes()) {
                                if let Some(val) = headers.get(hn) {
                                    if let Ok(s) = val.to_str() {
                                        header_map.insert(
                                            parameter_data.name.clone(),
                                            Value::String(s.to_string()),
                                        );
                                    }
                                }
                            }
                        }
                    }

                    // Cookies: parse Cookie header
                    let mut cookie_map = Map::new();
                    if let Some(val) = headers.get(axum::http::header::COOKIE) {
                        if let Ok(s) = val.to_str() {
                            for part in s.split(';') {
                                let part = part.trim();
                                if let Some((k, v)) = part.split_once('=') {
                                    cookie_map.insert(k.to_string(), Value::String(v.to_string()));
                                }
                            }
                        }
                    }

                    // Check if this is a multipart request
                    let is_multipart = headers
                        .get(axum::http::header::CONTENT_TYPE)
                        .and_then(|v| v.to_str().ok())
                        .map(|ct| ct.starts_with("multipart/form-data"))
                        .unwrap_or(false);

                    // Extract multipart data if applicable
                    #[allow(unused_assignments)]
                    let mut multipart_fields = HashMap::new();
                    let mut _multipart_files = HashMap::new();
                    let mut body_json: Option<Value> = None;

                    if is_multipart {
                        // For multipart requests, extract fields and files
                        match extract_multipart_from_bytes(&body, &headers).await {
                            Ok((fields, files)) => {
                                multipart_fields = fields;
                                _multipart_files = files;
                                // Also create a JSON representation for validation
                                let mut body_obj = Map::new();
                                for (k, v) in &multipart_fields {
                                    body_obj.insert(k.clone(), v.clone());
                                }
                                if !body_obj.is_empty() {
                                    body_json = Some(Value::Object(body_obj));
                                }
                            }
                            Err(e) => {
                                tracing::warn!("Failed to parse multipart data: {}", e);
                            }
                        }
                    } else {
                        // Body: try JSON when present
                        body_json = if !body.is_empty() {
                            serde_json::from_slice(&body).ok()
                        } else {
                            None
                        };
                    }

                    if let Err(e) = validator.validate_request_with_all(
                        &path_template,
                        &method,
                        &path_map,
                        &query_map,
                        &header_map,
                        &cookie_map,
                        body_json.as_ref(),
                    ) {
                        // Choose status: prefer options.validation_status, fallback to env, else 400
                        let status_code =
                            validator.options.validation_status.unwrap_or_else(|| {
                                std::env::var("MOCKFORGE_VALIDATION_STATUS")
                                    .ok()
                                    .and_then(|s| s.parse::<u16>().ok())
                                    .unwrap_or(400)
                            });

                        let payload = if status_code == 422 {
                            // For 422 responses, use enhanced schema validation with detailed errors
                            generate_enhanced_422_response(
                                &validator,
                                &path_template,
                                &method,
                                body_json.as_ref(),
                                &path_map,
                                &query_map,
                                &header_map,
                                &cookie_map,
                            )
                        } else {
                            // For other status codes, use generic error format
                            let msg = format!("{}", e);
                            let detail_val = serde_json::from_str::<Value>(&msg)
                                .unwrap_or(serde_json::json!(msg));
                            json!({
                                "error": "request validation failed",
                                "detail": detail_val,
                                "method": method,
                                "path": path_template,
                                "timestamp": Utc::now().to_rfc3339(),
                            })
                        };

                        record_validation_error(&payload);
                        let status = axum::http::StatusCode::from_u16(status_code)
                            .unwrap_or(axum::http::StatusCode::BAD_REQUEST);

                        // Serialize payload with fallback for serialization errors
                        let body_bytes = serde_json::to_vec(&payload)
                            .unwrap_or_else(|_| br#"{"error":"Serialization failed"}"#.to_vec());

                        return axum::http::Response::builder()
                            .status(status)
                            .header(axum::http::header::CONTENT_TYPE, "application/json")
                            .body(axum::body::Body::from(body_bytes))
                            .expect("Response builder should create valid response with valid headers and body");
                    }
                }

                // (g) Template expansion (if enabled via context or env var)
                let mut final_response = mock_response.clone();
                let env_expand = std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
                    .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                    .unwrap_or(false);
                let expand = ctx.enable_template_expand
                    || validator.options.response_template_expand
                    || env_expand;
                if expand {
                    final_response = core_expand_tokens(&final_response);
                }

                // (h) Apply overrides if provided and enabled
                if let Some(ref overrides) = ctx.overrides {
                    if ctx.overrides_enabled {
                        let op_tags =
                            operation.operation_id.clone().map(|id| vec![id]).unwrap_or_default();
                        overrides.apply(
                            &operation.operation_id.clone().unwrap_or_default(),
                            &op_tags,
                            &path_template,
                            &mut final_response,
                        );
                    }
                }

                // (i) Response validation and trace (if full validation is enabled)
                if ctx.enable_full_validation {
                    // Optional response validation
                    if validator.options.validate_responses {
                        // Find the first 2xx response in the operation
                        if let Some((status_code, _response)) = operation
                            .responses
                            .responses
                            .iter()
                            .filter_map(|(status, resp)| match status {
                                openapiv3::StatusCode::Code(code)
                                    if *code >= 200 && *code < 300 =>
                                {
                                    resp.as_item().map(|r| ((*code), r))
                                }
                                openapiv3::StatusCode::Range(range)
                                    if *range >= 200 && *range < 300 =>
                                {
                                    resp.as_item().map(|r| (200, r))
                                }
                                _ => None,
                            })
                            .next()
                        {
                            // Basic response validation - check if response is valid JSON
                            if serde_json::from_value::<Value>(final_response.clone()).is_err() {
                                tracing::warn!(
                                    "Response validation failed: invalid JSON for status {}",
                                    status_code
                                );
                            }
                        }
                    }

                    // Capture final payload and run schema validation for trace
                    let mut trace = ResponseGenerationTrace::new();
                    trace.set_final_payload(final_response.clone());

                    // Extract response schema and run validation diff
                    if let Some((_status_code, response_ref)) = operation
                        .responses
                        .responses
                        .iter()
                        .filter_map(|(status, resp)| match status {
                            openapiv3::StatusCode::Code(code) if *code == selected_status => {
                                resp.as_item().map(|r| ((*code), r))
                            }
                            openapiv3::StatusCode::Range(range)
                                if *range >= 200 && *range < 300 =>
                            {
                                resp.as_item().map(|r| (200, r))
                            }
                            _ => None,
                        })
                        .next()
                        .or_else(|| {
                            // Fallback to first 2xx response
                            operation
                                .responses
                                .responses
                                .iter()
                                .filter_map(|(status, resp)| match status {
                                    openapiv3::StatusCode::Code(code)
                                        if *code >= 200 && *code < 300 =>
                                    {
                                        resp.as_item().map(|r| ((*code), r))
                                    }
                                    _ => None,
                                })
                                .next()
                        })
                    {
                        // response_ref is already a Response, not a ReferenceOr
                        let response_item = response_ref;
                        // Extract schema from application/json content
                        if let Some(content) = response_item.content.get("application/json") {
                            if let Some(schema_ref) = &content.schema {
                                // Convert OpenAPI schema to JSON Schema Value
                                if let Some(schema) = schema_ref.as_item() {
                                    if let Ok(schema_json) = serde_json::to_value(schema) {
                                        // Run validation diff
                                        let validation_errors =
                                            validation_diff(&schema_json, &final_response);
                                        trace.set_schema_validation_diff(validation_errors);
                                    }
                                }
                            }
                        }
                    }

                    // Store trace in response extensions for later retrieval by logging middleware
                    let mut response = Json(final_response).into_response();
                    response.extensions_mut().insert(trace);
                    *response.status_mut() = axum::http::StatusCode::from_u16(selected_status)
                        .unwrap_or(axum::http::StatusCode::OK);
                    return response;
                }

                // (j) Return response (non-full-validation path)
                let mut response = Json(final_response).into_response();
                *response.status_mut() = axum::http::StatusCode::from_u16(selected_status)
                    .unwrap_or(axum::http::StatusCode::OK);
                response
            };

            router = Self::route_for_method(router, axum_path, &route.method, handler);
        }

        // Add OpenAPI documentation endpoint if configured
        if ctx.add_spec_endpoint {
            let spec_json = serde_json::to_value(&self.spec.spec).unwrap_or(Value::Null);
            router = router.route("/openapi.json", get(move || async move { Json(spec_json) }));
        }

        router
    }

    /// Build an Axum router from the OpenAPI spec with latency injection support
    pub fn build_router_with_latency(self, latency_injector: LatencyInjector) -> Router {
        self.build_router_with_injectors(latency_injector, None)
    }

    /// Build an Axum router from the OpenAPI spec with both latency and failure injection support
    pub fn build_router_with_injectors(
        self,
        latency_injector: LatencyInjector,
        failure_injector: Option<crate::FailureInjector>,
    ) -> Router {
        self.build_router_with_injectors_and_overrides(
            latency_injector,
            failure_injector,
            None,
            false,
        )
    }

    /// Build an Axum router from the OpenAPI spec with latency, failure injection, and overrides support
    pub fn build_router_with_injectors_and_overrides(
        self,
        latency_injector: LatencyInjector,
        failure_injector: Option<crate::FailureInjector>,
        overrides: Option<Overrides>,
        overrides_enabled: bool,
    ) -> Router {
        let ctx = RouterContext {
            custom_fixture_loader: self.custom_fixture_loader.clone(),
            latency_injector: Some(latency_injector),
            failure_injector,
            overrides,
            overrides_enabled,
            enable_template_expand: true,
            add_spec_endpoint: true,
            ..Default::default()
        };
        self.build_router_with_context(ctx)
    }

    /// Get route by path and method
    pub fn get_route(&self, path: &str, method: &str) -> Option<&OpenApiRoute> {
        self.routes.iter().find(|route| route.path == path && route.method == method)
    }

    /// Get all routes for a specific path
    pub fn get_routes_for_path(&self, path: &str) -> Vec<&OpenApiRoute> {
        self.routes.iter().filter(|route| route.path == path).collect()
    }

    /// Validate request against OpenAPI spec (legacy body-only)
    pub fn validate_request(&self, path: &str, method: &str, body: Option<&Value>) -> Result<()> {
        self.validate_request_with(path, method, &Map::new(), &Map::new(), body)
    }

    /// Validate request against OpenAPI spec with path/query params
    pub fn validate_request_with(
        &self,
        path: &str,
        method: &str,
        path_params: &Map<String, Value>,
        query_params: &Map<String, Value>,
        body: Option<&Value>,
    ) -> Result<()> {
        self.validate_request_with_all(
            path,
            method,
            path_params,
            query_params,
            &Map::new(),
            &Map::new(),
            body,
        )
    }

    /// Validate request against OpenAPI spec with path/query/header/cookie params
    #[allow(clippy::too_many_arguments)]
    pub fn validate_request_with_all(
        &self,
        path: &str,
        method: &str,
        path_params: &Map<String, Value>,
        query_params: &Map<String, Value>,
        header_params: &Map<String, Value>,
        cookie_params: &Map<String, Value>,
        body: Option<&Value>,
    ) -> Result<()> {
        // Skip validation for any configured admin prefixes
        for pref in &self.options.admin_skip_prefixes {
            if !pref.is_empty() && path.starts_with(pref) {
                return Ok(());
            }
        }
        // Runtime env overrides
        let env_mode = std::env::var("MOCKFORGE_REQUEST_VALIDATION").ok().map(|v| {
            match v.to_ascii_lowercase().as_str() {
                "off" | "disable" | "disabled" => ValidationMode::Disabled,
                "warn" | "warning" => ValidationMode::Warn,
                _ => ValidationMode::Enforce,
            }
        });
        let aggregate = std::env::var("MOCKFORGE_AGGREGATE_ERRORS")
            .ok()
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(self.options.aggregate_errors);
        // Per-route runtime overrides via JSON env var
        let env_overrides: Option<Map<String, Value>> =
            std::env::var("MOCKFORGE_VALIDATION_OVERRIDES_JSON")
                .ok()
                .and_then(|s| serde_json::from_str::<Value>(&s).ok())
                .and_then(|v| v.as_object().cloned());
        // Response validation is handled in HTTP layer now
        let mut effective_mode = env_mode.unwrap_or(self.options.request_mode.clone());
        // Apply runtime overrides first if present
        if let Some(map) = &env_overrides {
            if let Some(v) = map.get(&format!("{} {}", method, path)) {
                if let Some(m) = v.as_str() {
                    effective_mode = match m {
                        "off" => ValidationMode::Disabled,
                        "warn" => ValidationMode::Warn,
                        _ => ValidationMode::Enforce,
                    };
                }
            }
        }
        // Then static options overrides
        if let Some(override_mode) = self.options.overrides.get(&format!("{} {}", method, path)) {
            effective_mode = override_mode.clone();
        }
        if matches!(effective_mode, ValidationMode::Disabled) {
            return Ok(());
        }
        if let Some(route) = self.get_route(path, method) {
            if matches!(effective_mode, ValidationMode::Disabled) {
                return Ok(());
            }
            let mut errors: Vec<String> = Vec::new();
            let mut details: Vec<Value> = Vec::new();
            // Validate request body if required
            if let Some(schema) = &route.operation.request_body {
                if let Some(value) = body {
                    // First resolve the request body reference if it's a reference
                    let request_body = match schema {
                        openapiv3::ReferenceOr::Item(rb) => Some(rb),
                        openapiv3::ReferenceOr::Reference { reference } => {
                            // Try to resolve request body reference through spec
                            self.spec
                                .spec
                                .components
                                .as_ref()
                                .and_then(|components| {
                                    components.request_bodies.get(
                                        reference.trim_start_matches("#/components/requestBodies/"),
                                    )
                                })
                                .and_then(|rb_ref| rb_ref.as_item())
                        }
                    };

                    if let Some(rb) = request_body {
                        if let Some(content) = rb.content.get("application/json") {
                            if let Some(schema_ref) = &content.schema {
                                // Resolve schema reference and validate
                                match schema_ref {
                                    openapiv3::ReferenceOr::Item(schema) => {
                                        // Direct schema - validate immediately
                                        if let Err(validation_error) =
                                            OpenApiSchema::new(schema.clone()).validate(value)
                                        {
                                            let error_msg = validation_error.to_string();
                                            errors.push(format!(
                                                "body validation failed: {}",
                                                error_msg
                                            ));
                                            if aggregate {
                                                details.push(serde_json::json!({"path":"body","code":"schema_validation","message":error_msg}));
                                            }
                                        }
                                    }
                                    openapiv3::ReferenceOr::Reference { reference } => {
                                        // Referenced schema - resolve and validate
                                        if let Some(resolved_schema_ref) =
                                            self.spec.get_schema(reference)
                                        {
                                            if let Err(validation_error) = OpenApiSchema::new(
                                                resolved_schema_ref.schema.clone(),
                                            )
                                            .validate(value)
                                            {
                                                let error_msg = validation_error.to_string();
                                                errors.push(format!(
                                                    "body validation failed: {}",
                                                    error_msg
                                                ));
                                                if aggregate {
                                                    details.push(serde_json::json!({"path":"body","code":"schema_validation","message":error_msg}));
                                                }
                                            }
                                        } else {
                                            // Schema reference couldn't be resolved
                                            errors.push(format!("body validation failed: could not resolve schema reference {}", reference));
                                            if aggregate {
                                                details.push(serde_json::json!({"path":"body","code":"reference_error","message":"Could not resolve schema reference"}));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        // Request body reference couldn't be resolved or no application/json content
                        errors.push("body validation failed: could not resolve request body or no application/json content".to_string());
                        if aggregate {
                            details.push(serde_json::json!({"path":"body","code":"reference_error","message":"Could not resolve request body reference"}));
                        }
                    }
                } else {
                    errors.push("body: Request body is required but not provided".to_string());
                    details.push(serde_json::json!({"path":"body","code":"required","message":"Request body is required"}));
                }
            } else if body.is_some() {
                // No body expected but provided — not an error by default, but log it
                tracing::debug!("Body provided for operation without requestBody; accepting");
            }

            // Validate path/query parameters
            for p_ref in &route.operation.parameters {
                if let Some(p) = p_ref.as_item() {
                    match p {
                        openapiv3::Parameter::Path { parameter_data, .. } => {
                            validate_parameter(
                                parameter_data,
                                path_params,
                                "path",
                                aggregate,
                                &mut errors,
                                &mut details,
                            );
                        }
                        openapiv3::Parameter::Query {
                            parameter_data,
                            style,
                            ..
                        } => {
                            // For deepObject style, reconstruct nested value from keys like name[prop]
                            // e.g., filter[name]=John&filter[age]=30 -> {"name":"John","age":"30"}
                            let deep_value = if matches!(style, openapiv3::QueryStyle::DeepObject) {
                                let prefix_bracket = format!("{}[", parameter_data.name);
                                let mut obj = serde_json::Map::new();
                                for (key, val) in query_params.iter() {
                                    if let Some(rest) = key.strip_prefix(&prefix_bracket) {
                                        if let Some(prop) = rest.strip_suffix(']') {
                                            obj.insert(prop.to_string(), val.clone());
                                        }
                                    }
                                }
                                if obj.is_empty() {
                                    None
                                } else {
                                    Some(Value::Object(obj))
                                }
                            } else {
                                None
                            };
                            let style_str = match style {
                                openapiv3::QueryStyle::Form => Some("form"),
                                openapiv3::QueryStyle::SpaceDelimited => Some("spaceDelimited"),
                                openapiv3::QueryStyle::PipeDelimited => Some("pipeDelimited"),
                                openapiv3::QueryStyle::DeepObject => Some("deepObject"),
                            };
                            validate_parameter_with_deep_object(
                                parameter_data,
                                query_params,
                                "query",
                                deep_value,
                                style_str,
                                aggregate,
                                &mut errors,
                                &mut details,
                            );
                        }
                        openapiv3::Parameter::Header { parameter_data, .. } => {
                            validate_parameter(
                                parameter_data,
                                header_params,
                                "header",
                                aggregate,
                                &mut errors,
                                &mut details,
                            );
                        }
                        openapiv3::Parameter::Cookie { parameter_data, .. } => {
                            validate_parameter(
                                parameter_data,
                                cookie_params,
                                "cookie",
                                aggregate,
                                &mut errors,
                                &mut details,
                            );
                        }
                    }
                }
            }
            if errors.is_empty() {
                return Ok(());
            }
            match effective_mode {
                ValidationMode::Disabled => Ok(()),
                ValidationMode::Warn => {
                    tracing::warn!("Request validation warnings: {:?}", errors);
                    Ok(())
                }
                ValidationMode::Enforce => Err(Error::validation(
                    serde_json::json!({"errors": errors, "details": details}).to_string(),
                )),
            }
        } else {
            Err(Error::internal(format!("Route {} {} not found in OpenAPI spec", method, path)))
        }
    }

    // Legacy helper removed (mock + status selection happens in handler via route.mock_response_with_status)

    /// Get all paths defined in the spec
    pub fn paths(&self) -> Vec<String> {
        let mut paths: Vec<String> = self.routes.iter().map(|route| route.path.clone()).collect();
        paths.sort();
        paths.dedup();
        paths
    }

    /// Get all HTTP methods supported
    pub fn methods(&self) -> Vec<String> {
        let mut methods: Vec<String> =
            self.routes.iter().map(|route| route.method.clone()).collect();
        methods.sort();
        methods.dedup();
        methods
    }

    /// Get operation details for a route
    pub fn get_operation(&self, path: &str, method: &str) -> Option<OpenApiOperation> {
        self.get_route(path, method).map(|route| {
            OpenApiOperation::from_operation(
                &route.method,
                route.path.clone(),
                &route.operation,
                &self.spec,
            )
        })
    }

    /// Extract path parameters from a request path by matching against known routes
    pub fn extract_path_parameters(&self, path: &str, method: &str) -> HashMap<String, String> {
        for route in &self.routes {
            if route.method != method {
                continue;
            }

            if let Some(params) = self.match_path_to_route(path, &route.path) {
                return params;
            }
        }
        HashMap::new()
    }

    /// Match a request path against a route pattern and extract parameters
    fn match_path_to_route(
        &self,
        request_path: &str,
        route_pattern: &str,
    ) -> Option<HashMap<String, String>> {
        let mut params = HashMap::new();

        // Split both paths into segments
        let request_segments: Vec<&str> = request_path.trim_start_matches('/').split('/').collect();
        let pattern_segments: Vec<&str> =
            route_pattern.trim_start_matches('/').split('/').collect();

        if request_segments.len() != pattern_segments.len() {
            return None;
        }

        for (req_seg, pat_seg) in request_segments.iter().zip(pattern_segments.iter()) {
            if pat_seg.starts_with('{') && pat_seg.ends_with('}') {
                // This is a parameter
                let param_name = &pat_seg[1..pat_seg.len() - 1];
                params.insert(param_name.to_string(), req_seg.to_string());
            } else if req_seg != pat_seg {
                // Static segment doesn't match
                return None;
            }
        }

        Some(params)
    }

    /// Convert OpenAPI path to Axum-compatible path
    /// This is a utility function for converting path parameters from {param} to :param format
    pub fn convert_path_to_axum(openapi_path: &str) -> String {
        // Axum v0.7+ uses {param} format, same as OpenAPI
        openapi_path.to_string()
    }

    /// Build router with AI generator support
    pub fn build_router_with_ai(
        &self,
        ai_generator: Option<Arc<dyn AiGenerator + Send + Sync>>,
    ) -> Router {
        let mut router = Router::new();
        let deduped = self.deduplicated_routes();
        tracing::debug!("Building router with AI support from {} routes", self.routes.len());

        for (axum_path, route) in &deduped {
            tracing::debug!("Adding AI-enabled route: {} {}", route.method, route.path);

            let route_clone = (*route).clone();
            let ai_generator_clone = ai_generator.clone();

            // Create async handler that extracts request data and builds context
            let handler = move |headers: HeaderMap, body: Option<Json<Value>>| {
                let route = route_clone.clone();
                let ai_generator = ai_generator_clone.clone();

                async move {
                    tracing::debug!(
                        "Handling AI request for route: {} {}",
                        route.method,
                        route.path
                    );

                    // Build request context
                    let mut context = RequestContext::new(route.method.clone(), route.path.clone());

                    // Extract headers
                    context.headers = headers
                        .iter()
                        .map(|(k, v)| {
                            (k.to_string(), Value::String(v.to_str().unwrap_or("").to_string()))
                        })
                        .collect();

                    // Extract body if present
                    context.body = body.map(|Json(b)| b);

                    // Generate AI response if AI generator is available and route has AI config
                    let (status, response) = if let (Some(generator), Some(_ai_config)) =
                        (ai_generator, &route.ai_config)
                    {
                        route
                            .mock_response_with_status_async(&context, Some(generator.as_ref()))
                            .await
                    } else {
                        // No AI support, use static response
                        route.mock_response_with_status()
                    };

                    (
                        axum::http::StatusCode::from_u16(status)
                            .unwrap_or(axum::http::StatusCode::OK),
                        Json(response),
                    )
                }
            };

            router = Self::route_for_method(router, axum_path, &route.method, handler);
        }

        router
    }

    /// Build router with MockAI (Behavioral Mock Intelligence) support
    ///
    /// This method integrates MockAI for intelligent, context-aware response generation,
    /// mutation detection, validation error generation, and pagination intelligence.
    ///
    /// # Arguments
    /// * `mockai` - Optional MockAI instance for intelligent behavior
    ///
    /// # Returns
    /// Axum router with MockAI-powered response generation
    pub fn build_router_with_mockai(
        &self,
        mockai: Option<Arc<tokio::sync::RwLock<crate::intelligent_behavior::MockAI>>>,
    ) -> Router {
        use crate::intelligent_behavior::Request as MockAIRequest;

        let mut router = Router::new();
        let deduped = self.deduplicated_routes();
        tracing::debug!("Building router with MockAI support from {} routes", self.routes.len());

        let custom_loader = self.custom_fixture_loader.clone();
        for (axum_path, route) in &deduped {
            tracing::debug!("Adding MockAI-enabled route: {} {}", route.method, route.path);

            let route_clone = (*route).clone();
            let mockai_clone = mockai.clone();
            let custom_loader_clone = custom_loader.clone();

            // Create async handler that processes requests through MockAI
            // Query params are extracted via Query extractor with HashMap
            // Note: Using Query<HashMap<String, String>> wrapped in Option to handle missing query params
            let handler = move |query: axum::extract::Query<HashMap<String, String>>,
                                headers: HeaderMap,
                                body: Option<Json<Value>>| {
                let route = route_clone.clone();
                let mockai = mockai_clone.clone();

                async move {
                    tracing::info!(
                        "[FIXTURE DEBUG] Starting fixture check for {} {} (custom_loader available: {})",
                        route.method,
                        route.path,
                        custom_loader_clone.is_some()
                    );

                    // Check for custom fixture first (highest priority, before MockAI)
                    if let Some(ref loader) = custom_loader_clone {
                        use crate::RequestFingerprint;
                        use axum::http::{Method, Uri};

                        // Build query string from parsed query params
                        let query_string = if query.0.is_empty() {
                            String::new()
                        } else {
                            query
                                .0
                                .iter()
                                .map(|(k, v)| format!("{}={}", k, v))
                                .collect::<Vec<_>>()
                                .join("&")
                        };

                        // Normalize the path to match fixture normalization
                        let normalized_request_path =
                            crate::CustomFixtureLoader::normalize_path(&route.path);

                        tracing::info!(
                            "[FIXTURE DEBUG] Path normalization: original='{}', normalized='{}'",
                            route.path,
                            normalized_request_path
                        );

                        // Create URI for fingerprint
                        let uri_str = if query_string.is_empty() {
                            normalized_request_path.clone()
                        } else {
                            format!("{}?{}", normalized_request_path, query_string)
                        };

                        tracing::info!(
                            "[FIXTURE DEBUG] URI construction: uri_str='{}', query_string='{}'",
                            uri_str,
                            query_string
                        );

                        if let Ok(uri) = uri_str.parse::<Uri>() {
                            let http_method =
                                Method::from_bytes(route.method.as_bytes()).unwrap_or(Method::GET);

                            // Convert body to bytes for fingerprint
                            let body_bytes =
                                body.as_ref().and_then(|Json(b)| serde_json::to_vec(b).ok());
                            let body_slice = body_bytes.as_deref();

                            let fingerprint =
                                RequestFingerprint::new(http_method, &uri, &headers, body_slice);

                            tracing::info!(
                                "[FIXTURE DEBUG] RequestFingerprint created: method='{}', path='{}', query='{}', body_hash={:?}",
                                fingerprint.method,
                                fingerprint.path,
                                fingerprint.query,
                                fingerprint.body_hash
                            );

                            // Check what fixtures are available for this method
                            let available_fixtures = loader.has_fixture(&fingerprint);
                            tracing::info!(
                                "[FIXTURE DEBUG] Fixture check result: has_fixture={}",
                                available_fixtures
                            );

                            if let Some(custom_fixture) = loader.load_fixture(&fingerprint) {
                                tracing::info!(
                                    "[FIXTURE DEBUG] ✅ FIXTURE MATCHED! Using custom fixture for {} {} (status: {}, path: '{}')",
                                    route.method,
                                    route.path,
                                    custom_fixture.status,
                                    custom_fixture.path
                                );

                                // Apply delay if specified
                                if custom_fixture.delay_ms > 0 {
                                    tokio::time::sleep(tokio::time::Duration::from_millis(
                                        custom_fixture.delay_ms,
                                    ))
                                    .await;
                                }

                                // Convert response to JSON string if needed
                                let response_body = if custom_fixture.response.is_string() {
                                    custom_fixture.response.as_str().unwrap().to_string()
                                } else {
                                    serde_json::to_string(&custom_fixture.response)
                                        .unwrap_or_else(|_| "{}".to_string())
                                };

                                // Parse response body as JSON
                                let json_value: Value = serde_json::from_str(&response_body)
                                    .unwrap_or_else(|_| serde_json::json!({}));

                                // Build response with status and JSON body
                                let status =
                                    axum::http::StatusCode::from_u16(custom_fixture.status)
                                        .unwrap_or(axum::http::StatusCode::OK);

                                // Return as tuple (StatusCode, Json) to match handler signature
                                return (status, Json(json_value));
                            } else {
                                tracing::warn!(
                                    "[FIXTURE DEBUG] ❌ No fixture match found for {} {} (fingerprint.path='{}', normalized='{}')",
                                    route.method,
                                    route.path,
                                    fingerprint.path,
                                    normalized_request_path
                                );
                            }
                        } else {
                            tracing::warn!("[FIXTURE DEBUG] Failed to parse URI: '{}'", uri_str);
                        }
                    } else {
                        tracing::warn!(
                            "[FIXTURE DEBUG] Custom fixture loader not available for {} {}",
                            route.method,
                            route.path
                        );
                    }

                    tracing::debug!(
                        "Handling MockAI request for route: {} {}",
                        route.method,
                        route.path
                    );

                    // Query parameters are already parsed by Query extractor
                    let mockai_query = query.0;

                    // If MockAI is enabled, use it to process the request
                    // CRITICAL FIX: Skip MockAI for GET, HEAD, and OPTIONS requests
                    // These are read-only operations and should use OpenAPI response generation
                    // MockAI's mutation analysis incorrectly treats GET requests as "Create" mutations
                    let method_upper = route.method.to_uppercase();
                    let should_use_mockai =
                        matches!(method_upper.as_str(), "POST" | "PUT" | "PATCH" | "DELETE");

                    if should_use_mockai {
                        if let Some(mockai_arc) = mockai {
                            let mockai_guard = mockai_arc.read().await;

                            // Build MockAI request
                            let mut mockai_headers = HashMap::new();
                            for (k, v) in headers.iter() {
                                mockai_headers
                                    .insert(k.to_string(), v.to_str().unwrap_or("").to_string());
                            }

                            let mockai_request = MockAIRequest {
                                method: route.method.clone(),
                                path: route.path.clone(),
                                body: body.as_ref().map(|Json(b)| b.clone()),
                                query_params: mockai_query,
                                headers: mockai_headers,
                            };

                            // Process request through MockAI
                            match mockai_guard.process_request(&mockai_request).await {
                                Ok(mockai_response) => {
                                    // Check if MockAI returned an empty object (signals to use OpenAPI generation)
                                    let is_empty = mockai_response.body.is_object()
                                        && mockai_response
                                            .body
                                            .as_object()
                                            .map(|obj| obj.is_empty())
                                            .unwrap_or(false);

                                    if is_empty {
                                        tracing::debug!(
                                            "MockAI returned empty object for {} {}, falling back to OpenAPI response generation",
                                            route.method,
                                            route.path
                                        );
                                        // Fall through to standard OpenAPI response generation
                                    } else {
                                        // Use the status code from the OpenAPI spec rather than
                                        // MockAI's hardcoded 200, so that e.g. POST returning 201
                                        // is honored correctly.
                                        let spec_status = route.find_first_available_status_code();
                                        tracing::debug!(
                                            "MockAI generated response for {} {}, using spec status: {} (MockAI suggested: {})",
                                            route.method,
                                            route.path,
                                            spec_status,
                                            mockai_response.status_code
                                        );
                                        return (
                                            axum::http::StatusCode::from_u16(spec_status)
                                                .unwrap_or(axum::http::StatusCode::OK),
                                            Json(mockai_response.body),
                                        );
                                    }
                                }
                                Err(e) => {
                                    tracing::warn!(
                                        "MockAI processing failed for {} {}: {}, falling back to standard response",
                                        route.method,
                                        route.path,
                                        e
                                    );
                                    // Fall through to standard response generation
                                }
                            }
                        }
                    } else {
                        tracing::debug!(
                            "Skipping MockAI for {} request {} - using OpenAPI response generation",
                            method_upper,
                            route.path
                        );
                    }

                    // Check for status code override header
                    let status_override = headers
                        .get("X-Mockforge-Response-Status")
                        .and_then(|v| v.to_str().ok())
                        .and_then(|s| s.parse::<u16>().ok());

                    // Check for scenario header
                    let scenario = headers
                        .get("X-Mockforge-Scenario")
                        .and_then(|v| v.to_str().ok())
                        .map(|s| s.to_string())
                        .or_else(|| std::env::var("MOCKFORGE_HTTP_SCENARIO").ok());

                    // Fallback to standard response generation
                    let (status, response) = route
                        .mock_response_with_status_and_scenario_and_override(
                            scenario.as_deref(),
                            status_override,
                        );
                    (
                        axum::http::StatusCode::from_u16(status)
                            .unwrap_or(axum::http::StatusCode::OK),
                        Json(response),
                    )
                }
            };

            router = Self::route_for_method(router, axum_path, &route.method, handler);
        }

        router
    }
}

// Note: templating helpers are now in core::templating (shared across modules)

/// Extract multipart form data from request body bytes
/// Returns (form_fields, file_paths) where file_paths maps field names to stored file paths
async fn extract_multipart_from_bytes(
    body: &axum::body::Bytes,
    headers: &HeaderMap,
) -> Result<(HashMap<String, Value>, HashMap<String, String>)> {
    // Get boundary from Content-Type header
    let boundary = headers
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .and_then(|ct| {
            ct.split(';').find_map(|part| {
                let part = part.trim();
                if part.starts_with("boundary=") {
                    Some(part.strip_prefix("boundary=").unwrap_or("").trim_matches('"'))
                } else {
                    None
                }
            })
        })
        .ok_or_else(|| Error::internal("Missing boundary in Content-Type header"))?;

    let mut fields = HashMap::new();
    let mut files = HashMap::new();

    // Parse multipart data using bytes directly (not string conversion)
    // Multipart format: --boundary\r\n...\r\n--boundary\r\n...\r\n--boundary--\r\n
    let boundary_prefix = format!("--{}", boundary).into_bytes();
    let boundary_line = format!("\r\n--{}\r\n", boundary).into_bytes();
    let end_boundary = format!("\r\n--{}--\r\n", boundary).into_bytes();

    // Find all boundary positions
    let mut pos = 0;
    let mut parts = Vec::new();

    // Skip initial boundary if present
    if body.starts_with(&boundary_prefix) {
        if let Some(first_crlf) = body.iter().position(|&b| b == b'\r') {
            pos = first_crlf + 2; // Skip --boundary\r\n
        }
    }

    // Find all middle boundaries
    while let Some(boundary_pos) = body[pos..]
        .windows(boundary_line.len())
        .position(|window| window == boundary_line.as_slice())
    {
        let actual_pos = pos + boundary_pos;
        if actual_pos > pos {
            parts.push((pos, actual_pos));
        }
        pos = actual_pos + boundary_line.len();
    }

    // Find final boundary
    if let Some(end_pos) = body[pos..]
        .windows(end_boundary.len())
        .position(|window| window == end_boundary.as_slice())
    {
        let actual_end = pos + end_pos;
        if actual_end > pos {
            parts.push((pos, actual_end));
        }
    } else if pos < body.len() {
        // No final boundary found, treat rest as last part
        parts.push((pos, body.len()));
    }

    // Process each part
    for (start, end) in parts {
        let part_data = &body[start..end];

        // Find header/body separator (CRLF CRLF)
        let separator = b"\r\n\r\n";
        if let Some(sep_pos) =
            part_data.windows(separator.len()).position(|window| window == separator)
        {
            let header_bytes = &part_data[..sep_pos];
            let body_start = sep_pos + separator.len();
            let body_data = &part_data[body_start..];

            // Parse headers (assuming UTF-8)
            let header_str = String::from_utf8_lossy(header_bytes);
            let mut field_name = None;
            let mut filename = None;

            for header_line in header_str.lines() {
                if header_line.starts_with("Content-Disposition:") {
                    // Extract field name
                    if let Some(name_start) = header_line.find("name=\"") {
                        let name_start = name_start + 6;
                        if let Some(name_end) = header_line[name_start..].find('"') {
                            field_name =
                                Some(header_line[name_start..name_start + name_end].to_string());
                        }
                    }

                    // Extract filename if present
                    if let Some(file_start) = header_line.find("filename=\"") {
                        let file_start = file_start + 10;
                        if let Some(file_end) = header_line[file_start..].find('"') {
                            filename =
                                Some(header_line[file_start..file_start + file_end].to_string());
                        }
                    }
                }
            }

            if let Some(name) = field_name {
                if let Some(file) = filename {
                    // This is a file upload - store to temp directory
                    let temp_dir = std::env::temp_dir().join("mockforge-uploads");
                    std::fs::create_dir_all(&temp_dir)
                        .map_err(|e| Error::io_with_context("temp directory", e.to_string()))?;

                    let file_path = temp_dir.join(format!("{}_{}", uuid::Uuid::new_v4(), file));
                    std::fs::write(&file_path, body_data)
                        .map_err(|e| Error::io_with_context("file", e.to_string()))?;

                    let file_path_str = file_path.to_string_lossy().to_string();
                    files.insert(name.clone(), file_path_str.clone());
                    fields.insert(name, Value::String(file_path_str));
                } else {
                    // This is a regular form field - try to parse as UTF-8 string
                    // Trim trailing CRLF
                    let body_str = body_data
                        .strip_suffix(b"\r\n")
                        .or_else(|| body_data.strip_suffix(b"\n"))
                        .unwrap_or(body_data);

                    if let Ok(field_value) = String::from_utf8(body_str.to_vec()) {
                        fields.insert(name, Value::String(field_value.trim().to_string()));
                    } else {
                        // Non-UTF-8 field value - store as base64 encoded string
                        use base64::{engine::general_purpose, Engine as _};
                        fields.insert(
                            name,
                            Value::String(general_purpose::STANDARD.encode(body_str)),
                        );
                    }
                }
            }
        }
    }

    Ok((fields, files))
}

static LAST_ERRORS: Lazy<Mutex<VecDeque<Value>>> =
    Lazy::new(|| Mutex::new(VecDeque::with_capacity(20)));

/// Record last validation error for Admin UI inspection
pub fn record_validation_error(v: &Value) {
    if let Ok(mut q) = LAST_ERRORS.lock() {
        if q.len() >= 20 {
            q.pop_front();
        }
        q.push_back(v.clone());
    }
    // If mutex is poisoned, we silently fail - validation errors are informational only
}

/// Get most recent validation error
pub fn get_last_validation_error() -> Option<Value> {
    LAST_ERRORS.lock().ok()?.back().cloned()
}

/// Get recent validation errors (most recent last)
pub fn get_validation_errors() -> Vec<Value> {
    LAST_ERRORS.lock().map(|q| q.iter().cloned().collect()).unwrap_or_default()
}

/// Coerce a parameter `value` into the expected JSON type per `schema` where reasonable.
/// Applies only to param contexts (not request bodies). Conservative conversions:
/// - integer/number: parse from string; arrays: split comma-separated strings and coerce items
/// - boolean: parse true/false (case-insensitive) from string
fn coerce_value_for_schema(value: &Value, schema: &openapiv3::Schema) -> Value {
    // Basic coercion: try to parse strings as appropriate types
    match value {
        Value::String(s) => {
            // Check if schema expects an array and we have a comma-separated string
            if let openapiv3::SchemaKind::Type(openapiv3::Type::Array(array_type)) =
                &schema.schema_kind
            {
                if s.contains(',') {
                    // Split comma-separated string into array
                    let parts: Vec<&str> = s.split(',').map(|s| s.trim()).collect();
                    let mut array_values = Vec::new();

                    for part in parts {
                        // Coerce each part based on array item type
                        if let Some(items_schema) = &array_type.items {
                            if let Some(items_schema_obj) = items_schema.as_item() {
                                let part_value = Value::String(part.to_string());
                                let coerced_part =
                                    coerce_value_for_schema(&part_value, items_schema_obj);
                                array_values.push(coerced_part);
                            } else {
                                // If items schema is a reference or not available, keep as string
                                array_values.push(Value::String(part.to_string()));
                            }
                        } else {
                            // No items schema defined, keep as string
                            array_values.push(Value::String(part.to_string()));
                        }
                    }
                    return Value::Array(array_values);
                }
            }

            // Only coerce if the schema expects a different type
            match &schema.schema_kind {
                openapiv3::SchemaKind::Type(openapiv3::Type::String(_)) => {
                    // Schema expects string, keep as string
                    value.clone()
                }
                openapiv3::SchemaKind::Type(openapiv3::Type::Number(_)) => {
                    // Schema expects number, try to parse
                    if let Ok(n) = s.parse::<f64>() {
                        if let Some(num) = serde_json::Number::from_f64(n) {
                            return Value::Number(num);
                        }
                    }
                    value.clone()
                }
                openapiv3::SchemaKind::Type(openapiv3::Type::Integer(_)) => {
                    // Schema expects integer, try to parse
                    if let Ok(n) = s.parse::<i64>() {
                        if let Some(num) = serde_json::Number::from_f64(n as f64) {
                            return Value::Number(num);
                        }
                    }
                    value.clone()
                }
                openapiv3::SchemaKind::Type(openapiv3::Type::Boolean(_)) => {
                    // Schema expects boolean, try to parse
                    match s.to_lowercase().as_str() {
                        "true" | "1" | "yes" | "on" => Value::Bool(true),
                        "false" | "0" | "no" | "off" => Value::Bool(false),
                        _ => value.clone(),
                    }
                }
                _ => {
                    // Unknown schema type, keep as string
                    value.clone()
                }
            }
        }
        _ => value.clone(),
    }
}

/// Apply style-aware coercion for query params
fn coerce_by_style(value: &Value, schema: &openapiv3::Schema, style: Option<&str>) -> Value {
    // Style-aware coercion for query parameters
    match value {
        Value::String(s) => {
            // Check if schema expects an array and we have a delimited string
            if let openapiv3::SchemaKind::Type(openapiv3::Type::Array(array_type)) =
                &schema.schema_kind
            {
                let delimiter = match style {
                    Some("spaceDelimited") => " ",
                    Some("pipeDelimited") => "|",
                    Some("form") | None => ",", // Default to form style (comma-separated)
                    _ => ",",                   // Fallback to comma
                };

                if s.contains(delimiter) {
                    // Split delimited string into array
                    let parts: Vec<&str> = s.split(delimiter).map(|s| s.trim()).collect();
                    let mut array_values = Vec::new();

                    for part in parts {
                        // Coerce each part based on array item type
                        if let Some(items_schema) = &array_type.items {
                            if let Some(items_schema_obj) = items_schema.as_item() {
                                let part_value = Value::String(part.to_string());
                                let coerced_part =
                                    coerce_by_style(&part_value, items_schema_obj, style);
                                array_values.push(coerced_part);
                            } else {
                                // If items schema is a reference or not available, keep as string
                                array_values.push(Value::String(part.to_string()));
                            }
                        } else {
                            // No items schema defined, keep as string
                            array_values.push(Value::String(part.to_string()));
                        }
                    }
                    return Value::Array(array_values);
                }
            }

            // Try to parse as number first
            if let Ok(n) = s.parse::<f64>() {
                if let Some(num) = serde_json::Number::from_f64(n) {
                    return Value::Number(num);
                }
            }
            // Try to parse as boolean
            match s.to_lowercase().as_str() {
                "true" | "1" | "yes" | "on" => return Value::Bool(true),
                "false" | "0" | "no" | "off" => return Value::Bool(false),
                _ => {}
            }
            // Keep as string
            value.clone()
        }
        _ => value.clone(),
    }
}

/// Build a deepObject from query params like `name[prop]=val`
fn build_deep_object(name: &str, params: &Map<String, Value>) -> Option<Value> {
    let prefix = format!("{}[", name);
    let mut obj = Map::new();
    for (k, v) in params.iter() {
        if let Some(rest) = k.strip_prefix(&prefix) {
            if let Some(key) = rest.strip_suffix(']') {
                obj.insert(key.to_string(), v.clone());
            }
        }
    }
    if obj.is_empty() {
        None
    } else {
        Some(Value::Object(obj))
    }
}

// Import the enhanced schema diff functionality
// use crate::schema_diff::{validation_diff, to_enhanced_422_json, ValidationError}; // Not currently used

/// Generate an enhanced 422 response with detailed schema validation errors
/// This function provides comprehensive error information using the new schema diff utility
#[allow(clippy::too_many_arguments)]
fn generate_enhanced_422_response(
    validator: &OpenApiRouteRegistry,
    path_template: &str,
    method: &str,
    body: Option<&Value>,
    path_params: &Map<String, Value>,
    query_params: &Map<String, Value>,
    header_params: &Map<String, Value>,
    cookie_params: &Map<String, Value>,
) -> Value {
    let mut field_errors = Vec::new();

    // Extract schema validation details if we have a route
    if let Some(route) = validator.get_route(path_template, method) {
        // Validate request body with detailed error collection
        if let Some(schema) = &route.operation.request_body {
            if let Some(value) = body {
                if let Some(content) =
                    schema.as_item().and_then(|rb| rb.content.get("application/json"))
                {
                    if let Some(_schema_ref) = &content.schema {
                        // Basic JSON validation - schema validation deferred
                        if serde_json::from_value::<Value>(value.clone()).is_err() {
                            field_errors.push(json!({
                                "path": "body",
                                "message": "invalid JSON"
                            }));
                        }
                    }
                }
            } else {
                field_errors.push(json!({
                    "path": "body",
                    "expected": "object",
                    "found": "missing",
                    "message": "Request body is required but not provided"
                }));
            }
        }

        // Validate parameters with detailed error collection
        for param_ref in &route.operation.parameters {
            if let Some(param) = param_ref.as_item() {
                match param {
                    openapiv3::Parameter::Path { parameter_data, .. } => {
                        validate_parameter_detailed(
                            parameter_data,
                            path_params,
                            "path",
                            "path parameter",
                            &mut field_errors,
                        );
                    }
                    openapiv3::Parameter::Query { parameter_data, .. } => {
                        let deep_value = if Some("form") == Some("deepObject") {
                            build_deep_object(&parameter_data.name, query_params)
                        } else {
                            None
                        };
                        validate_parameter_detailed_with_deep(
                            parameter_data,
                            query_params,
                            "query",
                            "query parameter",
                            deep_value,
                            &mut field_errors,
                        );
                    }
                    openapiv3::Parameter::Header { parameter_data, .. } => {
                        validate_parameter_detailed(
                            parameter_data,
                            header_params,
                            "header",
                            "header parameter",
                            &mut field_errors,
                        );
                    }
                    openapiv3::Parameter::Cookie { parameter_data, .. } => {
                        validate_parameter_detailed(
                            parameter_data,
                            cookie_params,
                            "cookie",
                            "cookie parameter",
                            &mut field_errors,
                        );
                    }
                }
            }
        }
    }

    // Return the detailed 422 error format
    json!({
        "error": "Schema validation failed",
        "details": field_errors,
        "method": method,
        "path": path_template,
        "timestamp": Utc::now().to_rfc3339(),
        "validation_type": "openapi_schema"
    })
}

/// Helper function to validate a parameter
fn validate_parameter(
    parameter_data: &openapiv3::ParameterData,
    params_map: &Map<String, Value>,
    prefix: &str,
    aggregate: bool,
    errors: &mut Vec<String>,
    details: &mut Vec<Value>,
) {
    match params_map.get(&parameter_data.name) {
        Some(v) => {
            if let ParameterSchemaOrContent::Schema(s) = &parameter_data.format {
                if let Some(schema) = s.as_item() {
                    let coerced = coerce_value_for_schema(v, schema);
                    // Validate the coerced value against the schema
                    if let Err(validation_error) =
                        OpenApiSchema::new(schema.clone()).validate(&coerced)
                    {
                        let error_msg = validation_error.to_string();
                        errors.push(format!(
                            "{} parameter '{}' validation failed: {}",
                            prefix, parameter_data.name, error_msg
                        ));
                        if aggregate {
                            details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"schema_validation","message":error_msg}));
                        }
                    }
                }
            }
        }
        None => {
            if parameter_data.required {
                errors.push(format!(
                    "missing required {} parameter '{}'",
                    prefix, parameter_data.name
                ));
                details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"required","message":"Missing required parameter"}));
            }
        }
    }
}

/// Helper function to validate a parameter with deep object support
#[allow(clippy::too_many_arguments)]
fn validate_parameter_with_deep_object(
    parameter_data: &openapiv3::ParameterData,
    params_map: &Map<String, Value>,
    prefix: &str,
    deep_value: Option<Value>,
    style: Option<&str>,
    aggregate: bool,
    errors: &mut Vec<String>,
    details: &mut Vec<Value>,
) {
    match deep_value.as_ref().or_else(|| params_map.get(&parameter_data.name)) {
        Some(v) => {
            if let ParameterSchemaOrContent::Schema(s) = &parameter_data.format {
                if let Some(schema) = s.as_item() {
                    let coerced = coerce_by_style(v, schema, style); // Use the actual style
                                                                     // Validate the coerced value against the schema
                    if let Err(validation_error) =
                        OpenApiSchema::new(schema.clone()).validate(&coerced)
                    {
                        let error_msg = validation_error.to_string();
                        errors.push(format!(
                            "{} parameter '{}' validation failed: {}",
                            prefix, parameter_data.name, error_msg
                        ));
                        if aggregate {
                            details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"schema_validation","message":error_msg}));
                        }
                    }
                }
            }
        }
        None => {
            if parameter_data.required {
                errors.push(format!(
                    "missing required {} parameter '{}'",
                    prefix, parameter_data.name
                ));
                details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"required","message":"Missing required parameter"}));
            }
        }
    }
}

/// Helper function to validate a parameter with detailed error collection
fn validate_parameter_detailed(
    parameter_data: &openapiv3::ParameterData,
    params_map: &Map<String, Value>,
    location: &str,
    value_type: &str,
    field_errors: &mut Vec<Value>,
) {
    match params_map.get(&parameter_data.name) {
        Some(value) => {
            if let ParameterSchemaOrContent::Schema(schema) = &parameter_data.format {
                // Collect detailed validation errors for this parameter
                let details: Vec<Value> = Vec::new();
                let param_path = format!("{}.{}", location, parameter_data.name);

                // Apply coercion before validation
                if let Some(schema_ref) = schema.as_item() {
                    let coerced_value = coerce_value_for_schema(value, schema_ref);
                    // Validate the coerced value against the schema
                    if let Err(validation_error) =
                        OpenApiSchema::new(schema_ref.clone()).validate(&coerced_value)
                    {
                        field_errors.push(json!({
                            "path": param_path,
                            "expected": "valid according to schema",
                            "found": coerced_value,
                            "message": validation_error.to_string()
                        }));
                    }
                }

                for detail in details {
                    field_errors.push(json!({
                        "path": detail["path"],
                        "expected": detail["expected_type"],
                        "found": detail["value"],
                        "message": detail["message"]
                    }));
                }
            }
        }
        None => {
            if parameter_data.required {
                field_errors.push(json!({
                    "path": format!("{}.{}", location, parameter_data.name),
                    "expected": "value",
                    "found": "missing",
                    "message": format!("Missing required {} '{}'", value_type, parameter_data.name)
                }));
            }
        }
    }
}

/// Helper function to validate a parameter with deep object support and detailed errors
fn validate_parameter_detailed_with_deep(
    parameter_data: &openapiv3::ParameterData,
    params_map: &Map<String, Value>,
    location: &str,
    value_type: &str,
    deep_value: Option<Value>,
    field_errors: &mut Vec<Value>,
) {
    match deep_value.as_ref().or_else(|| params_map.get(&parameter_data.name)) {
        Some(value) => {
            if let ParameterSchemaOrContent::Schema(schema) = &parameter_data.format {
                // Collect detailed validation errors for this parameter
                let details: Vec<Value> = Vec::new();
                let param_path = format!("{}.{}", location, parameter_data.name);

                // Apply coercion before validation
                if let Some(schema_ref) = schema.as_item() {
                    let coerced_value = coerce_by_style(value, schema_ref, Some("form")); // Default to form style for now
                                                                                          // Validate the coerced value against the schema
                    if let Err(validation_error) =
                        OpenApiSchema::new(schema_ref.clone()).validate(&coerced_value)
                    {
                        field_errors.push(json!({
                            "path": param_path,
                            "expected": "valid according to schema",
                            "found": coerced_value,
                            "message": validation_error.to_string()
                        }));
                    }
                }

                for detail in details {
                    field_errors.push(json!({
                        "path": detail["path"],
                        "expected": detail["expected_type"],
                        "found": detail["value"],
                        "message": detail["message"]
                    }));
                }
            }
        }
        None => {
            if parameter_data.required {
                field_errors.push(json!({
                    "path": format!("{}.{}", location, parameter_data.name),
                    "expected": "value",
                    "found": "missing",
                    "message": format!("Missing required {} '{}'", value_type, parameter_data.name)
                }));
            }
        }
    }
}

/// Helper function to create an OpenAPI route registry from a file
pub async fn create_registry_from_file<P: AsRef<std::path::Path>>(
    path: P,
) -> Result<OpenApiRouteRegistry> {
    let spec = OpenApiSpec::from_file(path).await?;
    spec.validate()?;
    Ok(OpenApiRouteRegistry::new(spec))
}

/// Helper function to create an OpenAPI route registry from JSON
pub fn create_registry_from_json(json: Value) -> Result<OpenApiRouteRegistry> {
    let spec = OpenApiSpec::from_json(json)?;
    spec.validate()?;
    Ok(OpenApiRouteRegistry::new(spec))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_registry_creation() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {
                "/users": {
                    "get": {
                        "summary": "Get users",
                        "responses": {
                            "200": {
                                "description": "Success",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "array",
                                            "items": {
                                                "type": "object",
                                                "properties": {
                                                    "id": {"type": "integer"},
                                                    "name": {"type": "string"}
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "post": {
                        "summary": "Create user",
                        "requestBody": {
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "name": {"type": "string"}
                                        },
                                        "required": ["name"]
                                    }
                                }
                            }
                        },
                        "responses": {
                            "201": {
                                "description": "Created",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "properties": {
                                                "id": {"type": "integer"},
                                                "name": {"type": "string"}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                "/users/{id}": {
                    "get": {
                        "summary": "Get user by ID",
                        "parameters": [
                            {
                                "name": "id",
                                "in": "path",
                                "required": true,
                                "schema": {"type": "integer"}
                            }
                        ],
                        "responses": {
                            "200": {
                                "description": "Success",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "properties": {
                                                "id": {"type": "integer"},
                                                "name": {"type": "string"}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });

        let registry = create_registry_from_json(spec_json).unwrap();

        // Test basic properties
        assert_eq!(registry.paths().len(), 2);
        assert!(registry.paths().contains(&"/users".to_string()));
        assert!(registry.paths().contains(&"/users/{id}".to_string()));

        assert_eq!(registry.methods().len(), 2);
        assert!(registry.methods().contains(&"GET".to_string()));
        assert!(registry.methods().contains(&"POST".to_string()));

        // Test route lookup
        let get_users_route = registry.get_route("/users", "GET").unwrap();
        assert_eq!(get_users_route.method, "GET");
        assert_eq!(get_users_route.path, "/users");

        let post_users_route = registry.get_route("/users", "POST").unwrap();
        assert_eq!(post_users_route.method, "POST");
        assert!(post_users_route.operation.request_body.is_some());

        // Test path parameter conversion
        let user_by_id_route = registry.get_route("/users/{id}", "GET").unwrap();
        assert_eq!(user_by_id_route.axum_path(), "/users/{id}");
    }

    #[tokio::test]
    async fn test_validate_request_with_params_and_formats() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Test API", "version": "1.0.0" },
            "paths": {
                "/users/{id}": {
                    "post": {
                        "parameters": [
                            { "name": "id", "in": "path", "required": true, "schema": {"type": "string"} },
                            { "name": "q",  "in": "query", "required": false, "schema": {"type": "integer"} }
                        ],
                        "requestBody": {
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "required": ["email", "website"],
                                        "properties": {
                                            "email":   {"type": "string", "format": "email"},
                                            "website": {"type": "string", "format": "uri"}
                                        }
                                    }
                                }
                            }
                        },
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        });

        let registry = create_registry_from_json(spec_json).unwrap();
        let mut path_params = Map::new();
        path_params.insert("id".to_string(), json!("abc"));
        let mut query_params = Map::new();
        query_params.insert("q".to_string(), json!(123));

        // valid body
        let body = json!({"email":"a@b.co","website":"https://example.com"});
        assert!(registry
            .validate_request_with("/users/{id}", "POST", &path_params, &query_params, Some(&body))
            .is_ok());

        // invalid email
        let bad_email = json!({"email":"not-an-email","website":"https://example.com"});
        assert!(registry
            .validate_request_with(
                "/users/{id}",
                "POST",
                &path_params,
                &query_params,
                Some(&bad_email)
            )
            .is_err());

        // missing required path param
        let empty_path_params = Map::new();
        assert!(registry
            .validate_request_with(
                "/users/{id}",
                "POST",
                &empty_path_params,
                &query_params,
                Some(&body)
            )
            .is_err());
    }

    #[tokio::test]
    async fn test_ref_resolution_for_params_and_body() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Ref API", "version": "1.0.0" },
            "components": {
                "schemas": {
                    "EmailWebsite": {
                        "type": "object",
                        "required": ["email", "website"],
                        "properties": {
                            "email":   {"type": "string", "format": "email"},
                            "website": {"type": "string", "format": "uri"}
                        }
                    }
                },
                "parameters": {
                    "PathId": {"name": "id", "in": "path", "required": true, "schema": {"type": "string"}},
                    "QueryQ": {"name": "q",  "in": "query", "required": false, "schema": {"type": "integer"}}
                },
                "requestBodies": {
                    "CreateUser": {
                        "content": {
                            "application/json": {
                                "schema": {"$ref": "#/components/schemas/EmailWebsite"}
                            }
                        }
                    }
                }
            },
            "paths": {
                "/users/{id}": {
                    "post": {
                        "parameters": [
                            {"$ref": "#/components/parameters/PathId"},
                            {"$ref": "#/components/parameters/QueryQ"}
                        ],
                        "requestBody": {"$ref": "#/components/requestBodies/CreateUser"},
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        });

        let registry = create_registry_from_json(spec_json).unwrap();
        let mut path_params = Map::new();
        path_params.insert("id".to_string(), json!("abc"));
        let mut query_params = Map::new();
        query_params.insert("q".to_string(), json!(7));

        let body = json!({"email":"user@example.com","website":"https://example.com"});
        assert!(registry
            .validate_request_with("/users/{id}", "POST", &path_params, &query_params, Some(&body))
            .is_ok());

        let bad = json!({"email":"nope","website":"https://example.com"});
        assert!(registry
            .validate_request_with("/users/{id}", "POST", &path_params, &query_params, Some(&bad))
            .is_err());
    }

    #[tokio::test]
    async fn test_header_cookie_and_query_coercion() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Params API", "version": "1.0.0" },
            "paths": {
                "/items": {
                    "get": {
                        "parameters": [
                            {"name": "X-Flag", "in": "header", "required": true, "schema": {"type": "boolean"}},
                            {"name": "session", "in": "cookie", "required": true, "schema": {"type": "string"}},
                            {"name": "ids", "in": "query", "required": false, "schema": {"type": "array", "items": {"type": "integer"}}}
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        });

        let registry = create_registry_from_json(spec_json).unwrap();

        let path_params = Map::new();
        let mut query_params = Map::new();
        // comma-separated string for array should coerce
        query_params.insert("ids".to_string(), json!("1,2,3"));
        let mut header_params = Map::new();
        header_params.insert("X-Flag".to_string(), json!("true"));
        let mut cookie_params = Map::new();
        cookie_params.insert("session".to_string(), json!("abc123"));

        assert!(registry
            .validate_request_with_all(
                "/items",
                "GET",
                &path_params,
                &query_params,
                &header_params,
                &cookie_params,
                None
            )
            .is_ok());

        // Missing required cookie
        let empty_cookie = Map::new();
        assert!(registry
            .validate_request_with_all(
                "/items",
                "GET",
                &path_params,
                &query_params,
                &header_params,
                &empty_cookie,
                None
            )
            .is_err());

        // Bad boolean header value (cannot coerce)
        let mut bad_header = Map::new();
        bad_header.insert("X-Flag".to_string(), json!("notabool"));
        assert!(registry
            .validate_request_with_all(
                "/items",
                "GET",
                &path_params,
                &query_params,
                &bad_header,
                &cookie_params,
                None
            )
            .is_err());
    }

    #[tokio::test]
    async fn test_query_styles_space_pipe_deepobject() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Query Styles API", "version": "1.0.0" },
            "paths": {"/search": {"get": {
                "parameters": [
                    {"name":"tags","in":"query","style":"spaceDelimited","schema":{"type":"array","items":{"type":"string"}}},
                    {"name":"ids","in":"query","style":"pipeDelimited","schema":{"type":"array","items":{"type":"integer"}}},
                    {"name":"filter","in":"query","style":"deepObject","schema":{"type":"object","properties":{"color":{"type":"string"}},"required":["color"]}}
                ],
                "responses": {"200": {"description":"ok"}}
            }} }
        });

        let registry = create_registry_from_json(spec_json).unwrap();

        let path_params = Map::new();
        let mut query = Map::new();
        query.insert("tags".into(), json!("alpha beta gamma"));
        query.insert("ids".into(), json!("1|2|3"));
        query.insert("filter[color]".into(), json!("red"));

        assert!(registry
            .validate_request_with("/search", "GET", &path_params, &query, None)
            .is_ok());
    }

    #[tokio::test]
    async fn test_oneof_anyof_allof_validation() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Composite API", "version": "1.0.0" },
            "paths": {
                "/composite": {
                    "post": {
                        "requestBody": {
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"type": "object", "required": ["base"], "properties": {"base": {"type": "string"}}}
                                        ],
                                        "oneOf": [
                                            {"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"], "not": {"required": ["b"]}},
                                            {"type": "object", "properties": {"b": {"type": "integer"}}, "required": ["b"], "not": {"required": ["a"]}}
                                        ],
                                        "anyOf": [
                                            {"type": "object", "properties": {"flag": {"type": "boolean"}}, "required": ["flag"]},
                                            {"type": "object", "properties": {"extra": {"type": "string"}}, "required": ["extra"]}
                                        ]
                                    }
                                }
                            }
                        },
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        });

        let registry = create_registry_from_json(spec_json).unwrap();
        // valid: satisfies base via allOf, exactly one of a/b, and at least one of flag/extra
        let ok = json!({"base": "x", "a": 1, "flag": true});
        assert!(registry
            .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&ok))
            .is_ok());

        // invalid oneOf: both a and b present
        let bad_oneof = json!({"base": "x", "a": 1, "b": 2, "flag": false});
        assert!(registry
            .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&bad_oneof))
            .is_err());

        // invalid anyOf: none of flag/extra present
        let bad_anyof = json!({"base": "x", "a": 1});
        assert!(registry
            .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&bad_anyof))
            .is_err());

        // invalid allOf: missing base
        let bad_allof = json!({"a": 1, "flag": true});
        assert!(registry
            .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&bad_allof))
            .is_err());
    }

    #[tokio::test]
    async fn test_overrides_warn_mode_allows_invalid() {
        // Spec with a POST route expecting an integer query param
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Overrides API", "version": "1.0.0" },
            "paths": {"/things": {"post": {
                "parameters": [{"name":"q","in":"query","required":true,"schema":{"type":"integer"}}],
                "responses": {"200": {"description":"ok"}}
            }}}
        });

        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let mut overrides = HashMap::new();
        overrides.insert("POST /things".to_string(), ValidationMode::Warn);
        let registry = OpenApiRouteRegistry::new_with_options(
            spec,
            ValidationOptions {
                request_mode: ValidationMode::Enforce,
                aggregate_errors: true,
                validate_responses: false,
                overrides,
                admin_skip_prefixes: vec![],
                response_template_expand: false,
                validation_status: None,
            },
        );

        // Invalid q (missing) should warn, not error
        let ok = registry.validate_request_with("/things", "POST", &Map::new(), &Map::new(), None);
        assert!(ok.is_ok());
    }

    #[tokio::test]
    async fn test_admin_skip_prefix_short_circuit() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Skip API", "version": "1.0.0" },
            "paths": {}
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new_with_options(
            spec,
            ValidationOptions {
                request_mode: ValidationMode::Enforce,
                aggregate_errors: true,
                validate_responses: false,
                overrides: HashMap::new(),
                admin_skip_prefixes: vec!["/admin".into()],
                response_template_expand: false,
                validation_status: None,
            },
        );

        // No route exists for this, but skip prefix means it is accepted
        let res = registry.validate_request_with_all(
            "/admin/__mockforge/health",
            "GET",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None,
        );
        assert!(res.is_ok());
    }

    #[test]
    fn test_path_conversion() {
        assert_eq!(OpenApiRouteRegistry::convert_path_to_axum("/users"), "/users");
        assert_eq!(OpenApiRouteRegistry::convert_path_to_axum("/users/{id}"), "/users/{id}");
        assert_eq!(
            OpenApiRouteRegistry::convert_path_to_axum("/users/{id}/posts/{postId}"),
            "/users/{id}/posts/{postId}"
        );
    }

    #[test]
    fn test_validation_options_default() {
        let options = ValidationOptions::default();
        assert!(matches!(options.request_mode, ValidationMode::Enforce));
        assert!(options.aggregate_errors);
        assert!(!options.validate_responses);
        assert!(options.overrides.is_empty());
        assert!(options.admin_skip_prefixes.is_empty());
        assert!(!options.response_template_expand);
        assert!(options.validation_status.is_none());
    }

    #[test]
    fn test_validation_mode_variants() {
        // Test that all variants can be created and compared
        let disabled = ValidationMode::Disabled;
        let warn = ValidationMode::Warn;
        let enforce = ValidationMode::Enforce;
        let default = ValidationMode::default();

        // Test that default is Warn
        assert!(matches!(default, ValidationMode::Warn));

        // Test that variants are distinct
        assert!(!matches!(disabled, ValidationMode::Warn));
        assert!(!matches!(warn, ValidationMode::Enforce));
        assert!(!matches!(enforce, ValidationMode::Disabled));
    }

    #[test]
    fn test_registry_spec_accessor() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {}
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec.clone());

        // Test spec() accessor
        let accessed_spec = registry.spec();
        assert_eq!(accessed_spec.title(), "Test API");
    }

    #[test]
    fn test_clone_for_validation() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {
                "/users": {
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Success"
                            }
                        }
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Test clone_for_validation
        let cloned = registry.clone_for_validation();
        assert_eq!(cloned.routes().len(), registry.routes().len());
        assert_eq!(cloned.spec().title(), registry.spec().title());
    }

    #[test]
    fn test_with_custom_fixture_loader() {
        let temp_dir = TempDir::new().unwrap();
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {}
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);
        let original_routes_len = registry.routes().len();

        // Test with_custom_fixture_loader
        let custom_loader =
            Arc::new(crate::CustomFixtureLoader::new(temp_dir.path().to_path_buf(), true));
        let registry_with_loader = registry.with_custom_fixture_loader(custom_loader);

        // Verify the loader was set (we can't directly access it, but we can test it doesn't panic)
        assert_eq!(registry_with_loader.routes().len(), original_routes_len);
    }

    #[test]
    fn test_get_route() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {
                "/users": {
                    "get": {
                        "operationId": "getUsers",
                        "responses": {
                            "200": {
                                "description": "Success"
                            }
                        }
                    },
                    "post": {
                        "operationId": "createUser",
                        "responses": {
                            "201": {
                                "description": "Created"
                            }
                        }
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Test get_route for existing route
        let route = registry.get_route("/users", "GET");
        assert!(route.is_some());
        assert_eq!(route.unwrap().method, "GET");
        assert_eq!(route.unwrap().path, "/users");

        // Test get_route for non-existent route
        let route = registry.get_route("/nonexistent", "GET");
        assert!(route.is_none());

        // Test get_route for different method
        let route = registry.get_route("/users", "POST");
        assert!(route.is_some());
        assert_eq!(route.unwrap().method, "POST");
    }

    #[test]
    fn test_get_routes_for_path() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {
                "/users": {
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Success"
                            }
                        }
                    },
                    "post": {
                        "responses": {
                            "201": {
                                "description": "Created"
                            }
                        }
                    },
                    "put": {
                        "responses": {
                            "200": {
                                "description": "Success"
                            }
                        }
                    }
                },
                "/posts": {
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Success"
                            }
                        }
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Test get_routes_for_path with multiple methods
        let routes = registry.get_routes_for_path("/users");
        assert_eq!(routes.len(), 3);
        let methods: Vec<&str> = routes.iter().map(|r| r.method.as_str()).collect();
        assert!(methods.contains(&"GET"));
        assert!(methods.contains(&"POST"));
        assert!(methods.contains(&"PUT"));

        // Test get_routes_for_path with single method
        let routes = registry.get_routes_for_path("/posts");
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0].method, "GET");

        // Test get_routes_for_path with non-existent path
        let routes = registry.get_routes_for_path("/nonexistent");
        assert!(routes.is_empty());
    }

    #[test]
    fn test_new_vs_new_with_options() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {}
        });
        let spec1 = OpenApiSpec::from_json(spec_json.clone()).unwrap();
        let spec2 = OpenApiSpec::from_json(spec_json).unwrap();

        // Test new() - uses environment-based options
        let registry1 = OpenApiRouteRegistry::new(spec1);
        assert_eq!(registry1.spec().title(), "Test API");

        // Test new_with_options() - uses explicit options
        let options = ValidationOptions {
            request_mode: ValidationMode::Disabled,
            aggregate_errors: false,
            validate_responses: true,
            overrides: HashMap::new(),
            admin_skip_prefixes: vec!["/admin".to_string()],
            response_template_expand: true,
            validation_status: Some(422),
        };
        let registry2 = OpenApiRouteRegistry::new_with_options(spec2, options);
        assert_eq!(registry2.spec().title(), "Test API");
    }

    #[test]
    fn test_new_with_env_vs_new() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            },
            "paths": {}
        });
        let spec1 = OpenApiSpec::from_json(spec_json.clone()).unwrap();
        let spec2 = OpenApiSpec::from_json(spec_json).unwrap();

        // Test new() calls new_with_env()
        let registry1 = OpenApiRouteRegistry::new(spec1);

        // Test new_with_env() directly
        let registry2 = OpenApiRouteRegistry::new_with_env(spec2);

        // Both should create valid registries
        assert_eq!(registry1.spec().title(), "Test API");
        assert_eq!(registry2.spec().title(), "Test API");
    }

    #[test]
    fn test_validation_options_custom() {
        let options = ValidationOptions {
            request_mode: ValidationMode::Warn,
            aggregate_errors: false,
            validate_responses: true,
            overrides: {
                let mut map = HashMap::new();
                map.insert("getUsers".to_string(), ValidationMode::Disabled);
                map
            },
            admin_skip_prefixes: vec!["/admin".to_string(), "/internal".to_string()],
            response_template_expand: true,
            validation_status: Some(422),
        };

        assert!(matches!(options.request_mode, ValidationMode::Warn));
        assert!(!options.aggregate_errors);
        assert!(options.validate_responses);
        assert_eq!(options.overrides.len(), 1);
        assert_eq!(options.admin_skip_prefixes.len(), 2);
        assert!(options.response_template_expand);
        assert_eq!(options.validation_status, Some(422));
    }

    #[test]
    fn test_validation_mode_default_standalone() {
        let mode = ValidationMode::default();
        assert!(matches!(mode, ValidationMode::Warn));
    }

    #[test]
    fn test_validation_mode_clone() {
        let mode1 = ValidationMode::Enforce;
        let mode2 = mode1.clone();
        assert!(matches!(mode1, ValidationMode::Enforce));
        assert!(matches!(mode2, ValidationMode::Enforce));
    }

    #[test]
    fn test_validation_mode_debug() {
        let mode = ValidationMode::Disabled;
        let debug_str = format!("{:?}", mode);
        assert!(debug_str.contains("Disabled") || debug_str.contains("ValidationMode"));
    }

    #[test]
    fn test_validation_options_clone() {
        let options1 = ValidationOptions {
            request_mode: ValidationMode::Warn,
            aggregate_errors: true,
            validate_responses: false,
            overrides: HashMap::new(),
            admin_skip_prefixes: vec![],
            response_template_expand: false,
            validation_status: None,
        };
        let options2 = options1.clone();
        assert!(matches!(options2.request_mode, ValidationMode::Warn));
        assert_eq!(options1.aggregate_errors, options2.aggregate_errors);
    }

    #[test]
    fn test_validation_options_debug() {
        let options = ValidationOptions::default();
        let debug_str = format!("{:?}", options);
        assert!(debug_str.contains("ValidationOptions"));
    }

    #[test]
    fn test_validation_options_with_all_fields() {
        let mut overrides = HashMap::new();
        overrides.insert("op1".to_string(), ValidationMode::Disabled);
        overrides.insert("op2".to_string(), ValidationMode::Warn);

        let options = ValidationOptions {
            request_mode: ValidationMode::Enforce,
            aggregate_errors: false,
            validate_responses: true,
            overrides: overrides.clone(),
            admin_skip_prefixes: vec!["/admin".to_string(), "/internal".to_string()],
            response_template_expand: true,
            validation_status: Some(422),
        };

        assert!(matches!(options.request_mode, ValidationMode::Enforce));
        assert!(!options.aggregate_errors);
        assert!(options.validate_responses);
        assert_eq!(options.overrides.len(), 2);
        assert_eq!(options.admin_skip_prefixes.len(), 2);
        assert!(options.response_template_expand);
        assert_eq!(options.validation_status, Some(422));
    }

    #[test]
    fn test_openapi_route_registry_clone() {
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": { "title": "Test API", "version": "1.0.0" },
            "paths": {}
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry1 = OpenApiRouteRegistry::new(spec);
        let registry2 = registry1.clone();
        assert_eq!(registry1.spec().title(), registry2.spec().title());
    }

    #[test]
    fn test_validation_mode_serialization() {
        let mode = ValidationMode::Enforce;
        let json = serde_json::to_string(&mode).unwrap();
        assert!(json.contains("Enforce") || json.contains("enforce"));
    }

    #[test]
    fn test_validation_mode_deserialization() {
        let json = r#""Disabled""#;
        let mode: ValidationMode = serde_json::from_str(json).unwrap();
        assert!(matches!(mode, ValidationMode::Disabled));
    }

    #[test]
    fn test_validation_options_default_values() {
        let options = ValidationOptions::default();
        assert!(matches!(options.request_mode, ValidationMode::Enforce));
        assert!(options.aggregate_errors);
        assert!(!options.validate_responses);
        assert!(options.overrides.is_empty());
        assert!(options.admin_skip_prefixes.is_empty());
        assert!(!options.response_template_expand);
        assert_eq!(options.validation_status, None);
    }

    #[test]
    fn test_validation_mode_all_variants() {
        let disabled = ValidationMode::Disabled;
        let warn = ValidationMode::Warn;
        let enforce = ValidationMode::Enforce;

        assert!(matches!(disabled, ValidationMode::Disabled));
        assert!(matches!(warn, ValidationMode::Warn));
        assert!(matches!(enforce, ValidationMode::Enforce));
    }

    #[test]
    fn test_validation_options_with_overrides() {
        let mut overrides = HashMap::new();
        overrides.insert("operation1".to_string(), ValidationMode::Disabled);
        overrides.insert("operation2".to_string(), ValidationMode::Warn);

        let options = ValidationOptions {
            request_mode: ValidationMode::Enforce,
            aggregate_errors: true,
            validate_responses: false,
            overrides,
            admin_skip_prefixes: vec![],
            response_template_expand: false,
            validation_status: None,
        };

        assert_eq!(options.overrides.len(), 2);
        assert!(matches!(options.overrides.get("operation1"), Some(ValidationMode::Disabled)));
        assert!(matches!(options.overrides.get("operation2"), Some(ValidationMode::Warn)));
    }

    #[test]
    fn test_validation_options_with_admin_skip_prefixes() {
        let options = ValidationOptions {
            request_mode: ValidationMode::Enforce,
            aggregate_errors: true,
            validate_responses: false,
            overrides: HashMap::new(),
            admin_skip_prefixes: vec![
                "/admin".to_string(),
                "/internal".to_string(),
                "/debug".to_string(),
            ],
            response_template_expand: false,
            validation_status: None,
        };

        assert_eq!(options.admin_skip_prefixes.len(), 3);
        assert!(options.admin_skip_prefixes.contains(&"/admin".to_string()));
        assert!(options.admin_skip_prefixes.contains(&"/internal".to_string()));
        assert!(options.admin_skip_prefixes.contains(&"/debug".to_string()));
    }

    #[test]
    fn test_validation_options_with_validation_status() {
        let options1 = ValidationOptions {
            request_mode: ValidationMode::Enforce,
            aggregate_errors: true,
            validate_responses: false,
            overrides: HashMap::new(),
            admin_skip_prefixes: vec![],
            response_template_expand: false,
            validation_status: Some(400),
        };

        let options2 = ValidationOptions {
            request_mode: ValidationMode::Enforce,
            aggregate_errors: true,
            validate_responses: false,
            overrides: HashMap::new(),
            admin_skip_prefixes: vec![],
            response_template_expand: false,
            validation_status: Some(422),
        };

        assert_eq!(options1.validation_status, Some(400));
        assert_eq!(options2.validation_status, Some(422));
    }

    #[test]
    fn test_validate_request_with_disabled_mode() {
        // Test validation with disabled mode (lines 1001-1007)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let options = ValidationOptions {
            request_mode: ValidationMode::Disabled,
            ..Default::default()
        };
        let registry = OpenApiRouteRegistry::new_with_options(spec, options);

        // Should pass validation when disabled (lines 1002-1003, 1005-1007)
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_request_with_warn_mode() {
        // Test validation with warn mode (lines 1162-1166)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "post": {
                        "requestBody": {
                            "required": true,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "required": ["name"],
                                        "properties": {
                                            "name": {"type": "string"}
                                        }
                                    }
                                }
                            }
                        },
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let options = ValidationOptions {
            request_mode: ValidationMode::Warn,
            ..Default::default()
        };
        let registry = OpenApiRouteRegistry::new_with_options(spec, options);

        // Should pass with warnings when body is missing (lines 1162-1166)
        let result = registry.validate_request_with_all(
            "/users",
            "POST",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None, // Missing required body
        );
        assert!(result.is_ok()); // Warn mode doesn't fail
    }

    #[test]
    fn test_validate_request_body_validation_error() {
        // Test request body validation error path (lines 1072-1091)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "post": {
                        "requestBody": {
                            "required": true,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "required": ["name"],
                                        "properties": {
                                            "name": {"type": "string"}
                                        }
                                    }
                                }
                            }
                        },
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should fail validation when body is missing (lines 1088-1091)
        let result = registry.validate_request_with_all(
            "/users",
            "POST",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None, // Missing required body
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_request_body_schema_validation_error() {
        // Test request body schema validation error (lines 1038-1049)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "post": {
                        "requestBody": {
                            "required": true,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "required": ["name"],
                                        "properties": {
                                            "name": {"type": "string"}
                                        }
                                    }
                                }
                            }
                        },
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should fail validation when body doesn't match schema (lines 1038-1049)
        let invalid_body = json!({}); // Missing required "name" field
        let result = registry.validate_request_with_all(
            "/users",
            "POST",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            Some(&invalid_body),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_request_body_referenced_schema_error() {
        // Test request body with referenced schema that can't be resolved (lines 1070-1076)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "post": {
                        "requestBody": {
                            "required": true,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/NonExistentSchema"
                                    }
                                }
                            }
                        },
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            },
            "components": {}
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should fail validation when schema reference can't be resolved (lines 1070-1076)
        let body = json!({"name": "test"});
        let result = registry.validate_request_with_all(
            "/users",
            "POST",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            Some(&body),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_request_body_referenced_request_body_error() {
        // Test request body with referenced request body that can't be resolved (lines 1081-1087)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "post": {
                        "requestBody": {
                            "$ref": "#/components/requestBodies/NonExistentRequestBody"
                        },
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            },
            "components": {}
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should fail validation when request body reference can't be resolved (lines 1081-1087)
        let body = json!({"name": "test"});
        let result = registry.validate_request_with_all(
            "/users",
            "POST",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            Some(&body),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_request_body_provided_when_not_expected() {
        // Test body provided when not expected (lines 1092-1094)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should accept body even when not expected (lines 1092-1094)
        let body = json!({"extra": "data"});
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            Some(&body),
        );
        // Should not error - just logs debug message
        assert!(result.is_ok());
    }

    #[test]
    fn test_get_operation() {
        // Test get_operation method (lines 1196-1205)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "operationId": "getUsers",
                        "summary": "Get users",
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should return operation details (lines 1196-1205)
        let operation = registry.get_operation("/users", "GET");
        assert!(operation.is_some());
        assert_eq!(operation.unwrap().method, "GET");

        // Should return None for non-existent route
        assert!(registry.get_operation("/nonexistent", "GET").is_none());
    }

    #[test]
    fn test_extract_path_parameters() {
        // Test extract_path_parameters method (lines 1208-1223)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users/{id}": {
                    "get": {
                        "parameters": [
                            {
                                "name": "id",
                                "in": "path",
                                "required": true,
                                "schema": {"type": "string"}
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should extract path parameters (lines 1208-1223)
        let params = registry.extract_path_parameters("/users/123", "GET");
        assert_eq!(params.get("id"), Some(&"123".to_string()));

        // Should return empty map for non-matching path
        let empty_params = registry.extract_path_parameters("/users", "GET");
        assert!(empty_params.is_empty());
    }

    #[test]
    fn test_extract_path_parameters_multiple_params() {
        // Test extract_path_parameters with multiple path parameters
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users/{userId}/posts/{postId}": {
                    "get": {
                        "parameters": [
                            {
                                "name": "userId",
                                "in": "path",
                                "required": true,
                                "schema": {"type": "string"}
                            },
                            {
                                "name": "postId",
                                "in": "path",
                                "required": true,
                                "schema": {"type": "string"}
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should extract multiple path parameters
        let params = registry.extract_path_parameters("/users/123/posts/456", "GET");
        assert_eq!(params.get("userId"), Some(&"123".to_string()));
        assert_eq!(params.get("postId"), Some(&"456".to_string()));
    }

    #[test]
    fn test_validate_request_route_not_found() {
        // Test validation when route not found (lines 1171-1173)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should return error when route not found (lines 1171-1173)
        let result = registry.validate_request_with_all(
            "/nonexistent",
            "GET",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_validate_request_with_path_parameters() {
        // Test path parameter validation (lines 1101-1110)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users/{id}": {
                    "get": {
                        "parameters": [
                            {
                                "name": "id",
                                "in": "path",
                                "required": true,
                                "schema": {"type": "string", "minLength": 1}
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should pass validation with valid path parameter
        let mut path_params = Map::new();
        path_params.insert("id".to_string(), json!("123"));
        let result = registry.validate_request_with_all(
            "/users/{id}",
            "GET",
            &path_params,
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_request_with_query_parameters() {
        // Test query parameter validation (lines 1111-1134)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "parameters": [
                            {
                                "name": "page",
                                "in": "query",
                                "required": true,
                                "schema": {"type": "integer", "minimum": 1}
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should pass validation with valid query parameter
        let mut query_params = Map::new();
        query_params.insert("page".to_string(), json!(1));
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &query_params,
            &Map::new(),
            &Map::new(),
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_request_with_header_parameters() {
        // Test header parameter validation (lines 1135-1144)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "parameters": [
                            {
                                "name": "X-API-Key",
                                "in": "header",
                                "required": true,
                                "schema": {"type": "string"}
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should pass validation with valid header parameter
        let mut header_params = Map::new();
        header_params.insert("X-API-Key".to_string(), json!("secret-key"));
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &Map::new(),
            &header_params,
            &Map::new(),
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_request_with_cookie_parameters() {
        // Test cookie parameter validation (lines 1145-1154)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "parameters": [
                            {
                                "name": "sessionId",
                                "in": "cookie",
                                "required": true,
                                "schema": {"type": "string"}
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should pass validation with valid cookie parameter
        let mut cookie_params = Map::new();
        cookie_params.insert("sessionId".to_string(), json!("abc123"));
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &cookie_params,
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_request_no_errors_early_return() {
        // Test early return when no errors (lines 1158-1160)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should return early when no errors (lines 1158-1160)
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &Map::new(),
            &Map::new(),
            &Map::new(),
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_request_query_parameter_different_styles() {
        // Test query parameter validation with different styles (lines 1118-1123)
        let spec_json = json!({
            "openapi": "3.0.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "parameters": [
                            {
                                "name": "tags",
                                "in": "query",
                                "style": "pipeDelimited",
                                "schema": {
                                    "type": "array",
                                    "items": {"type": "string"}
                                }
                            }
                        ],
                        "responses": {"200": {"description": "OK"}}
                    }
                }
            }
        });
        let spec = OpenApiSpec::from_json(spec_json).unwrap();
        let registry = OpenApiRouteRegistry::new(spec);

        // Should handle pipeDelimited style (lines 1118-1123)
        let mut query_params = Map::new();
        query_params.insert("tags".to_string(), json!(["tag1", "tag2"]));
        let result = registry.validate_request_with_all(
            "/users",
            "GET",
            &Map::new(),
            &query_params,
            &Map::new(),
            &Map::new(),
            None,
        );
        // Should not error on style handling
        assert!(result.is_ok() || result.is_err()); // Either is fine, just testing the path
    }
}