llmposter 0.4.8

Drop-in mock server for OpenAI, Anthropic & Gemini APIs — library or standalone CLI. SSE streaming, tool calling, OAuth2, failure injection, streaming chaos, stateful scenarios, request capture, hot-reload, response templating. Test LLM apps without burning tokens.
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
use std::collections::HashMap;
use std::path::Path;

use serde::Deserialize;

/// How to match a string field — substring (default) or regex.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum StringMatch {
    /// Plain substring match (case-sensitive).
    Substring(String),
    /// Regex match using `{ regex: "pattern" }` YAML syntax.
    Regex(RegexMatch),
}

/// Wrapper for `{ regex: "pattern" }` syntax in YAML.
/// After validation, `compiled` holds the pre-compiled regex for efficient linear-time matching.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RegexMatch {
    /// The regex pattern string from the YAML fixture.
    pub regex: String,
    #[serde(skip)]
    compiled: Option<regex::Regex>,
}

impl PartialEq for RegexMatch {
    fn eq(&self, other: &Self) -> bool {
        self.regex == other.regex
    }
}

impl RegexMatch {
    fn compile(&mut self) -> Result<(), String> {
        if self.compiled.is_some() {
            return Ok(()); // Already compiled, skip
        }
        let re = regex::RegexBuilder::new(&self.regex)
            .size_limit(1 << 20)
            .dfa_size_limit(1 << 20) // Cap both compiled NFA and per-thread DFA cache
            .build()
            .map_err(|e| format!("Invalid regex '{}': {}", self.regex, e))?;
        self.compiled = Some(re);
        Ok(())
    }

    fn is_match(&self, haystack: &str) -> bool {
        match &self.compiled {
            Some(re) => re.is_match(haystack),
            None => {
                // Fallback: compile on the fly. This path is only hit if
                // validate() was not called (programmatic fixtures added
                // without going through ServerBuilder::build).
                match regex::RegexBuilder::new(&self.regex)
                    .size_limit(1 << 20)
                    .dfa_size_limit(1 << 20)
                    .build()
                {
                    Ok(re) => re.is_match(haystack),
                    Err(e) => {
                        eprintln!("[llmposter] Warning: invalid regex '{}': {}", self.regex, e);
                        false
                    }
                }
            }
        }
    }
}

impl StringMatch {
    /// Create a regex `StringMatch` from a pattern string.
    pub fn regex(pattern: &str) -> Self {
        StringMatch::Regex(RegexMatch {
            regex: pattern.to_string(),
            compiled: None,
        })
    }
}

/// Numeric range match for `temperature` and similar floats.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct F64Range {
    /// Inclusive lower bound. `None` = no lower bound.
    #[serde(default)]
    pub min: Option<f64>,
    /// Inclusive upper bound. `None` = no upper bound.
    #[serde(default)]
    pub max: Option<f64>,
}

/// Exact value OR range match for `temperature` etc.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum F64Match {
    /// Exact equality match against the request's `temperature`.
    /// Both sides round-trip cleanly from YAML/JSON literals, so
    /// plain `f64` equality is used. Reach for [`F64Match::Range`]
    /// if you need tolerance-based matching.
    Exact(f64),
    /// Inclusive range match.
    Range(F64Range),
}

/// Match criteria for a fixture.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct FixtureMatch {
    /// Match by substring or regex in the last user message.
    pub user_message: Option<StringMatch>,
    /// Match by model name (substring or regex).
    pub model: Option<StringMatch>,
    /// Match on request headers (lowercase names). Each entry must
    /// match for the fixture to apply. Values support substring /
    /// regex via `StringMatch`.
    #[serde(default)]
    pub headers: std::collections::HashMap<String, StringMatch>,
    /// Match on the system prompt text. OpenAI: any `messages[*]`
    /// with `role == "system"`. Anthropic: top-level `system`
    /// string OR array-of-text. Gemini: `systemInstruction.parts[*].text`.
    /// Responses: `input[*]` with `role == "system"`.
    pub system_prompt: Option<StringMatch>,
    /// Match on `body.temperature` — exact value or inclusive range.
    pub temperature: Option<F64Match>,
    /// Match on top-level request metadata (OpenAI + Responses API).
    /// Each entry must match for the fixture to apply.
    #[serde(default)]
    pub metadata: std::collections::HashMap<String, StringMatch>,
    /// Match on any declared tool name in the request (`tools[*]`).
    /// Works across all four providers.
    pub tool_schema: Option<StringMatch>,
    /// Arbitrary JSONPath expression evaluated against the full
    /// parsed request body. The fixture matches when the query
    /// returns at least one non-null value. Requires the `jsonpath`
    /// Cargo feature (on by default). The field itself is always
    /// present so serde gives a clear validation error instead of
    /// a confusing "unknown field" message when the feature is off.
    pub body_jsonpath: Option<String>,
    /// Pre-compiled form of `body_jsonpath`. Populated by `validate()`
    /// at load time so the hot path evaluates against a parsed
    /// `JpQuery` instead of re-parsing the source string on every
    /// request (mirrors `RegexMatch::compiled`).
    #[cfg(feature = "jsonpath")]
    #[serde(skip)]
    body_jsonpath_compiled: Option<jsonpath_rust::parser::model::JpQuery>,
}

/// A tool call in a fixture response.
///
/// The `arguments` field must be a JSON object (validated at load time).
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolCall {
    /// Function name (e.g., `"get_weather"`).
    pub name: String,
    /// Function arguments as a JSON object.
    pub arguments: serde_json::Value,
}

/// Opaque compile cache for a fixture's minijinja template.
///
/// Populated on first render and reused for every subsequent request,
/// eliminating per-request `add_template` cost for hot templated
/// fixtures. Exposes no public methods beyond `Default`.
#[cfg(feature = "templating")]
#[derive(Default)]
pub struct TemplateCache {
    cell: std::sync::OnceLock<Result<std::sync::Arc<minijinja::Environment<'static>>, String>>,
}

#[cfg(feature = "templating")]
impl std::fmt::Debug for TemplateCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TemplateCache")
            .field("initialized", &self.cell.get().is_some())
            .finish()
    }
}

#[cfg(feature = "templating")]
impl Clone for TemplateCache {
    // NOTE: a clone always returns a fresh empty cache. The contract
    // relies on the invariant that fixtures live inside `Arc<Fixture>`
    // post-build (`AppState.fixtures: RwLock<FixtureSet>`), so
    // `Fixture::clone()` — and therefore this impl — is never called
    // on the request hot path. If a future refactor reintroduces a
    // direct `Fixture::clone()` anywhere, the compile cache is
    // silently defeated for that path.
    fn clone(&self) -> Self {
        #[cfg(debug_assertions)]
        if self.cell.get().is_some() {
            eprintln!(
                "[llmposter] Warning: TemplateCache cloned — compile cache defeated. \
                 This is expected during hot-reload but not on the request path."
            );
        }
        Self::default()
    }
}

#[cfg(feature = "templating")]
impl TemplateCache {
    /// Returns a reference to the compiled environment, building it on
    /// first call. The compile result — success or the error message — is
    /// cached so subsequent calls don't pay the compile cost again.
    pub(crate) fn get_or_compile(
        &self,
        template_source: &str,
    ) -> Result<&std::sync::Arc<minijinja::Environment<'static>>, &str> {
        let entry = self.cell.get_or_init(|| {
            let mut env = minijinja::Environment::new();
            env.add_template_owned("t", template_source.to_string())
                .map_err(|e| format!("template compile error: {}", e))?;
            Ok(std::sync::Arc::new(env))
        });
        match entry {
            Ok(env) => Ok(env),
            Err(msg) => Err(msg.as_str()),
        }
    }
}

/// The response to return when a fixture matches.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct FixtureResponse {
    /// Text content to return (mutually exclusive with `tool_calls` and
    /// `content_template`).
    pub content: Option<String>,
    /// Jinja-style template rendered at response time, with access to
    /// request fields (`user_message`, `model`, `provider`, `request`).
    /// Mutually exclusive with `content` and `tool_calls`. Requires the
    /// `templating` feature — if that feature is disabled, any fixture
    /// with `content_template` set is rejected at load time with a clear
    /// error pointing at the feature flag.
    pub content_template: Option<String>,
    /// Tool calls to return (mutually exclusive with `content`).
    pub tool_calls: Option<Vec<ToolCall>>,
    /// Anthropic-style stop reason (e.g. `"end_turn"`, `"tool_use"`).
    pub stop_reason: Option<String>,
    /// OpenAI-style finish reason (e.g. `"stop"`, `"tool_calls"`).
    pub finish_reason: Option<String>,
    /// Embedding vector for `/v1/embeddings` responses. When absent on
    /// an embeddings request, a deterministic fake embedding is generated.
    pub embedding: Option<Vec<f64>>,
    /// Compile cache for `content_template`. Populated lazily on first
    /// render; see [`TemplateCache`] for details. This field MUST stay
    /// `pub` (not `pub(crate)`) because external tests construct
    /// `FixtureResponse` via `..Default::default()` and Rust's
    /// functional update syntax still requires every field to be
    /// visible from the caller's position. `TemplateCache` exposes no
    /// mutation methods, so external callers can only reset it to its
    /// default value — never populate or observe the cache contents.
    /// Hidden from rustdoc so it doesn't pollute the public surface
    /// browsable on docs.rs.
    #[cfg(feature = "templating")]
    #[serde(skip)]
    #[doc(hidden)]
    pub template_cache: TemplateCache,
}

/// Error simulation — returns an HTTP error status.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FixtureError {
    /// HTTP status code (must be 400-599).
    pub status: u16,
    /// Error message included in the response body.
    pub message: String,
    /// Optional response headers to include (e.g. override rate limit headers on 429).
    #[serde(default)]
    pub headers: HashMap<String, String>,
}

/// Failure simulation — network/streaming problems.
///
/// Two flavors of failure:
///
/// - **Classical** (`latency_ms`, `corrupt_body`, `truncate_after_frames`,
///   `disconnect_after_ms`): deterministic, always fire when set.
/// - **Chaos** (`latency_jitter_ms`, `duplicate_frames`, `probability`,
///   `chaos_seed`): randomized but seeded, so runs are reproducible. Chaos
///   fields are gated by `probability` — rolling above the probability on
///   a given request leaves chaos inactive for that request. Classical
///   failures ignore `probability` and always apply.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct FailureConfig {
    /// Inject latency (in milliseconds) before sending the response.
    pub latency_ms: Option<u64>,
    /// If `true`, corrupt the response body (invalid JSON/SSE).
    pub corrupt_body: Option<bool>,
    /// Truncate SSE stream after N frames (including preamble events).
    /// Alias: `truncate_after_chunks` (deprecated, use `truncate_after_frames`).
    ///
    /// **Interaction with `duplicate_frames`:** this count is applied to the
    /// stream AFTER duplication. If `duplicate_frames: true` doubles the
    /// source frames, `truncate_after_frames: 2` sends the first two
    /// *doubled* entries (i.e. the first source frame emitted twice). Set
    /// `truncate_after_frames` to `2 * N` if you want to cut after `N` of
    /// the original frames.
    #[serde(alias = "truncate_after_chunks")]
    pub truncate_after_frames: Option<u32>,
    /// Abruptly close the connection after this many milliseconds.
    pub disconnect_after_ms: Option<u64>,
    // --- Streaming chaos (seeded, deterministic per request) ---
    /// Add random ±jitter (milliseconds) to the per-frame streaming latency.
    /// Requires a base `streaming.latency` to act on. Jitter is symmetric:
    /// a jitter of `10` adds a value in the range `[-10, +10]` to each frame
    /// delay. The effective delay is clamped at zero — a jittered negative
    /// value becomes an immediate frame.
    pub latency_jitter_ms: Option<u64>,
    /// If `true`, emit each streaming frame twice back-to-back. Useful for
    /// testing idempotent-consumer logic that must tolerate repeated events.
    ///
    /// **Interaction with `truncate_after_frames`:** duplication happens
    /// before truncation counting, so `duplicate_frames: true` +
    /// `truncate_after_frames: N` cuts after N *doubled* frames. See the
    /// `truncate_after_frames` doc for the full explanation.
    pub duplicate_frames: Option<bool>,
    /// Probability in `[0.0, 1.0]` that the chaos fields activate for a
    /// given request. `None` or `1.0` = always. `0.0` = never. Classical
    /// failures (latency_ms, corrupt_body, truncate, disconnect) are NOT
    /// affected by this — only the chaos fields above.
    pub probability: Option<f32>,
    /// Override the chaos PRNG seed. When unset, the seed is derived from
    /// an internal per-server request counter, so successive requests from
    /// the same test produce a deterministic but distinct sequence of chaos
    /// outcomes. Setting `chaos_seed` to a fixed value reproduces the same
    /// jitter/duplicate pattern across server instances.
    pub chaos_seed: Option<u64>,
}

impl FailureConfig {
    /// Returns true if any of the chaos-specific fields are set — i.e. this
    /// failure config requires the chaos PRNG + activation roll. Classical
    /// failure fields (latency_ms, corrupt_body, truncate_after_frames,
    /// disconnect_after_ms) are not chaos and do not trigger this.
    pub(crate) fn has_chaos(&self) -> bool {
        self.latency_jitter_ms.is_some()
            || self.duplicate_frames.is_some()
            || self.probability.is_some()
            || self.chaos_seed.is_some()
    }
}

/// Streaming behavior config.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StreamingConfig {
    /// Delay in milliseconds between SSE frames.
    pub latency: Option<u64>,
    /// Number of Unicode characters per streaming chunk.
    pub chunk_size: Option<usize>,
}

/// Scenario state machine config for multi-turn fixtures.
///
/// When a fixture has a `scenario` block, it participates in a named state machine.
/// The fixture only matches when the scenario's current state equals `required_state`
/// (or if `required_state` is not set). After matching, the scenario state advances
/// to `set_state`.
///
/// # YAML Example
///
/// ```yaml
/// fixtures:
///   - match:
///       user_message: "weather in Paris"
///     scenario:
///       name: "weather-flow"
///       set_state: "tool_called"
///     response:
///       tool_calls:
///         - name: get_weather
///           arguments: { location: "Paris" }
///
///   - match:
///       user_message: "tool_result"
///     scenario:
///       name: "weather-flow"
///       required_state: "tool_called"
///       set_state: "completed"
///     response:
///       content: "It's 22°C in Paris"
/// ```
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScenarioConfig {
    /// Name of the scenario state machine.
    pub name: String,
    /// Only match this fixture when the scenario is in this state.
    /// If not set, the fixture matches regardless of current state.
    pub required_state: Option<String>,
    /// Advance the scenario to this state after the fixture matches.
    /// If not set, the scenario state is unchanged.
    pub set_state: Option<String>,
}

/// Safety refusal configuration for a fixture.
///
/// Produces a provider-appropriate refusal response:
///
/// - **OpenAI Chat Completions**: `message.refusal: "<reason>"` with
///   `content: null`; `finish_reason: "stop"`.
/// - **Anthropic**: a text content block with the refusal reason and
///   `stop_reason: "refusal"` (Anthropic's native refusal stop reason).
/// - **Gemini**: `candidates: []` plus `promptFeedback.blockReason:
///   "SAFETY"`. Mirrors the real Gemini shape when the prompt itself is
///   blocked.
/// - **OpenAI Responses API**: a message output item containing a
///   single `type: "refusal"` content part; top-level
///   `status: "completed"`.
///
/// This is a first-class fixture outcome — tests exercising client-side
/// refusal handling no longer need to hand-roll provider-specific error
/// shapes.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Refusal {
    /// Human-readable refusal text returned to the client. Required.
    pub reason: String,
}

/// A single fixture entry.
///
/// Fixtures are the core building block of llmposter. Each fixture defines a
/// match rule, a response (or error/failure/refusal), and optional streaming/scenario config.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Fixture {
    /// Match criteria (user message, model). If absent, fixture matches all requests.
    #[serde(rename = "match")]
    pub match_rule: Option<FixtureMatch>,
    /// Restrict this fixture to a specific LLM provider endpoint.
    pub provider: Option<crate::format::Provider>,
    /// The response to return when matched.
    pub response: Option<FixtureResponse>,
    /// Error simulation (HTTP error status + message).
    pub error: Option<FixtureError>,
    /// Safety refusal — provider-specific refusal-shape response.
    /// Mutually exclusive with `response`, `error`, and `failure`.
    /// Only applies to non-streaming requests: a `refusal` fixture
    /// matched against `stream: true` returns HTTP 400 (streaming
    /// refusal envelopes are not yet implemented).
    pub refusal: Option<Refusal>,
    /// Failure simulation (latency, corruption, truncation, disconnect).
    pub failure: Option<FailureConfig>,
    /// Streaming behavior (latency between frames, chunk size).
    pub streaming: Option<StreamingConfig>,
    /// Scenario state machine — enables multi-turn fixture matching.
    pub scenario: Option<ScenarioConfig>,
    /// Match priority (higher wins). Fixtures without priority fall
    /// back to file order. Useful when a high-priority "specific"
    /// fixture must beat a lower-priority catch-all regardless of
    /// where each sits in the fixture list.
    #[serde(default)]
    pub priority: Option<i32>,
    /// When `true`, this fixture is considered only after every
    /// non-catch-all fixture has failed to match, regardless of the
    /// catch-all's `priority`. Within the catch-all fallback pass,
    /// `priority` still orders candidates (highest first, file order
    /// as the stable tiebreak). Useful for a last-resort default
    /// response that can sit anywhere in the fixture list.
    #[serde(default)]
    pub catch_all: bool,
}

/// Top-level YAML file structure (internal, used for deserialization only).
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct FixtureFile {
    /// List of fixture entries from the YAML file.
    pub fixtures: Vec<Fixture>,
}

// --- Programmatic builder API ---

impl Fixture {
    /// Create a new empty fixture with no match criteria. Because
    /// `match_rule` is `None`, the fixture will match every request
    /// reaching the matcher (first-match-wins within the priority pass).
    /// This is NOT the same as `catch_all: true` — v0.4.6's catch-all
    /// flag defers a fixture to a second-pass fallback after every
    /// non-catch-all has had a chance. Opt into that by chaining
    /// [`Fixture::as_catch_all`].
    pub fn new() -> Self {
        Self {
            match_rule: None,
            provider: None,
            response: None,
            error: None,
            refusal: None,
            failure: None,
            streaming: None,
            scenario: None,
            priority: None,
            catch_all: false,
        }
    }

    /// Set the fixture match priority. Higher wins; unprioritized
    /// fixtures fall back to file order. See the field doc for
    /// interaction with `catch_all`.
    pub fn with_priority(mut self, priority: i32) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Mark this fixture as catch-all: it only matches when no
    /// other fixture does, regardless of file order.
    pub fn as_catch_all(mut self) -> Self {
        self.catch_all = true;
        self
    }

    /// Configure this fixture to return a provider-specific safety refusal.
    ///
    /// Mutually exclusive with `respond_with_content`, `respond_with_tool_calls`,
    /// and `with_error`. The `reason` string is the refusal text returned to the
    /// client.
    pub fn respond_with_refusal(mut self, reason: &str) -> Self {
        self.refusal = Some(Refusal {
            reason: reason.to_string(),
        });
        self
    }

    /// Match requests where the last user message contains `pattern` (substring match).
    pub fn match_user_message(mut self, pattern: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.user_message = Some(StringMatch::Substring(pattern.to_string()));
        self
    }

    /// Match requests where the model name contains `pattern` (substring match).
    pub fn match_model(mut self, pattern: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.model = Some(StringMatch::Substring(pattern.to_string()));
        self
    }

    /// Match requests that carry a specific header value (substring match,
    /// case-insensitive header name).
    pub fn match_header(mut self, name: &str, value: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.headers.insert(
            name.to_ascii_lowercase(),
            StringMatch::Substring(value.to_string()),
        );
        self
    }

    /// Match requests where the system prompt contains `pattern` (substring match).
    pub fn match_system_prompt(mut self, pattern: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.system_prompt = Some(StringMatch::Substring(pattern.to_string()));
        self
    }

    /// Match requests whose `temperature` field equals `value`. For
    /// tolerance-based matching use [`Fixture::match_temperature_range`].
    pub fn match_temperature(mut self, value: f64) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.temperature = Some(F64Match::Exact(value));
        self
    }

    /// Match requests whose `temperature` falls inside an inclusive
    /// range. Either bound may be `None` for open-ended ranges.
    pub fn match_temperature_range(mut self, min: Option<f64>, max: Option<f64>) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.temperature = Some(F64Match::Range(F64Range { min, max }));
        self
    }

    /// Match requests whose top-level `metadata` object contains a
    /// given key with a substring match on the value.
    pub fn match_metadata(mut self, key: &str, value: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.metadata
            .insert(key.to_string(), StringMatch::Substring(value.to_string()));
        self
    }

    /// Match requests that declare a tool with a given name
    /// (substring match). Works across all four providers' tool
    /// schema shapes.
    pub fn match_tool_schema(mut self, pattern: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.tool_schema = Some(StringMatch::Substring(pattern.to_string()));
        self
    }

    /// Match requests whose JSON body satisfies a JSONPath expression
    /// (RFC 9535). The fixture matches when the path returns at least
    /// one non-null value. Requires the `jsonpath` crate feature.
    #[cfg(feature = "jsonpath")]
    pub fn match_body_jsonpath(mut self, path: &str) -> Self {
        let m = self.match_rule.get_or_insert_with(FixtureMatch::default);
        m.body_jsonpath = Some(path.to_string());
        self
    }

    /// Set a plain-text content response for this fixture.
    pub fn respond_with_content(mut self, content: &str) -> Self {
        let r = self.response.get_or_insert(FixtureResponse::default());
        r.content = Some(content.to_string());
        r.tool_calls = None;
        self
    }

    /// Configure this fixture to return an HTTP error response.
    pub fn with_error(mut self, status: u16, message: &str) -> Self {
        self.error = Some(FixtureError {
            status,
            message: message.to_string(),
            headers: HashMap::new(),
        });
        self
    }

    /// Like `with_error` but also sets custom response headers (e.g. to override
    /// rate limit header values on a 429 fixture).
    ///
    /// Returns `Err` if any header name or value is not a valid HTTP header.
    pub fn with_error_headers<I, K, V>(
        mut self,
        status: u16,
        message: &str,
        headers: I,
    ) -> Result<Self, String>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        use axum::http::{HeaderName, HeaderValue};
        use std::str::FromStr;
        let mut map = HashMap::new();
        for (k, v) in headers {
            HeaderName::from_str(k.as_ref())
                .map_err(|e| format!("invalid header name {:?}: {e}", k.as_ref()))?;
            HeaderValue::from_str(v.as_ref())
                .map_err(|e| format!("invalid header value {:?}: {e}", v.as_ref()))?;
            let lower = k.as_ref().to_ascii_lowercase();
            if map.contains_key(&lower) {
                return Err(format!(
                    "duplicate header name (case-insensitive): {lower:?}"
                ));
            }
            map.insert(lower, v.as_ref().to_string());
        }
        self.error = Some(FixtureError {
            status,
            message: message.to_string(),
            headers: map,
        });
        Ok(self)
    }

    /// Attach a failure simulation (latency, corruption, truncation, disconnect).
    pub fn with_failure(mut self, failure: FailureConfig) -> Self {
        self.failure = Some(failure);
        self
    }

    /// Set the Anthropic-style `stop_reason` on the response.
    pub fn with_stop_reason(mut self, reason: &str) -> Self {
        self.response
            .get_or_insert(FixtureResponse::default())
            .stop_reason = Some(reason.to_string());
        self
    }

    /// Set the OpenAI-style `finish_reason` on the response.
    pub fn with_finish_reason(mut self, reason: &str) -> Self {
        self.response
            .get_or_insert(FixtureResponse::default())
            .finish_reason = Some(reason.to_string());
        self
    }

    /// Configure streaming behavior (inter-frame latency and chunk size).
    pub fn with_streaming(mut self, latency: Option<u64>, chunk_size: Option<usize>) -> Self {
        self.streaming = Some(StreamingConfig {
            latency,
            chunk_size,
        });
        self
    }

    /// Attach this fixture to a named scenario state machine.
    ///
    /// - `name`: scenario identifier (shared across fixtures in the same scenario)
    /// - `required_state`: only match when the scenario is in this state (None = always match)
    /// - `set_state`: advance the scenario to this state after matching (None = no change)
    pub fn with_scenario(
        mut self,
        name: &str,
        required_state: Option<&str>,
        set_state: Option<&str>,
    ) -> Self {
        self.scenario = Some(ScenarioConfig {
            name: name.to_string(),
            required_state: required_state.map(|s| s.to_string()),
            set_state: set_state.map(|s| s.to_string()),
        });
        self
    }

    /// Restrict this fixture to a specific LLM provider endpoint.
    pub fn for_provider(mut self, provider: crate::format::Provider) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Set the response to return tool calls instead of text content.
    pub fn respond_with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
        let r = self.response.get_or_insert(FixtureResponse::default());
        r.tool_calls = Some(tool_calls);
        r.content = None;
        self
    }

    /// Set an embedding vector for `/v1/embeddings` responses.
    pub fn respond_with_embedding(mut self, embedding: Vec<f64>) -> Self {
        let r = self.response.get_or_insert(FixtureResponse::default());
        r.embedding = Some(embedding);
        self
    }
}

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

// --- Validation ---

impl Fixture {
    /// Validate fixture invariants and pre-compile regex patterns.
    pub fn validate(&mut self) -> Result<(), String> {
        if let Some(ref e) = self.error {
            if !(400..=599).contains(&e.status) {
                return Err("error.status must be an error HTTP status (400-599)".to_string());
            }
            use axum::http::{HeaderName, HeaderValue};
            use std::str::FromStr;
            for (name, value) in &e.headers {
                HeaderName::from_str(name)
                    .map_err(|err| format!("invalid error header name {name:?}: {err}"))?;
                HeaderValue::from_str(value)
                    .map_err(|err| format!("invalid error header value {value:?}: {err}"))?;
            }
        }
        // Normalize header keys to lowercase, rejecting case-insensitive duplicates.
        // (Ends immutable borrow before mutating.)
        if let Some(ref mut e) = self.error {
            let mut normalized: HashMap<String, String> = HashMap::new();
            for (k, v) in e.headers.drain() {
                let lower = k.to_ascii_lowercase();
                if normalized.contains_key(&lower) {
                    return Err(format!(
                        "duplicate error header name (case-insensitive): {lower:?}"
                    ));
                }
                normalized.insert(lower, v);
            }
            e.headers = normalized;
        }
        if self.response.is_some() && self.error.is_some() {
            return Err("'error' and 'response' are mutually exclusive".to_string());
        }
        if self.error.is_some() && self.failure.is_some() {
            return Err("'error' and 'failure' are mutually exclusive".to_string());
        }
        if self.refusal.is_some() && self.response.is_some() {
            return Err("'refusal' and 'response' are mutually exclusive".to_string());
        }
        if self.refusal.is_some() && self.error.is_some() {
            return Err("'refusal' and 'error' are mutually exclusive".to_string());
        }
        if self.refusal.is_some() && self.failure.is_some() {
            return Err("'refusal' and 'failure' are mutually exclusive".to_string());
        }
        if self.refusal.is_some() && self.streaming.is_some() {
            return Err("'refusal' and 'streaming' are mutually exclusive".to_string());
        }
        if let Some(ref r) = self.refusal {
            if r.reason.trim().is_empty() {
                return Err("refusal.reason must not be blank".to_string());
            }
        }
        if self.failure.is_some() && self.response.is_none() {
            return Err("'failure' requires response to also be present".to_string());
        }
        if let (Some(ref f), None) = (&self.failure, &self.streaming) {
            let has_stream_failure =
                f.truncate_after_frames.is_some() || f.disconnect_after_ms.is_some();
            if has_stream_failure {
                eprintln!(
                    "[llmposter] Warning: failure.truncate_after_frames/disconnect_after_ms \
                     have no effect without streaming configured"
                );
            }
            // Same gap applies to `duplicate_frames`: the chaos plan is only
            // consulted inside the `is_streaming` branch of the handler, so
            // a non-streaming fixture that sets duplicate_frames silently
            // drops the flag. Warn so the misconfiguration is visible.
            if f.duplicate_frames == Some(true) {
                eprintln!(
                    "[llmposter] Warning: failure.duplicate_frames has no effect \
                     without streaming configured"
                );
            }
        }
        // Validate chaos field invariants.
        if let Some(ref f) = self.failure {
            if let Some(p) = f.probability {
                if !p.is_finite() || !(0.0..=1.0).contains(&p) {
                    return Err(format!(
                        "failure.probability must be a finite number in [0.0, 1.0], got {}",
                        p
                    ));
                }
            }
            // latency_jitter_ms: Some(0) is a documented no-op (ChaosPlan
            // collapses it to None), so it needs no base latency and no cap
            // check. Only enforce the constraints when jitter > 0.
            if let Some(jitter) = f.latency_jitter_ms {
                if jitter > 0 {
                    let base_latency = self.streaming.as_ref().and_then(|s| s.latency).unwrap_or(0);
                    if base_latency == 0 {
                        return Err(
                            "failure.latency_jitter_ms requires a non-zero streaming.latency"
                                .to_string(),
                        );
                    }
                    // Cap at 1 hour. A mock server has no legitimate reason
                    // to jitter a per-frame delay beyond this, and the upper
                    // bound keeps the chaos PRNG arithmetic inside i64.
                    const MAX_JITTER_MS: u64 = 60 * 60 * 1000;
                    if jitter > MAX_JITTER_MS {
                        return Err(format!(
                            "failure.latency_jitter_ms must be <= {} (got {})",
                            MAX_JITTER_MS, jitter
                        ));
                    }
                }
            }
            // Warn on degenerate chaos config: `chaos_seed` and `probability`
            // only take effect when paired with `latency_jitter_ms` or
            // `duplicate_frames`. A fixture setting only the gating fields
            // advances the chaos counter but produces no observable effect,
            // which is confusing to debug. This is a warning, not an error —
            // the config is technically valid.
            let has_effect_field = f.latency_jitter_ms.map(|j| j > 0).unwrap_or(false)
                || f.duplicate_frames == Some(true);
            let has_gate_field = f.chaos_seed.is_some() || f.probability.is_some();
            if has_gate_field && !has_effect_field {
                eprintln!(
                    "[llmposter] Warning: failure.chaos_seed/probability set without \
                     latency_jitter_ms or duplicate_frames — chaos fields have no \
                     observable effect"
                );
            }
        }
        // Validate FixtureResponse mutual exclusivity
        if let Some(ref r) = self.response {
            // content_template requires the `templating` feature. Reject
            // early with a clear error so users who typo the feature name
            // or disable it intentionally know exactly what's wrong.
            #[cfg(not(feature = "templating"))]
            if r.content_template.is_some() {
                return Err(
                    "'content_template' requires the 'templating' feature — rebuild with \
                     `--features templating` to enable it"
                        .to_string(),
                );
            }
            if r.content.is_some() && r.content_template.is_some() {
                return Err(
                    "'content' and 'content_template' in response are mutually exclusive"
                        .to_string(),
                );
            }
            if r.content_template.is_some() && r.tool_calls.is_some() {
                return Err(
                    "'content_template' and 'tool_calls' in response are mutually exclusive"
                        .to_string(),
                );
            }
            // Compile the template at validation time so syntax errors
            // surface during `--validate` / `ServerBuilder::build()`
            // instead of producing a 500 on the first matching request.
            #[cfg(feature = "templating")]
            if let Some(ref tmpl) = r.content_template {
                let mut env = minijinja::Environment::new();
                if let Err(e) = env.add_template_owned("t", tmpl.clone()) {
                    return Err(format!("content_template compile error: {}", e));
                }
            }
            if r.content.is_some() && r.tool_calls.is_some() {
                return Err(
                    "'content' and 'tool_calls' in response are mutually exclusive".to_string(),
                );
            }
            if r.content.is_none()
                && r.tool_calls.is_none()
                && r.content_template.is_none()
                && r.embedding.is_none()
            {
                return Err(
                    "response must have 'content', 'content_template', 'tool_calls', or 'embedding'"
                        .to_string(),
                );
            }
            if let Some(ref emb) = r.embedding {
                for (i, v) in emb.iter().enumerate() {
                    if !v.is_finite() {
                        return Err(format!(
                            "response.embedding[{}] must be finite (got {})",
                            i, v
                        ));
                    }
                }
            }
            if let Some(ref tc) = r.tool_calls {
                if tc.is_empty() {
                    return Err("tool_calls must not be empty".to_string());
                }
                for (i, call) in tc.iter().enumerate() {
                    if call.name.trim().is_empty() {
                        return Err(format!("tool_calls[{}].name must not be empty", i));
                    }
                    if !call.arguments.is_object() {
                        return Err(format!(
                            "tool_calls[{}].arguments must be a JSON object, got {}",
                            i,
                            match &call.arguments {
                                serde_json::Value::Array(_) => "array",
                                serde_json::Value::String(_) => "string",
                                serde_json::Value::Number(_) => "number",
                                serde_json::Value::Bool(_) => "boolean",
                                serde_json::Value::Null => "null",
                                _ => "non-object",
                            }
                        ));
                    }
                }
            }
        }
        if self.response.is_none() && self.error.is_none() && self.refusal.is_none() {
            return Err("Fixture must have either 'response', 'error', or 'refusal'".to_string());
        }
        if let Some(ref s) = self.streaming {
            if s.chunk_size == Some(0) {
                return Err("streaming.chunk_size must be > 0".to_string());
            }
            if self.error.is_some() {
                return Err("'streaming' config has no effect on error-only fixtures".to_string());
            }
        }
        if let Some(ref mut m) = self.match_rule {
            validate_string_match_field(&mut m.user_message, "user_message")?;
            validate_string_match_field(&mut m.model, "model")?;
            validate_string_match_field(&mut m.system_prompt, "system_prompt")?;
            validate_string_match_field(&mut m.tool_schema, "tool_schema")?;

            for (name, pattern) in m.headers.iter_mut() {
                if name.trim().is_empty() {
                    return Err("match.headers: header name must not be blank".to_string());
                }
                // HTTP header names are tokens per RFC 7230 §3.2.6:
                // ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'"
                // / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
                // Reject anything that can never match a real request.
                if !name.bytes().all(|b| {
                    matches!(b,
                    b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' |
                    b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' |
                    b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~')
                }) {
                    return Err(format!(
                        "match.headers: '{}' is not a valid HTTP header name \
                         (must be RFC 7230 token characters)",
                        name
                    ));
                }
                validate_string_match(pattern, &format!("headers[{}]", name))?;
            }
            for (key, pattern) in m.metadata.iter_mut() {
                if key.trim().is_empty() {
                    return Err("match.metadata: key must not be blank".to_string());
                }
                validate_string_match(pattern, &format!("metadata[{}]", key))?;
            }

            // body_jsonpath requires the `jsonpath` feature. Reject
            // early with a clear error — without this, serde would
            // accept the field but the matcher would silently ignore
            // the expression at match time.
            #[cfg(not(feature = "jsonpath"))]
            if m.body_jsonpath.is_some() {
                return Err(
                    "'match.body_jsonpath' requires the 'jsonpath' feature — rebuild with \
                     `--features jsonpath` to enable it"
                        .to_string(),
                );
            }

            #[cfg(feature = "jsonpath")]
            {
                // Unconditionally clear any previously-cached compiled
                // query FIRST so early-return error paths don't leave a
                // stale `JpQuery` from a prior `validate()` call — the
                // fixture's `body_jsonpath` may have been changed to an
                // invalid string between the two calls.
                m.body_jsonpath_compiled = None;
                if let Some(ref path) = m.body_jsonpath {
                    if path.trim().is_empty() {
                        return Err("match.body_jsonpath must not be empty".to_string());
                    }
                    // Pre-parse into a `JpQuery` so the hot path doesn't
                    // re-parse the string on every request (pest-based
                    // parser is not free).
                    match jsonpath_rust::parser::parse_json_path(path) {
                        Ok(q) => m.body_jsonpath_compiled = Some(q),
                        Err(e) => {
                            return Err(format!("match.body_jsonpath is invalid: {}", e));
                        }
                    }
                }
            }

            // Normalize header match keys to ASCII lowercase once at
            // load time so the hot path can look up directly against
            // `HeaderName::as_str()` (which is always lowercase).
            if !m.headers.is_empty() {
                let raw = std::mem::take(&mut m.headers);
                let mut normalized: std::collections::HashMap<String, StringMatch> =
                    std::collections::HashMap::with_capacity(raw.len());
                // Track the original-case version of each already-
                // inserted key so the duplicate error can name BOTH
                // colliding headers (the first one and the one we
                // rejected), not just the trailing key.
                let mut origins: std::collections::HashMap<String, String> =
                    std::collections::HashMap::with_capacity(raw.len());
                for (name, pattern) in raw {
                    let key = name.to_ascii_lowercase();
                    if let Some(prior) = origins.get(&key) {
                        return Err(format!(
                            "match.headers: duplicate header name after case-folding: \
                             '{}' and '{}' both normalize to '{}'",
                            prior, name, key
                        ));
                    }
                    origins.insert(key.clone(), name);
                    normalized.insert(key, pattern);
                }
                m.headers = normalized;
            }

            if let Some(ref tm) = m.temperature {
                match tm {
                    F64Match::Exact(v) => {
                        if !v.is_finite() {
                            return Err(format!(
                                "match.temperature must be a finite number, got {}",
                                v
                            ));
                        }
                    }
                    F64Match::Range(r) => {
                        if let Some(min) = r.min {
                            if !min.is_finite() {
                                return Err("match.temperature.min must be finite".to_string());
                            }
                        }
                        if let Some(max) = r.max {
                            if !max.is_finite() {
                                return Err("match.temperature.max must be finite".to_string());
                            }
                        }
                        if let (Some(min), Some(max)) = (r.min, r.max) {
                            if min > max {
                                return Err(format!(
                                    "match.temperature range inverted: min={} > max={}",
                                    min, max
                                ));
                            }
                        }
                        if r.min.is_none() && r.max.is_none() {
                            return Err("match.temperature range must set at least one of min/max"
                                .to_string());
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

/// Validate a single optional `StringMatch` field used in `match:`.
/// Compiles regex patterns to surface bad patterns at load time.
fn validate_string_match_field(field: &mut Option<StringMatch>, name: &str) -> Result<(), String> {
    if let Some(pattern) = field {
        validate_string_match(pattern, name)?;
    }
    Ok(())
}

fn validate_string_match(pattern: &mut StringMatch, name: &str) -> Result<(), String> {
    match pattern {
        StringMatch::Substring(s) => {
            if s.is_empty() {
                return Err(format!("match.{} substring must not be empty", name));
            }
        }
        StringMatch::Regex(r) => {
            if r.regex.is_empty() {
                return Err(format!("match.{} regex must not be empty", name));
            }
            r.compile().map_err(|e| format!("{} {}", name, e))?;
        }
    }
    Ok(())
}

// --- Matching ---

/// Find the first fixture that matches the given request parameters and scenario state.
///
/// Fixtures are evaluated in slice order (first-match-wins). If a
/// fixture has a `scenario` with `required_state`, it only matches
/// when the scenario's current state equals that value. Fixtures
/// without a scenario always participate in matching.
///
/// **NOTE:** v0.4.6's `priority` and `catch_all` fields are
/// **ignored** by this helper, and the v0.4.6 request-body match
/// fields (`headers`, `system_prompt`, `temperature`, `metadata`,
/// `tool_schema`, `body_jsonpath`) **cannot be satisfied** here —
/// the helper fabricates an empty header map and a `Value::Null`
/// body, so any fixture declaring one of those fields will skip
/// and emit a one-line `[llmposter]` warning. Production request
/// dispatch runs the two-pass priority-sorted selection in
/// `src/handler/mod.rs` with real request data; this function
/// stays on the original first-match path so pre-v0.4.6 callers
/// (and unit tests built around `&[Fixture]`) keep their existing
/// semantics. For the full v0.4.6 behavior, go through a
/// `ServerBuilder` + real HTTP request.
///
/// Production code iterates `&[Arc<Fixture>]` directly and calls
/// [`fixture_matches`] — this function survives as a `&[Fixture]` helper
/// for external callers and unit tests, but is hidden from rustdoc.
#[doc(hidden)]
pub fn match_fixture<'a>(
    fixtures: &'a [Fixture],
    user_message: &str,
    model: Option<&str>,
    provider: Option<crate::format::Provider>,
    scenario_states: Option<&std::collections::HashMap<String, String>>,
) -> Option<&'a Fixture> {
    // Surface the "unsupported field is silently skipped" trap
    // instead of letting a request-body match fail with no
    // diagnostic. This only fires when someone actually hits the
    // combination, so normal pre-v0.4.6 usage stays silent.
    for f in fixtures {
        let has_body_fields = f.match_rule.as_ref().is_some_and(|m| {
            !m.headers.is_empty()
                || m.system_prompt.is_some()
                || m.temperature.is_some()
                || !m.metadata.is_empty()
                || m.tool_schema.is_some()
                || m.body_jsonpath.is_some()
        });
        let has_ordering = f.priority.is_some() || f.catch_all;
        if has_body_fields || has_ordering {
            eprintln!(
                "[llmposter] Warning: match_fixture() cannot honor \
                 v0.4.6 features (priority / catch_all / headers / \
                 system_prompt / temperature / metadata / tool_schema / \
                 body_jsonpath) — this legacy helper uses first-match \
                 order and a fabricated empty request. Drive the server \
                 through ServerBuilder for full match semantics."
            );
            break;
        }
    }
    let empty_headers = std::collections::HashMap::new();
    let empty_body = serde_json::Value::Null;
    let ctx = MatchContext::new(
        user_message,
        model,
        provider,
        scenario_states,
        &empty_headers,
        &empty_body,
    );
    fixtures.iter().find(|f| fixture_matches(f, &ctx))
}

/// Request-side data available for fixture matching. Extracted once
/// per request by the generic handler, then passed by reference into
/// each call to [`fixture_matches`] so richer match fields (headers,
/// temperature, system prompt, tool schema, metadata, JSONPath) don't
/// have to re-parse the request body for every candidate fixture.
///
/// System-prompt and tool-name extraction is deferred to first use via
/// `OnceCell` so a request that never hits a fixture with those match
/// fields pays nothing, and a request that hits several only pays the
/// walk once.
pub(crate) struct MatchContext<'a> {
    /// The extracted latest-user-turn text.
    pub user_message: &'a str,
    /// Model name from the request body or URL (Gemini).
    pub model: Option<&'a str>,
    /// Provider the request hit.
    pub provider: Option<crate::format::Provider>,
    /// Live scenario state machine values.
    pub scenario_states: Option<&'a std::collections::HashMap<String, String>>,
    /// Request headers, lowercased keys (HTTP is case-insensitive).
    /// Empty map when the route does not plumb headers through.
    pub headers: &'a std::collections::HashMap<String, String>,
    /// Full parsed request body. `Value::Null` for routes that don't
    /// send a JSON body (e.g. `/code/{status}`).
    pub body: &'a serde_json::Value,
    /// Cached system prompt extract — populated on first fixture that
    /// consults it. `None` inside the cell means "extracted, but the
    /// request has no system prompt".
    system_prompt_cache: std::cell::OnceCell<Option<String>>,
    /// Cached tool-name list — populated on first fixture that
    /// consults it. Entries borrow from `body`.
    tool_names_cache: std::cell::OnceCell<Vec<&'a str>>,
}

impl<'a> MatchContext<'a> {
    pub fn new(
        user_message: &'a str,
        model: Option<&'a str>,
        provider: Option<crate::format::Provider>,
        scenario_states: Option<&'a std::collections::HashMap<String, String>>,
        headers: &'a std::collections::HashMap<String, String>,
        body: &'a serde_json::Value,
    ) -> Self {
        Self {
            user_message,
            model,
            provider,
            scenario_states,
            headers,
            body,
            system_prompt_cache: std::cell::OnceCell::new(),
            tool_names_cache: std::cell::OnceCell::new(),
        }
    }

    pub(crate) fn system_prompt(&self) -> Option<&str> {
        self.system_prompt_cache
            .get_or_init(|| extract_system_prompt(self.body, self.provider))
            .as_deref()
    }

    pub(crate) fn tool_names(&self) -> &[&'a str] {
        self.tool_names_cache
            .get_or_init(|| extract_tool_names(self.body, self.provider))
    }
}

pub(crate) fn fixture_matches(fixture: &Fixture, ctx: &MatchContext<'_>) -> bool {
    if let Some(fp) = fixture.provider {
        match ctx.provider {
            Some(p) if p == fp => {}
            _ => return false,
        }
    }

    // Check scenario required_state
    if let Some(ref scenario) = fixture.scenario {
        if let Some(ref required) = scenario.required_state {
            let current = ctx
                .scenario_states
                .and_then(|states| states.get(&scenario.name))
                .map(|s| s.as_str())
                .unwrap_or("");
            if current != required {
                return false;
            }
        }
    }

    let Some(m) = fixture.match_rule.as_ref() else {
        return true;
    };

    if let Some(ref um) = m.user_message {
        if !string_matches(um, ctx.user_message) {
            return false;
        }
    }
    if let Some(ref mm) = m.model {
        match ctx.model {
            Some(model) => {
                if !string_matches(mm, model) {
                    return false;
                }
            }
            None => return false,
        }
    }

    // Headers: each declared header pattern must match the request's
    // lowercased-name headers. Keys are normalized to lowercase at
    // `validate()` time so no per-request allocation is needed here.
    // Missing header = no match.
    for (name, pattern) in &m.headers {
        match ctx.headers.get(name) {
            Some(value) => {
                if !string_matches(pattern, value) {
                    return false;
                }
            }
            None => return false,
        }
    }

    // System prompt: extracted once per request via `MatchContext`
    // cache, so fixtures with `system_prompt:` don't re-walk the
    // request body for every candidate.
    if let Some(ref sp) = m.system_prompt {
        match ctx.system_prompt() {
            Some(text) => {
                if !string_matches(sp, text) {
                    return false;
                }
            }
            None => return false,
        }
    }

    // Temperature: field location is provider-specific. Gemini nests
    // it under `generationConfig.temperature`; every other provider
    // uses top-level `temperature`.
    if let Some(ref tm) = m.temperature {
        let temp = extract_temperature(ctx.body, ctx.provider);
        match temp {
            Some(t) => {
                if !f64_matches(tm, t) {
                    return false;
                }
            }
            None => return false,
        }
    }

    // Metadata: `body.metadata` is an OpenAI/Responses convention.
    // Each declared entry must match. OpenAI's metadata spec allows
    // non-string values (numbers, booleans); coerce them to their
    // JSON scalar form (`2`, `true`) so a fixture declaring
    // `metadata: { priority: "2" }` still matches a request with
    // `"metadata": {"priority": 2}`. Null values and nested
    // objects / arrays stay no-match.
    if !m.metadata.is_empty() {
        let Some(metadata) = ctx.body.get("metadata").and_then(|v| v.as_object()) else {
            return false;
        };
        for (key, pattern) in &m.metadata {
            let value_str: Option<std::borrow::Cow<str>> =
                metadata.get(key).and_then(|v| match v {
                    serde_json::Value::String(s) => Some(std::borrow::Cow::Borrowed(s.as_str())),
                    serde_json::Value::Number(n) => Some(std::borrow::Cow::Owned(n.to_string())),
                    serde_json::Value::Bool(b) => Some(std::borrow::Cow::Owned(b.to_string())),
                    _ => None,
                });
            match value_str {
                Some(value) => {
                    if !string_matches(pattern, &value) {
                        return false;
                    }
                }
                None => return false,
            }
        }
    }

    // Tool schema: match on any declared tool name. The request must
    // have at least one tool whose name matches the pattern. Extraction
    // is cached on `MatchContext` so multiple fixtures with
    // `tool_schema:` only walk `body.tools[]` once per request.
    if let Some(ref ts) = m.tool_schema {
        let names = ctx.tool_names();
        if !names.iter().any(|name| string_matches(ts, name)) {
            return false;
        }
    }

    // JSONPath: match when the query returns at least one non-null
    // result against the full parsed request body. `body_jsonpath` is
    // compiled at load time into a `JpQuery`; the hot path evaluates
    // the already-parsed query via `js_path_process` — no pest parse
    // per request.
    //
    // Fallback: if a caller constructed this fixture programmatically
    // and bypassed `ServerBuilder::build`, the compiled field may be
    // empty while the source string is set. Mirror `RegexMatch`: try
    // an on-the-fly parse and emit a one-line warning. This keeps
    // programmatic tests from silently matching every request when
    // they forgot to call validate().
    #[cfg(feature = "jsonpath")]
    if let Some(ref compiled) = m.body_jsonpath_compiled {
        match jsonpath_rust::query::js_path_process(compiled, ctx.body) {
            Ok(matches) => {
                if matches.is_empty() || matches.into_iter().all(|q| q.val().is_null()) {
                    return false;
                }
            }
            Err(_) => {
                // Evaluation error against this body — treat as no match.
                return false;
            }
        }
    } else if let Some(ref path_str) = m.body_jsonpath {
        match jsonpath_rust::parser::parse_json_path(path_str) {
            Ok(query) => match jsonpath_rust::query::js_path_process(&query, ctx.body) {
                Ok(matches) => {
                    if matches.is_empty() || matches.into_iter().all(|q| q.val().is_null()) {
                        return false;
                    }
                }
                Err(_) => return false,
            },
            Err(e) => {
                eprintln!(
                    "[llmposter] Warning: invalid body_jsonpath '{}': {}",
                    path_str, e
                );
                return false;
            }
        }
    }

    true
}

/// Per-field pass/fail result for nearest-match diagnostics.
#[derive(Debug, Clone)]
pub(crate) struct FieldResult {
    pub field: &'static str,
    pub passed: bool,
}

/// Nearest-match diagnostic hint for 404 responses.
#[derive(Debug, Clone)]
pub(crate) struct NearestMatchHint {
    pub fixture_index: usize,
    pub pass_count: usize,
    pub total_fields: usize,
    pub summary: String,
    pub fields: Vec<FieldResult>,
}

/// Evaluate every declared match field on a fixture without short-circuiting.
/// Returns a list of per-field pass/fail results.
pub(crate) fn evaluate_fixture_fields(
    fixture: &Fixture,
    ctx: &MatchContext<'_>,
) -> Vec<FieldResult> {
    let mut results = Vec::new();

    if let Some(fp) = fixture.provider {
        let passed = matches!(ctx.provider, Some(p) if p == fp);
        results.push(FieldResult {
            field: "provider",
            passed,
        });
    }

    if let Some(ref scenario) = fixture.scenario {
        if let Some(ref required) = scenario.required_state {
            let current = ctx
                .scenario_states
                .and_then(|states| states.get(&scenario.name))
                .map(|s| s.as_str())
                .unwrap_or("");
            results.push(FieldResult {
                field: "scenario.required_state",
                passed: current == required,
            });
        }
    }

    let Some(m) = fixture.match_rule.as_ref() else {
        return results;
    };

    if let Some(ref um) = m.user_message {
        results.push(FieldResult {
            field: "user_message",
            passed: string_matches(um, ctx.user_message),
        });
    }

    if let Some(ref mm) = m.model {
        let passed = ctx.model.is_some_and(|model| string_matches(mm, model));
        results.push(FieldResult {
            field: "model",
            passed,
        });
    }

    for (name, pattern) in &m.headers {
        let passed = ctx
            .headers
            .get(name)
            .is_some_and(|v| string_matches(pattern, v));
        results.push(FieldResult {
            field: "headers",
            passed,
        });
    }

    if let Some(ref sp) = m.system_prompt {
        let passed = ctx
            .system_prompt()
            .is_some_and(|text| string_matches(sp, text));
        results.push(FieldResult {
            field: "system_prompt",
            passed,
        });
    }

    if let Some(ref tm) = m.temperature {
        let passed =
            extract_temperature(ctx.body, ctx.provider).is_some_and(|t| f64_matches(tm, t));
        results.push(FieldResult {
            field: "temperature",
            passed,
        });
    }

    if !m.metadata.is_empty() {
        let metadata = ctx.body.get("metadata").and_then(|v| v.as_object());
        let passed = metadata.is_some_and(|meta| {
            m.metadata.iter().all(|(key, pattern)| {
                meta.get(key)
                    .and_then(|v| match v {
                        serde_json::Value::String(s) => {
                            Some(std::borrow::Cow::Borrowed(s.as_str()))
                        }
                        serde_json::Value::Number(n) => {
                            Some(std::borrow::Cow::Owned(n.to_string()))
                        }
                        serde_json::Value::Bool(b) => Some(std::borrow::Cow::Owned(b.to_string())),
                        _ => None,
                    })
                    .is_some_and(|v| string_matches(pattern, &v))
            })
        });
        results.push(FieldResult {
            field: "metadata",
            passed,
        });
    }

    if let Some(ref ts) = m.tool_schema {
        let names = ctx.tool_names();
        let passed = names.iter().any(|name| string_matches(ts, name));
        results.push(FieldResult {
            field: "tool_schema",
            passed,
        });
    }

    #[cfg(feature = "jsonpath")]
    if m.body_jsonpath.is_some() || m.body_jsonpath_compiled.is_some() {
        let passed = if let Some(ref compiled) = m.body_jsonpath_compiled {
            jsonpath_rust::query::js_path_process(compiled, ctx.body)
                .map(|matches| {
                    !matches.is_empty() && !matches.into_iter().all(|q| q.val().is_null())
                })
                .unwrap_or(false)
        } else {
            false
        };
        results.push(FieldResult {
            field: "body_jsonpath",
            passed,
        });
    }

    results
}

/// Find the fixture that came closest to matching (most fields passed).
/// Deterministic: ties broken by lowest fixture index (insertion order).
/// Returns `None` only when the fixture set is empty.
pub(crate) fn evaluate_nearest_match(
    fixtures: &crate::server::FixtureSet,
    ctx: &MatchContext<'_>,
) -> Option<NearestMatchHint> {
    let mut best: Option<NearestMatchHint> = None;

    for (i, fixture) in fixtures.iter_all().enumerate() {
        let fields = evaluate_fixture_fields(fixture, ctx);
        let total_fields = fields.len();
        // Skip fixtures with no match fields (catch-alls, bare fixtures) —
        // they produce a useless 0/0 diagnostic with no actionable info.
        if total_fields == 0 {
            continue;
        }
        let pass_count = fields.iter().filter(|f| f.passed).count();

        let dominated = best.as_ref().is_none_or(|b| pass_count > b.pass_count);
        if dominated {
            let summary = match_summary_for_diagnostic(fixture);
            best = Some(NearestMatchHint {
                fixture_index: i,
                pass_count,
                total_fields,
                summary,
                fields,
            });
        }
    }

    best
}

fn match_summary_for_diagnostic(f: &Fixture) -> String {
    let Some(m) = f.match_rule.as_ref() else {
        return "(any request)".into();
    };
    let mut parts = Vec::new();
    if let Some(ref um) = m.user_message {
        let s = match um {
            StringMatch::Substring(s) => format!("user_message: {:?}", s),
            StringMatch::Regex(r) => format!("user_message: regex({:?})", r.regex),
        };
        parts.push(s);
    }
    if let Some(ref mm) = m.model {
        let s = match mm {
            StringMatch::Substring(s) => format!("model: {:?}", s),
            StringMatch::Regex(r) => format!("model: regex({:?})", r.regex),
        };
        parts.push(s);
    }
    if !m.headers.is_empty() {
        parts.push(format!("headers: {} field(s)", m.headers.len()));
    }
    if parts.is_empty() {
        "(other fields only)".into()
    } else {
        parts.join(", ")
    }
}

/// Pull the system prompt out of a parsed request body. Returns
/// `None` when no system message is present. Handles OpenAI,
/// Anthropic (top-level `system` or array-of-text), Gemini
/// (`systemInstruction.parts`), and Responses API (`input[*]`).
fn extract_system_prompt(
    body: &serde_json::Value,
    provider: Option<crate::format::Provider>,
) -> Option<String> {
    use crate::format::Provider;
    // Anthropic carries the system prompt at the top level, not as a
    // message entry. Support both string and array-of-text shapes.
    if provider == Some(Provider::Anthropic) {
        if let Some(s) = body.get("system") {
            if let Some(text) = s.as_str() {
                return Some(text.to_string());
            }
            if let Some(arr) = s.as_array() {
                let parts: Vec<&str> = arr
                    .iter()
                    .filter(|block| block.get("type").and_then(|v| v.as_str()) == Some("text"))
                    .filter_map(|block| block.get("text").and_then(|v| v.as_str()))
                    .collect();
                if !parts.is_empty() {
                    return Some(parts.join("\n"));
                }
            }
        }
        // Anthropic's system prompt lives at the top level only;
        // don't fall through to the OpenAI `messages[role==system]`
        // scan, which would silently match non-spec request shapes.
        return None;
    }

    // Gemini uses `systemInstruction.parts[*].text`.
    if provider == Some(Provider::Gemini) {
        if let Some(parts) = body
            .get("systemInstruction")
            .and_then(|v| v.get("parts"))
            .and_then(|v| v.as_array())
        {
            let texts: Vec<&str> = parts
                .iter()
                .filter_map(|p| p.get("text").and_then(|v| v.as_str()))
                .collect();
            if !texts.is_empty() {
                return Some(texts.join("\n"));
            }
        }
        return None;
    }

    // Responses API primary shape: the top-level `instructions:`
    // field is a plain string. Some clients ALSO embed a
    // `role == "system"` entry inside `input[]`; fall back to that
    // shape if `instructions` is absent.
    if provider == Some(Provider::Responses) {
        if let Some(text) = body.get("instructions").and_then(|v| v.as_str()) {
            return Some(text.to_string());
        }
    }

    // OpenAI Chat Completions + Responses API (fallback): system is a
    // message with `role == "system"` inside `messages` / `input`.
    let array_key = match provider {
        Some(Provider::Responses) => "input",
        _ => "messages",
    };
    if let Some(arr) = body.get(array_key).and_then(|v| v.as_array()) {
        let parts: Vec<String> = arr
            .iter()
            .filter(|m| m.get("role").and_then(|v| v.as_str()) == Some("system"))
            .filter_map(|m| {
                let content = m.get("content")?;
                if let Some(s) = content.as_str() {
                    return Some(s.to_string());
                }
                if let Some(arr) = content.as_array() {
                    let texts: Vec<&str> = arr
                        .iter()
                        .filter_map(|part| part.get("text").and_then(|v| v.as_str()))
                        .collect();
                    if !texts.is_empty() {
                        return Some(texts.join("\n"));
                    }
                }
                None
            })
            .collect();
        if !parts.is_empty() {
            return Some(parts.join("\n"));
        }
    }
    None
}

/// Pull the list of declared tool names out of a parsed request body.
/// Returns an empty vec when no tools are declared. Works across all
/// four provider shapes. Values borrow from `body`, which outlives
/// the match loop — no allocation per name.
fn extract_tool_names(
    body: &serde_json::Value,
    provider: Option<crate::format::Provider>,
) -> Vec<&str> {
    use crate::format::Provider;
    let tools = match body.get("tools").and_then(|v| v.as_array()) {
        Some(t) => t,
        None => return Vec::new(),
    };

    let mut out: Vec<&str> = Vec::new();
    for tool in tools {
        match provider {
            // Gemini: tools[].functionDeclarations[].name
            Some(Provider::Gemini) => {
                if let Some(decls) = tool.get("functionDeclarations").and_then(|v| v.as_array()) {
                    for decl in decls {
                        if let Some(name) = decl.get("name").and_then(|v| v.as_str()) {
                            out.push(name);
                        }
                    }
                }
            }
            // Anthropic: tools[].name
            Some(Provider::Anthropic) => {
                if let Some(name) = tool.get("name").and_then(|v| v.as_str()) {
                    out.push(name);
                }
            }
            // OpenAI / Responses: tools[].function.name (OpenAI) or
            // tools[].name (Responses API function tools). Try both.
            _ => {
                if let Some(name) = tool
                    .get("function")
                    .and_then(|v| v.get("name"))
                    .and_then(|v| v.as_str())
                {
                    out.push(name);
                } else if let Some(name) = tool.get("name").and_then(|v| v.as_str()) {
                    out.push(name);
                }
            }
        }
    }
    out
}

/// Pull the request's `temperature` out of a parsed body. Gemini
/// nests temperature inside `generationConfig`; every other provider
/// puts it at the top level.
/// Public alias for the debug UI to call without duplicating the
/// provider-aware temperature extraction logic.
#[cfg(feature = "ui")]
pub(crate) fn extract_temperature_for_debug(
    body: &serde_json::Value,
    provider: Option<crate::format::Provider>,
) -> Option<f64> {
    extract_temperature(body, provider)
}

fn extract_temperature(
    body: &serde_json::Value,
    provider: Option<crate::format::Provider>,
) -> Option<f64> {
    if provider == Some(crate::format::Provider::Gemini) {
        return body
            .get("generationConfig")
            .and_then(|v| v.get("temperature"))
            .and_then(|v| v.as_f64());
    }
    body.get("temperature").and_then(|v| v.as_f64())
}

fn f64_matches(pattern: &F64Match, value: f64) -> bool {
    match pattern {
        // Plain `==` on `f64` is sufficient here: YAML literal round-trip
        // is exact, and our load-time validation rejects NaN/Inf, so both
        // sides are finite and binary-equal when the user wrote the same
        // literal. Use a range match for tolerance-based comparisons.
        F64Match::Exact(target) => value == *target,
        F64Match::Range(range) => {
            if let Some(min) = range.min {
                if value < min {
                    return false;
                }
            }
            if let Some(max) = range.max {
                if value > max {
                    return false;
                }
            }
            true
        }
    }
}

pub(crate) fn string_matches(pattern: &StringMatch, haystack: &str) -> bool {
    match pattern {
        StringMatch::Substring(s) => haystack.contains(s.as_str()),
        StringMatch::Regex(r) => r.is_match(haystack),
    }
}

// --- YAML loading ---

/// Load and validate fixtures from a single YAML file.
pub fn load_yaml_file(path: &Path) -> Result<Vec<Fixture>, Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let file: FixtureFile = serde_yaml_ng::from_str(&content)
        .map_err(|e| format!("Invalid YAML in {}: {}", path.display(), e))?;

    let mut fixtures = file.fixtures;
    for (i, fixture) in fixtures.iter_mut().enumerate() {
        fixture
            .validate()
            .map_err(|e| format!("Fixture #{} in {}: {}", i + 1, path.display(), e))?;
    }

    Ok(fixtures)
}

/// Re-read and concatenate fixtures from a list of source paths (files or directories).
/// Used by hot-reload to rebuild the fixture list on file change or SIGHUP.
pub(crate) fn reload_sources(sources: &[std::path::PathBuf]) -> Result<Vec<Fixture>, String> {
    let mut fixtures = Vec::new();
    for path in sources {
        let loaded = if path.is_dir() {
            load_yaml_dir(path).map_err(|e| format!("{}: {}", path.display(), e))?
        } else {
            load_yaml_file(path).map_err(|e| format!("{}: {}", path.display(), e))?
        };
        fixtures.extend(loaded);
    }
    Ok(fixtures)
}

/// Load and validate fixtures from all `.yaml`/`.yml` files in a directory (sorted by filename).
pub fn load_yaml_dir(dir: &Path) -> Result<Vec<Fixture>, Box<dyn std::error::Error>> {
    let mut entries: Vec<_> = std::fs::read_dir(dir)
        .map_err(|e| format!("Failed to read directory {}: {}", dir.display(), e))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| format!("Error reading directory entry in {}: {}", dir.display(), e))?
        .into_iter()
        .filter(|e| {
            let is_file = e.file_type().map(|ft| ft.is_file()).unwrap_or(false);
            if !is_file {
                return false;
            }
            let name = e.file_name();
            let name = name.to_string_lossy();
            name.ends_with(".yaml") || name.ends_with(".yml")
        })
        .collect();

    entries.sort_by_key(|e| e.file_name());

    let mut all_fixtures = Vec::new();
    for entry in entries {
        let fixtures = load_yaml_file(&entry.path())?;
        all_fixtures.extend(fixtures);
    }

    Ok(all_fixtures)
}

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

    // --- YAML parsing tests ---

    #[test]
    fn should_parse_simple_text_fixture() {
        let yaml = r#"
fixtures:
  - match:
      user_message: "hello"
    response:
      content: "Hi there!"
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(file.fixtures.len(), 1);
        let f = &file.fixtures[0];
        assert_eq!(
            f.match_rule.as_ref().unwrap().user_message,
            Some(StringMatch::Substring("hello".to_string()))
        );
        assert_eq!(
            f.response.as_ref().unwrap().content.as_deref(),
            Some("Hi there!")
        );
    }

    #[test]
    fn should_parse_regex_match() {
        let yaml = r#"
fixtures:
  - match:
      user_message:
        regex: "hello \\w+"
    response:
      content: "matched regex"
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let f = &file.fixtures[0];
        match &f.match_rule.as_ref().unwrap().user_message {
            Some(StringMatch::Regex(r)) => assert_eq!(r.regex, "hello \\w+"),
            other => panic!("Expected Regex, got {:?}", other),
        }
    }

    #[test]
    fn should_parse_error_fixture() {
        let yaml = r#"
fixtures:
  - match:
      model: "fail-model"
    error:
      status: 429
      message: "Rate limit exceeded"
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let f = &file.fixtures[0];
        assert!(f.response.is_none());
        let err = f.error.as_ref().unwrap();
        assert_eq!(err.status, 429);
        assert_eq!(err.message, "Rate limit exceeded");
    }

    #[test]
    fn should_parse_failure_config() {
        let yaml = r#"
fixtures:
  - match:
      user_message: "slow"
    response:
      content: "delayed"
    failure:
      latency_ms: 5000
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let f = &file.fixtures[0];
        assert_eq!(f.failure.as_ref().unwrap().latency_ms, Some(5000));
    }

    #[test]
    fn should_parse_streaming_config() {
        let yaml = r#"
fixtures:
  - match:
      user_message: "stream"
    response:
      content: "streamed"
    streaming:
      latency: 50
      chunk_size: 10
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let f = &file.fixtures[0];
        let s = f.streaming.as_ref().unwrap();
        assert_eq!(s.latency, Some(50));
        assert_eq!(s.chunk_size, Some(10));
    }

    #[test]
    fn should_parse_tool_call_response() {
        let yaml = r#"
fixtures:
  - match:
      user_message: "weather"
    response:
      tool_calls:
        - name: get_weather
          arguments:
            location: "San Francisco"
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let tc = &file.fixtures[0]
            .response
            .as_ref()
            .unwrap()
            .tool_calls
            .as_ref()
            .unwrap()[0];
        assert_eq!(tc.name, "get_weather");
        assert_eq!(tc.arguments["location"], "San Francisco");
    }

    #[test]
    fn should_parse_provider_specific_fixture() {
        let yaml = r#"
fixtures:
  - match:
      user_message: "test"
    provider: anthropic
    response:
      content: "response"
      stop_reason: end_turn
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let f = &file.fixtures[0];
        assert_eq!(f.provider, Some(crate::format::Provider::Anthropic));
    }

    #[test]
    fn should_reject_invalid_yaml() {
        let yaml = "not: [valid: yaml: {{{";
        let result: Result<FixtureFile, _> = serde_yaml_ng::from_str(yaml);
        assert!(result.is_err());
    }

    #[test]
    fn should_parse_model_match() {
        let yaml = r#"
fixtures:
  - match:
      model: "gpt-4"
      user_message: "hello"
    response:
      content: "hi"
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let m = file.fixtures[0].match_rule.as_ref().unwrap();
        assert_eq!(m.model, Some(StringMatch::Substring("gpt-4".to_string())));
    }

    #[test]
    fn should_parse_catch_all_fixture() {
        let yaml = r#"
fixtures:
  - response:
      content: "default response"
"#;
        let file: FixtureFile = serde_yaml_ng::from_str(yaml).unwrap();
        let f = &file.fixtures[0];
        assert!(f.match_rule.is_none());
    }

    // --- Validation tests ---

    #[test]
    fn should_reject_fixture_with_both_error_and_response() {
        let mut f = Fixture {
            response: Some(FixtureResponse {
                content: Some("hi".to_string()),
                ..Default::default()
            }),
            error: Some(FixtureError {
                status: 500,
                message: "fail".to_string(),
                headers: HashMap::new(),
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("mutually exclusive"));
    }

    #[test]
    fn should_reject_fixture_with_failure_but_no_response() {
        let mut f = Fixture {
            failure: Some(FailureConfig {
                latency_ms: Some(1000),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("requires response"));
    }

    #[test]
    fn should_reject_fixture_with_error_and_failure() {
        let mut f = Fixture {
            error: Some(FixtureError {
                status: 429,
                message: "rate limit".to_string(),
                headers: HashMap::new(),
            }),
            failure: Some(FailureConfig {
                latency_ms: Some(1000),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
    }

    #[test]
    fn should_reject_fixture_with_no_response_and_no_error() {
        let mut f = Fixture {
            match_rule: Some(FixtureMatch::default()),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must have either"));
    }

    #[test]
    fn should_reject_failure_probability_above_one() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                probability: Some(2.0),
                ..Default::default()
            });
        let err = f.validate().unwrap_err();
        assert!(
            err.contains("probability must be a finite number in"),
            "got: {}",
            err
        );
    }

    #[test]
    fn should_reject_failure_probability_below_zero() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                probability: Some(-0.5),
                ..Default::default()
            });
        let err = f.validate().unwrap_err();
        assert!(
            err.contains("probability must be a finite number in"),
            "got: {}",
            err
        );
    }

    #[test]
    fn should_reject_failure_probability_nan() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                probability: Some(f32::NAN),
                ..Default::default()
            });
        let err = f.validate().unwrap_err();
        assert!(
            err.contains("probability must be a finite number in"),
            "got: {}",
            err
        );
    }

    #[test]
    fn should_reject_latency_jitter_without_streaming_latency() {
        // No streaming block at all.
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                latency_jitter_ms: Some(5),
                ..Default::default()
            });
        let err = f.validate().unwrap_err();
        assert!(err.contains("latency_jitter_ms requires"), "got: {}", err);
    }

    #[test]
    fn should_reject_latency_jitter_with_zero_streaming_latency() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_streaming(Some(0), Some(10))
            .with_failure(FailureConfig {
                latency_jitter_ms: Some(5),
                ..Default::default()
            });
        let err = f.validate().unwrap_err();
        assert!(err.contains("latency_jitter_ms requires"), "got: {}", err);
    }

    #[test]
    fn should_accept_zero_latency_jitter_without_streaming() {
        // `latency_jitter_ms: Some(0)` is a no-op — ChaosPlan collapses it
        // to None — so it should NOT require a base streaming.latency.
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                latency_jitter_ms: Some(0),
                ..Default::default()
            });
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_reject_latency_jitter_above_one_hour_cap() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_streaming(Some(10), Some(5))
            .with_failure(FailureConfig {
                // 1 hour = 3_600_000 ms — one more than the cap.
                latency_jitter_ms: Some(3_600_001),
                ..Default::default()
            });
        let err = f.validate().unwrap_err();
        assert!(err.contains("latency_jitter_ms must be <="), "got: {}", err);
    }

    #[test]
    fn should_accept_latency_jitter_at_one_hour_cap() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_streaming(Some(10), Some(5))
            .with_failure(FailureConfig {
                latency_jitter_ms: Some(3_600_000),
                ..Default::default()
            });
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_accept_latency_jitter_with_positive_streaming_latency() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_streaming(Some(10), Some(5))
            .with_failure(FailureConfig {
                latency_jitter_ms: Some(5),
                ..Default::default()
            });
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_accept_failure_probability_at_boundaries() {
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                probability: Some(0.0),
                ..Default::default()
            });
        assert!(f.validate().is_ok());
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_failure(FailureConfig {
                probability: Some(1.0),
                ..Default::default()
            });
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_accept_valid_error_fixture() {
        let mut f = Fixture::new().with_error(429, "rate limit");
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_accept_valid_response_fixture() {
        let mut f = Fixture::new().respond_with_content("hi");
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_reject_invalid_regex() {
        let mut f = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::regex("[invalid")),
                model: None,
                ..Default::default()
            }),
            response: Some(FixtureResponse {
                content: Some("hi".to_string()),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("regex"));
    }

    // --- Matching tests ---

    #[test]
    fn should_match_substring_user_message() {
        let fixtures = vec![Fixture::new()
            .match_user_message("hello")
            .respond_with_content("hi")];
        let result = match_fixture(&fixtures, "say hello world", None, None, None);
        assert!(result.is_some());
    }

    #[test]
    fn should_not_match_wrong_substring() {
        let fixtures = vec![Fixture::new()
            .match_user_message("goodbye")
            .respond_with_content("bye")];
        let result = match_fixture(&fixtures, "say hello world", None, None, None);
        assert!(result.is_none());
    }

    #[test]
    fn should_match_regex_user_message() {
        let fixtures = vec![Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::regex("hello \\w+")),
                model: None,
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("matched")
        }];
        let result = match_fixture(&fixtures, "hello world", None, None, None);
        assert!(result.is_some());
    }

    #[test]
    fn should_match_model() {
        let fixtures = vec![Fixture::new()
            .match_model("gpt-4")
            .respond_with_content("gpt4 response")];
        let result = match_fixture(&fixtures, "anything", Some("gpt-4-turbo"), None, None);
        assert!(result.is_some());
    }

    #[test]
    fn should_match_first_fixture_wins() {
        let fixtures = vec![
            Fixture::new()
                .match_user_message("hello")
                .respond_with_content("first"),
            Fixture::new()
                .match_user_message("hello")
                .respond_with_content("second"),
        ];
        let result = match_fixture(&fixtures, "hello", None, None, None);
        assert_eq!(
            result
                .unwrap()
                .response
                .as_ref()
                .unwrap()
                .content
                .as_deref(),
            Some("first")
        );
    }

    #[test]
    fn should_match_catch_all() {
        let fixtures = vec![Fixture::new().respond_with_content("default")];
        let result = match_fixture(&fixtures, "anything at all", None, None, None);
        assert!(result.is_some());
    }

    #[test]
    fn should_filter_by_provider() {
        let fixtures = vec![Fixture {
            provider: Some(crate::format::Provider::Anthropic),
            ..Fixture::new().respond_with_content("anthropic only")
        }];
        let result = match_fixture(
            &fixtures,
            "hello",
            None,
            Some(crate::format::Provider::Anthropic),
            None,
        );
        assert!(result.is_some());
        let result = match_fixture(
            &fixtures,
            "hello",
            None,
            Some(crate::format::Provider::OpenAI),
            None,
        );
        assert!(result.is_none());
    }

    // --- Builder API tests ---

    #[test]
    fn should_build_fixture_programmatically() {
        let mut f = Fixture::new()
            .match_user_message("hello")
            .respond_with_content("Hi there!");
        assert!(f.validate().is_ok());
        assert_eq!(
            f.response.as_ref().unwrap().content.as_deref(),
            Some("Hi there!")
        );
    }

    #[test]
    fn should_build_error_fixture_programmatically() {
        let mut f = Fixture::new()
            .match_model("fail-model")
            .with_error(429, "Rate limited");
        assert!(f.validate().is_ok());
        assert_eq!(f.error.as_ref().unwrap().status, 429);
    }

    #[test]
    fn should_use_default_trait_for_fixture() {
        let f = Fixture::default();
        assert!(f.response.is_none());
        assert!(f.error.is_none());
        assert!(f.match_rule.is_none());
    }

    #[test]
    fn should_compare_regex_match_by_pattern_string() {
        let a = RegexMatch {
            regex: "hello".to_string(),
            compiled: None,
        };
        let b = RegexMatch {
            regex: "hello".to_string(),
            compiled: None,
        };
        let c = RegexMatch {
            regex: "world".to_string(),
            compiled: None,
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn should_reject_response_with_both_content_and_tool_calls() {
        let mut f = Fixture {
            response: Some(FixtureResponse {
                content: Some("text".to_string()),
                tool_calls: Some(vec![ToolCall {
                    name: "func".to_string(),
                    arguments: serde_json::json!({}),
                }]),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("mutually exclusive"));
    }

    #[test]
    fn should_reject_response_with_neither_content_nor_tool_calls() {
        let mut f = Fixture {
            response: Some(FixtureResponse::default()),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("response must have"));
    }

    #[test]
    fn should_reject_non_finite_embedding_values() {
        let mut f = Fixture::new().respond_with_embedding(vec![0.1, f64::NAN, 0.3]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must be finite"));
    }

    #[test]
    fn should_reject_infinite_embedding_values() {
        let mut f = Fixture::new().respond_with_embedding(vec![0.1, f64::INFINITY]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must be finite"));
    }

    #[test]
    fn should_reject_zero_chunk_size() {
        let mut f = Fixture {
            response: Some(FixtureResponse {
                content: Some("hi".to_string()),
                ..Default::default()
            }),
            streaming: Some(StreamingConfig {
                latency: None,
                chunk_size: Some(0),
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("chunk_size must be > 0"));
    }

    #[test]
    fn should_compile_model_regex_on_validate() {
        let mut f = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: None,
                model: Some(StringMatch::regex("gpt-4.*")),
                ..Default::default()
            }),
            response: Some(FixtureResponse {
                content: Some("hi".to_string()),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        assert!(f.validate().is_ok());
        // After validation, the compiled regex should be used for matching
        let fixtures = vec![f];
        let result = match_fixture(&fixtures, "hello", Some("gpt-4-turbo"), None, None);
        assert!(result.is_some());
    }

    #[test]
    fn should_match_compiled_user_message_regex() {
        let mut f = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::regex("he.*ld")),
                model: None,
                ..Default::default()
            }),
            response: Some(FixtureResponse {
                content: Some("matched".to_string()),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        // Validate to compile the regex
        assert!(f.validate().is_ok());
        // Now match against it -- should use the compiled (Some) path
        let fixtures = vec![f];
        let result = match_fixture(&fixtures, "hello world", None, None, None);
        assert!(result.is_some());
    }

    #[test]
    fn should_reject_invalid_model_regex() {
        let mut f = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: None,
                model: Some(StringMatch::regex("[invalid")),
                ..Default::default()
            }),
            response: Some(FixtureResponse {
                content: Some("hi".to_string()),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("model"));
    }

    #[test]
    fn should_not_match_model_when_no_model_provided() {
        let fixtures = vec![Fixture::new()
            .match_model("gpt-4")
            .respond_with_content("gpt4 only")];
        // model is None: should NOT match a fixture that requires a model
        let result = match_fixture(&fixtures, "hello", None, None, None);
        assert!(result.is_none());
    }

    #[test]
    fn should_use_regex_fallback_for_unvalidated_fixture() {
        // Fixture with valid regex that was NOT validated (no compile() called).
        // This exercises the fallback path in RegexMatch::is_match.
        let fixtures = vec![Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::regex("hel+o")),
                model: None,
                ..Default::default()
            }),
            response: Some(FixtureResponse {
                content: Some("matched".to_string()),
                ..Default::default()
            }),
            ..Fixture::new()
        }];
        let result = match_fixture(&fixtures, "helllo world", None, None, None);
        assert!(result.is_some());
    }

    // --- YAML file loading tests ---

    #[test]
    fn should_load_yaml_file() {
        let dir = std::env::temp_dir().join("llmposter_test_load");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("test.yaml");
        std::fs::write(
            &file,
            r#"
fixtures:
  - match:
      user_message: "test"
    response:
      content: "loaded from file"
"#,
        )
        .unwrap();
        let fixtures = load_yaml_file(&file).unwrap();
        assert_eq!(fixtures.len(), 1);
        assert_eq!(
            fixtures[0].response.as_ref().unwrap().content.as_deref(),
            Some("loaded from file")
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn should_load_yaml_dir() {
        let dir = std::env::temp_dir().join("llmposter_test_dir");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("a.yaml"),
            "fixtures:\n  - match:\n      user_message: \"a\"\n    response:\n      content: \"a\"",
        )
        .unwrap();
        std::fs::write(
            dir.join("b.yml"),
            "fixtures:\n  - match:\n      user_message: \"b\"\n    response:\n      content: \"b\"",
        )
        .unwrap();
        std::fs::write(dir.join("not_yaml.txt"), "ignored").unwrap();
        std::fs::create_dir_all(dir.join("subdir")).unwrap();
        let fixtures = load_yaml_dir(&dir).unwrap();
        assert_eq!(fixtures.len(), 2);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn should_return_error_for_invalid_yaml_file() {
        let dir = std::env::temp_dir().join("llmposter_test_invalid");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("bad.yaml");
        std::fs::write(&file, "not: [valid: {{{").unwrap();
        let result = load_yaml_file(&file);
        assert!(result.is_err());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn should_return_error_for_missing_file() {
        let result = load_yaml_file(Path::new("/nonexistent/file.yaml"));
        assert!(result.is_err());
    }

    #[test]
    fn should_validate_fixtures_on_load() {
        let dir = std::env::temp_dir().join("llmposter_test_validate_load");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("invalid_fixture.yaml");
        std::fs::write(
            &file,
            r#"
fixtures:
  - match:
      user_message: "test"
    response:
      content: "hi"
    error:
      status: 500
      message: "also error"
"#,
        )
        .unwrap();
        let result = load_yaml_file(&file);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("mutually exclusive"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn should_reject_oversized_regex_at_validation() {
        // A regex with a huge repetition count that would blow up the DFA
        let huge_pattern = format!("a{{{}}}", 999_999);
        let mut f = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::regex(&huge_pattern)),
                model: None,
                ..Default::default()
            }),
            response: Some(FixtureResponse {
                content: Some("hi".to_string()),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err(), "oversized regex should be rejected");
    }

    #[test]
    fn should_return_false_for_oversized_regex_in_fallback() {
        let huge_pattern = format!("a{{{}}}", 999_999);
        let rm = RegexMatch {
            regex: huge_pattern,
            compiled: None, // No pre-compilation — exercises fallback path
        };
        // Should return false, not panic or OOM
        assert!(!rm.is_match("aaaa"));
    }

    #[test]
    fn should_reject_scalar_tool_call_arguments() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "test".to_string(),
            arguments: serde_json::json!("not an object"),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must be a JSON object"));
    }

    #[test]
    fn should_reject_array_tool_call_arguments() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "test".to_string(),
            arguments: serde_json::json!([1, 2, 3]),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must be a JSON object"));
    }

    #[test]
    fn should_accept_object_tool_call_arguments() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "test".to_string(),
            arguments: serde_json::json!({"key": "value"}),
        }]);
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_reject_blank_tool_call_name() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "".to_string(),
            arguments: serde_json::json!({"key": "value"}),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("name must not be empty"));
    }

    #[test]
    fn should_reject_whitespace_only_tool_call_name() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "   ".to_string(),
            arguments: serde_json::json!({"key": "value"}),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("name must not be empty"));
    }

    #[test]
    fn should_reject_non_error_status_codes() {
        // 200, 301, etc. should be rejected — only 400-599 for error simulation
        for status in [200, 204, 301, 302] {
            let mut f = Fixture::new().with_error(status, "test");
            let result = f.validate();
            assert!(result.is_err(), "status {} should be rejected", status);
            assert!(result.unwrap_err().contains("400-599"));
        }
    }

    #[test]
    fn should_accept_error_status_codes() {
        for status in [400, 401, 403, 404, 429, 500, 502, 503, 529] {
            let mut f = Fixture::new().with_error(status, "test");
            assert!(f.validate().is_ok(), "status {} should be accepted", status);
        }
    }

    #[test]
    fn should_reject_empty_user_message_substring() {
        let mut f = Fixture::new()
            .match_user_message("")
            .respond_with_content("ok");
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must not be empty"));
    }

    #[test]
    fn should_reject_empty_model_substring() {
        let mut f = Fixture::new().match_model("").respond_with_content("ok");
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must not be empty"));
    }

    #[test]
    fn should_reject_empty_user_message_regex() {
        let mut f = Fixture::new().respond_with_content("ok");
        let m = f.match_rule.get_or_insert_with(FixtureMatch::default);
        m.user_message = Some(StringMatch::regex(""));
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("regex must not be empty"));
    }

    #[test]
    fn should_reject_empty_model_regex() {
        let mut f = Fixture::new().respond_with_content("ok");
        let m = f.match_rule.get_or_insert_with(FixtureMatch::default);
        m.model = Some(StringMatch::regex(""));
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("regex must not be empty"));
    }

    #[test]
    fn should_reject_unknown_yaml_fields() {
        let yaml =
            "fixtures:\n  - match:\n      user_mesage: typo\n    response:\n      content: ok";
        let result: Result<FixtureFile, _> = serde_yaml_ng::from_str(yaml);
        assert!(result.is_err(), "typo field 'user_mesage' must be rejected");
    }

    #[test]
    fn should_reject_unknown_fixture_fields() {
        let yaml = "fixtures:\n  - unknown_field: true\n    response:\n      content: ok";
        let result: Result<FixtureFile, _> = serde_yaml_ng::from_str(yaml);
        assert!(result.is_err(), "unknown fixture field must be rejected");
    }

    #[test]
    fn should_set_stop_reason_via_builder() {
        let f = Fixture::new()
            .respond_with_content("test")
            .with_stop_reason("max_tokens");
        assert_eq!(
            f.response.as_ref().unwrap().stop_reason.as_deref(),
            Some("max_tokens")
        );
    }

    #[test]
    fn should_set_finish_reason_via_builder() {
        let f = Fixture::new()
            .respond_with_content("test")
            .with_finish_reason("length");
        assert_eq!(
            f.response.as_ref().unwrap().finish_reason.as_deref(),
            Some("length")
        );
    }

    #[test]
    fn should_set_stop_reason_on_empty_response() {
        let f = Fixture::new().with_stop_reason("end_turn");
        assert!(f.response.is_some());
        assert_eq!(
            f.response.as_ref().unwrap().stop_reason.as_deref(),
            Some("end_turn")
        );
    }

    #[test]
    fn should_set_finish_reason_on_empty_response() {
        let f = Fixture::new().with_finish_reason("stop");
        assert!(f.response.is_some());
        assert_eq!(
            f.response.as_ref().unwrap().finish_reason.as_deref(),
            Some("stop")
        );
    }

    #[test]
    fn should_warn_but_accept_truncate_without_streaming_config() {
        // Warning is printed but validation still passes — no streaming is just a no-op.
        let mut f = Fixture {
            failure: Some(FailureConfig {
                truncate_after_frames: Some(2),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_warn_but_accept_disconnect_without_streaming_config() {
        let mut f = Fixture {
            failure: Some(FailureConfig {
                disconnect_after_ms: Some(100),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_warn_but_accept_duplicate_frames_without_streaming_config() {
        // Matches the sibling warnings above: duplicate_frames on a
        // non-streaming fixture is a no-op, validated-but-warned.
        let mut f = Fixture {
            failure: Some(FailureConfig {
                duplicate_frames: Some(true),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_accept_duplicate_frames_with_streaming_config() {
        // Happy path: duplicate_frames alongside streaming is fine.
        let mut f = Fixture::new()
            .respond_with_content("ok")
            .with_streaming(Some(5), Some(10))
            .with_failure(FailureConfig {
                duplicate_frames: Some(true),
                ..Default::default()
            });
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_warn_but_accept_truncate_on_tool_calls_fixture() {
        // After the fix, tool_calls fixtures also produce the warning.
        let mut f = Fixture {
            failure: Some(FailureConfig {
                truncate_after_frames: Some(2),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_tool_calls(vec![ToolCall {
                name: "get_weather".to_string(),
                arguments: serde_json::json!({"location": "SF"}),
            }])
        };
        assert!(f.validate().is_ok());
    }

    #[test]
    fn should_skip_compile_when_already_compiled() {
        // Calling validate() twice must not error — compile() returns Ok early.
        let mut f = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::Regex(RegexMatch {
                    regex: "hello \\w+".to_string(),
                    compiled: None,
                })),
                model: None,
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        assert!(f.validate().is_ok());
        assert!(f.validate().is_ok()); // second call hits the early-return branch
    }

    #[test]
    fn should_reject_empty_tool_calls_vec() {
        let mut f = Fixture {
            response: Some(FixtureResponse {
                tool_calls: Some(vec![]),
                ..Default::default()
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must not be empty"));
    }

    #[test]
    fn should_reject_number_tool_call_arguments() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "test".to_string(),
            arguments: serde_json::json!(42),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("must be a JSON object, got number"));
    }

    #[test]
    fn should_reject_bool_tool_call_arguments() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "test".to_string(),
            arguments: serde_json::json!(true),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("must be a JSON object, got boolean"));
    }

    #[test]
    fn should_reject_null_tool_call_arguments() {
        let mut f = Fixture::new().respond_with_tool_calls(vec![ToolCall {
            name: "test".to_string(),
            arguments: serde_json::json!(null),
        }]);
        let result = f.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("must be a JSON object, got null"));
    }

    #[test]
    fn should_reject_duplicate_header_name_in_validate() {
        let mut f = Fixture {
            error: Some(FixtureError {
                status: 429,
                message: "rate limit".to_string(),
                headers: HashMap::from([
                    ("x-custom".to_string(), "a".to_string()),
                    ("X-Custom".to_string(), "b".to_string()),
                ]),
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("duplicate"));
    }

    #[test]
    fn should_reject_invalid_header_name_in_validate() {
        let mut f = Fixture {
            error: Some(FixtureError {
                status: 429,
                message: "rate limit".to_string(),
                headers: HashMap::from([("invalid name!".to_string(), "value".to_string())]),
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid error header name"));
    }

    #[test]
    fn should_reject_invalid_header_value_in_validate() {
        let mut f = Fixture {
            error: Some(FixtureError {
                status: 429,
                message: "rate limit".to_string(),
                headers: HashMap::from([("x-custom".to_string(), "\x00bad".to_string())]),
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid error header value"));
    }

    #[test]
    fn should_reject_streaming_config_on_error_fixture() {
        let mut f = Fixture {
            error: Some(FixtureError {
                status: 429,
                message: "rate limit".to_string(),
                headers: HashMap::new(),
            }),
            streaming: Some(StreamingConfig {
                latency: None,
                chunk_size: Some(10),
            }),
            ..Fixture::new()
        };
        let result = f.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("no effect on error-only"));
    }

    // --- Extraction branch coverage ---

    /// Build a `MatchContext` for direct-to-`fixture_matches` unit
    /// tests. Only the JSONPath fallback tests call this today, so
    /// gate it behind the same feature to avoid dead-code warnings
    /// under `--no-default-features`.
    #[cfg(feature = "jsonpath")]
    fn ctx<'a>(
        body: &'a serde_json::Value,
        provider: Option<crate::format::Provider>,
    ) -> MatchContext<'a> {
        static EMPTY_HEADERS: std::sync::OnceLock<HashMap<String, String>> =
            std::sync::OnceLock::new();
        let headers = EMPTY_HEADERS.get_or_init(HashMap::new);
        MatchContext::new("", None, provider, None, headers, body)
    }

    #[test]
    fn extract_system_prompt_anthropic_array_without_text_blocks() {
        // Array with no `text`-bearing blocks → None.
        let body = serde_json::json!({
            "system": [{"type": "image", "data": "..."}]
        });
        assert_eq!(
            extract_system_prompt(&body, Some(crate::format::Provider::Anthropic)),
            None
        );
    }

    #[test]
    fn extract_system_prompt_anthropic_array_of_strings_ignored() {
        // Anthropic top-level system is neither string nor array → None.
        let body = serde_json::json!({"system": 42});
        assert_eq!(
            extract_system_prompt(&body, Some(crate::format::Provider::Anthropic)),
            None
        );
    }

    #[test]
    fn extract_system_prompt_gemini_with_empty_parts_returns_none() {
        // systemInstruction present but parts is empty or has no text.
        let body = serde_json::json!({
            "systemInstruction": {"parts": []}
        });
        assert_eq!(
            extract_system_prompt(&body, Some(crate::format::Provider::Gemini)),
            None
        );

        let body = serde_json::json!({
            "systemInstruction": {"parts": [{"data": "no text field"}]}
        });
        assert_eq!(
            extract_system_prompt(&body, Some(crate::format::Provider::Gemini)),
            None
        );
    }

    #[test]
    fn extract_system_prompt_gemini_without_system_instruction_returns_none() {
        let body = serde_json::json!({
            "contents": [{"role": "user", "parts": [{"text": "hi"}]}]
        });
        assert_eq!(
            extract_system_prompt(&body, Some(crate::format::Provider::Gemini)),
            None
        );
    }

    #[test]
    fn extract_system_prompt_openai_content_array_without_text_parts() {
        let body = serde_json::json!({
            "messages": [
                {"role": "system", "content": [{"type": "image_url", "image_url": {}}]}
            ]
        });
        assert_eq!(extract_system_prompt(&body, None), None);
    }

    #[test]
    fn extract_system_prompt_multiple_openai_system_messages_concatenated() {
        let body = serde_json::json!({
            "messages": [
                {"role": "system", "content": "first"},
                {"role": "user", "content": "hi"},
                {"role": "system", "content": "second"}
            ]
        });
        assert_eq!(
            extract_system_prompt(&body, None).as_deref(),
            Some("first\nsecond")
        );
    }

    #[test]
    fn extract_tool_names_missing_tools_field_returns_empty() {
        let body = serde_json::json!({"messages": []});
        assert!(extract_tool_names(&body, None).is_empty());
    }

    #[test]
    fn extract_tool_names_openai_fallback_to_tools_name_field() {
        // When `function.name` is missing, fall through to `tools[].name`.
        let body = serde_json::json!({
            "tools": [{"name": "plain_tool"}]
        });
        let names = extract_tool_names(&body, None);
        assert_eq!(names, vec!["plain_tool"]);
    }

    #[test]
    fn extract_tool_names_gemini_without_function_declarations() {
        let body = serde_json::json!({
            "tools": [{"retrieval": {"source": "..."}}]
        });
        assert!(extract_tool_names(&body, Some(crate::format::Provider::Gemini)).is_empty());
    }

    #[test]
    fn extract_temperature_gemini_nested_path() {
        let body = serde_json::json!({
            "generationConfig": {"temperature": 0.42}
        });
        assert_eq!(
            extract_temperature(&body, Some(crate::format::Provider::Gemini)),
            Some(0.42)
        );
    }

    #[test]
    fn extract_temperature_gemini_missing_generation_config() {
        let body = serde_json::json!({"contents": []});
        assert_eq!(
            extract_temperature(&body, Some(crate::format::Provider::Gemini)),
            None
        );
    }

    #[test]
    fn extract_temperature_non_gemini_top_level() {
        let body = serde_json::json!({"temperature": 0.8});
        assert_eq!(extract_temperature(&body, None), Some(0.8));
        assert_eq!(
            extract_temperature(&body, Some(crate::format::Provider::OpenAI)),
            Some(0.8)
        );
    }

    #[test]
    fn f64_matches_exact_and_range_bounds() {
        assert!(f64_matches(&F64Match::Exact(0.7), 0.7));
        assert!(!f64_matches(&F64Match::Exact(0.7), 0.8));
        let rng = F64Match::Range(F64Range {
            min: Some(0.5),
            max: Some(1.0),
        });
        assert!(f64_matches(&rng, 0.5));
        assert!(f64_matches(&rng, 0.75));
        assert!(f64_matches(&rng, 1.0));
        assert!(!f64_matches(&rng, 0.4));
        assert!(!f64_matches(&rng, 1.1));

        // Half-open ranges.
        let only_min = F64Match::Range(F64Range {
            min: Some(0.5),
            max: None,
        });
        assert!(f64_matches(&only_min, 5.0));
        assert!(!f64_matches(&only_min, 0.4));

        let only_max = F64Match::Range(F64Range {
            min: None,
            max: Some(0.5),
        });
        assert!(f64_matches(&only_max, 0.4));
        assert!(!f64_matches(&only_max, 0.6));
    }

    // --- JSONPath on-the-fly fallback (for programmatic fixtures
    // that skipped validate()) ---
    #[cfg(feature = "jsonpath")]
    #[test]
    fn body_jsonpath_matches_via_onthefly_compile_when_not_validated() {
        // Build a Fixture via the builder API without calling
        // `validate()` — the fallback compile path should still
        // honor the JSONPath constraint.
        let f = Fixture::new()
            .match_body_jsonpath("$.foo")
            .respond_with_content("ok");
        let body = serde_json::json!({"foo": "bar"});
        let c = ctx(&body, None);
        assert!(fixture_matches(&f, &c));

        // Non-matching request body — should fall through the
        // is_empty branch and return false.
        let body = serde_json::json!({"other": "value"});
        let c = ctx(&body, None);
        assert!(!fixture_matches(&f, &c));
    }

    #[cfg(feature = "jsonpath")]
    #[test]
    fn body_jsonpath_invalid_expression_fails_match_via_fallback() {
        // Un-validated fixture whose source string is syntactically
        // invalid. Hot path emits a warning and returns false
        // instead of silently matching.
        let f = Fixture::new()
            .match_body_jsonpath("$[not-valid")
            .respond_with_content("ok");
        let body = serde_json::json!({"foo": 1});
        let c = ctx(&body, None);
        assert!(!fixture_matches(&f, &c));
    }

    // Helper to build a MatchContext for direct unit tests that don't
    // require the jsonpath feature.
    fn make_ctx<'a>(
        user_message: &'a str,
        body: &'a serde_json::Value,
        provider: Option<crate::format::Provider>,
        headers: &'a HashMap<String, String>,
    ) -> MatchContext<'a> {
        MatchContext::new(user_message, None, provider, None, headers, body)
    }

    // --- evaluate_fixture_fields coverage ---

    #[test]
    fn should_return_empty_results_for_bare_fixture_with_no_match_rule() {
        // A fixture with no match_rule should return early with empty results.
        let fixture = Fixture::new().respond_with_content("default");
        let body = serde_json::json!({"messages": [{"role": "user", "content": "hello"}]});
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = make_ctx("hello", &body, None, headers);
        let results = evaluate_fixture_fields(&fixture, &ctx);
        // No match_rule → no fields evaluated → empty results.
        assert!(results.is_empty());
    }

    #[test]
    fn should_evaluate_metadata_number_coercion_in_fixture_fields() {
        // metadata value is a Number — should be coerced to string "42" and matched.
        let fixture = Fixture::new()
            .match_metadata("priority", "42")
            .respond_with_content("ok");
        let body = serde_json::json!({
            "metadata": {"priority": 42},
            "messages": [{"role": "user", "content": "hi"}]
        });
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = make_ctx("hi", &body, None, headers);
        let results = evaluate_fixture_fields(&fixture, &ctx);
        let md = results.iter().find(|r| r.field == "metadata").unwrap();
        assert!(
            md.passed,
            "number metadata should coerce to string and match"
        );
    }

    #[test]
    fn should_evaluate_metadata_bool_coercion_in_fixture_fields() {
        // metadata value is a Bool — should be coerced to string "true" and matched.
        let fixture = Fixture::new()
            .match_metadata("enabled", "true")
            .respond_with_content("ok");
        let body = serde_json::json!({
            "metadata": {"enabled": true},
            "messages": [{"role": "user", "content": "hi"}]
        });
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = make_ctx("hi", &body, None, headers);
        let results = evaluate_fixture_fields(&fixture, &ctx);
        let md = results.iter().find(|r| r.field == "metadata").unwrap();
        assert!(md.passed, "bool metadata should coerce to string and match");
    }

    #[test]
    fn should_evaluate_metadata_string_coercion_in_fixture_fields() {
        // metadata value is a String — direct match.
        let fixture = Fixture::new()
            .match_metadata("tier", "gold")
            .respond_with_content("ok");
        let body = serde_json::json!({
            "metadata": {"tier": "gold"},
            "messages": [{"role": "user", "content": "hi"}]
        });
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = make_ctx("hi", &body, None, headers);
        let results = evaluate_fixture_fields(&fixture, &ctx);
        let md = results.iter().find(|r| r.field == "metadata").unwrap();
        assert!(md.passed, "string metadata should match directly");
    }

    #[test]
    fn should_evaluate_metadata_null_falls_through_to_false_in_fixture_fields() {
        // metadata value is null — no coercion possible → passed: false.
        let fixture = Fixture::new()
            .match_metadata("tier", "gold")
            .respond_with_content("ok");
        let body = serde_json::json!({
            "metadata": {"tier": null},
            "messages": [{"role": "user", "content": "hi"}]
        });
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = make_ctx("hi", &body, None, headers);
        let results = evaluate_fixture_fields(&fixture, &ctx);
        let md = results.iter().find(|r| r.field == "metadata").unwrap();
        assert!(!md.passed, "null metadata value should yield passed: false");
    }

    // --- match_summary_for_diagnostic coverage ---

    #[test]
    fn should_return_any_request_summary_for_bare_fixture() {
        // Fixture with no match_rule → "(any request)".
        let fixture = Fixture::new().respond_with_content("default");
        let summary = match_summary_for_diagnostic(&fixture);
        assert_eq!(summary, "(any request)");
    }

    #[test]
    fn should_include_regex_user_message_in_summary() {
        // Fixture with a regex user_message → summary contains regex form.
        let fixture = Fixture {
            match_rule: Some(FixtureMatch {
                user_message: Some(StringMatch::regex("hel+o")),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        let summary = match_summary_for_diagnostic(&fixture);
        assert!(
            summary.contains("regex("),
            "expected regex notation in summary, got: {}",
            summary
        );
    }

    #[test]
    fn should_return_other_fields_only_for_match_rule_without_user_message_model_or_headers() {
        // match_rule present but no user_message, no model, no headers → "(other fields only)".
        let fixture = Fixture {
            match_rule: Some(FixtureMatch {
                temperature: Some(F64Match::Exact(0.5)),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        let summary = match_summary_for_diagnostic(&fixture);
        assert_eq!(summary, "(other fields only)");
    }

    // --- extract_system_prompt: OpenAI fallback None path ---

    #[test]
    fn extract_system_prompt_returns_none_when_no_system_message_in_array() {
        // All messages have role "user" — no system entry → None.
        let body = serde_json::json!({
            "messages": [
                {"role": "user", "content": "hello"},
                {"role": "assistant", "content": "hi"}
            ]
        });
        assert_eq!(extract_system_prompt(&body, None), None);
    }

    #[test]
    fn extract_system_prompt_returns_none_when_messages_absent() {
        // Body has no `messages` key at all → None.
        let body = serde_json::json!({"model": "gpt-4"});
        assert_eq!(extract_system_prompt(&body, None), None);
    }

    // --- JSONPath fallback: runtime evaluation error path ---

    #[cfg(feature = "jsonpath")]
    #[test]
    fn body_jsonpath_fallback_evaluation_error_returns_false() {
        // Construct a fixture with body_jsonpath set (compiled = None)
        // against a body that causes a runtime evaluation error.
        // We exercise the Err(_) => return false path (line 1433) by
        // building a fixture whose body_jsonpath is a valid expression
        // that the runtime rejects for a particular body shape.
        //
        // Use a fixture constructed directly so body_jsonpath_compiled
        // stays None (bypassing validate()) — mirrors the existing
        // body_jsonpath_matches_via_onthefly_compile_when_not_validated test.
        //
        // A JSONPath that returns all nulls → is_empty-or-all-null → false.
        let f = Fixture::new()
            .match_body_jsonpath("$.missing_field")
            .respond_with_content("ok");
        // Body has no `missing_field` — the path matches zero nodes.
        let body = serde_json::json!({"other": 1});
        let c = ctx(&body, None);
        assert!(
            !fixture_matches(&f, &c),
            "empty JSONPath result should not match"
        );
    }

    // --- evaluate_nearest_match: skip bare fixtures ---

    #[test]
    fn should_skip_bare_fixture_in_evaluate_nearest_match() {
        // A fixture with no match fields (catch-all) should be skipped in
        // evaluate_nearest_match (the `continue` branch for total_fields == 0).
        use std::sync::Arc;

        // One bare fixture (no match_rule) + one fixture with a match field.
        let bare = Arc::new(Fixture::new().respond_with_content("default"));
        let with_field = Arc::new(
            Fixture::new()
                .match_user_message("specific")
                .respond_with_content("ok"),
        );
        let fixture_set = crate::server::FixtureSet::new(vec![bare, with_field]);

        let body = serde_json::json!({"messages": [{"role": "user", "content": "hello"}]});
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = MatchContext::new("hello", None, None, None, headers, &body);

        // evaluate_nearest_match should skip the bare fixture and find the one with a field.
        let hint = evaluate_nearest_match(&fixture_set, &ctx);
        assert!(
            hint.is_some(),
            "should find nearest match from the fielded fixture"
        );
        assert_eq!(hint.unwrap().total_fields, 1);
    }

    // --- match_summary_for_diagnostic: regex model arm ---

    #[test]
    fn should_include_regex_model_in_summary() {
        // Fixture with a regex model → summary contains regex notation for model.
        let fixture = Fixture {
            match_rule: Some(FixtureMatch {
                model: Some(StringMatch::regex("gpt-4.*")),
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        let summary = match_summary_for_diagnostic(&fixture);
        assert!(
            summary.contains("regex("),
            "expected regex notation for model in summary, got: {}",
            summary
        );
        assert!(
            summary.contains("model"),
            "expected 'model' in summary, got: {}",
            summary
        );
    }

    // --- evaluate_fixture_fields: scenario with no required_state ---

    #[test]
    fn should_not_evaluate_scenario_field_when_required_state_is_none() {
        // Scenario block is present but required_state is None → no field result added.
        use crate::format::Provider;
        let fixture = Fixture {
            scenario: Some(ScenarioConfig {
                name: "flow".to_string(),
                required_state: None,
                set_state: Some("done".to_string()),
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        let body = serde_json::json!({"messages": [{"role": "user", "content": "hi"}]});
        static HEADERS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
        let headers = HEADERS.get_or_init(HashMap::new);
        let ctx = MatchContext::new("hi", None, Some(Provider::OpenAI), None, headers, &body);
        let results = evaluate_fixture_fields(&fixture, &ctx);
        // No scenario.required_state → no field pushed for it.
        assert!(
            results.iter().all(|r| r.field != "scenario.required_state"),
            "should not have scenario.required_state result when required_state is None"
        );
    }

    // --- FieldResult Clone derive ---

    #[test]
    fn should_clone_field_result() {
        // Exercises the Clone derive on FieldResult.
        let original = FieldResult {
            field: "user_message",
            passed: true,
        };
        let cloned = original.clone();
        assert_eq!(cloned.field, original.field);
        assert_eq!(cloned.passed, original.passed);
    }

    // --- extract_system_prompt: OpenAI array content with no text parts ---

    #[test]
    fn extract_system_prompt_openai_array_content_empty_text_parts_returns_none() {
        // system message with array content where no part has a `text` field.
        let body = serde_json::json!({
            "messages": [
                {"role": "system", "content": [{"type": "image_url", "image_url": "..."}]},
                {"role": "user", "content": "hi"}
            ]
        });
        // Content is array but no text parts → parts is empty → should fall through to None.
        assert_eq!(extract_system_prompt(&body, None), None);
    }

    #[test]
    fn extract_system_prompt_anthropic_with_no_system_field_returns_none() {
        // Anthropic request with no `system` key at all → None (covers the
        // path where body.get("system") is None and the if-let block is skipped).
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "hello"}]
        });
        assert_eq!(
            extract_system_prompt(&body, Some(crate::format::Provider::Anthropic)),
            None
        );
    }

    #[test]
    fn extract_system_prompt_openai_system_with_non_string_non_array_content_returns_none() {
        // A system message whose content is neither a string nor an array (e.g. a
        // number). The filter_map closure returns None for that message, so the
        // overall parts vector is empty → function returns None.
        let body = serde_json::json!({
            "messages": [
                {"role": "system", "content": 42},
                {"role": "user", "content": "hi"}
            ]
        });
        assert_eq!(extract_system_prompt(&body, None), None);
    }

    #[cfg(feature = "jsonpath")]
    #[test]
    fn body_jsonpath_uncompiled_with_body_jsonpath_set_returns_false_in_evaluate_fields() {
        // evaluate_fixture_fields: body_jsonpath is Some but compiled is None → passed: false.
        let fixture = Fixture {
            match_rule: Some(FixtureMatch {
                body_jsonpath: Some("$.foo".to_string()),
                body_jsonpath_compiled: None,
                ..Default::default()
            }),
            ..Fixture::new().respond_with_content("ok")
        };
        let body = serde_json::json!({"foo": "bar"});
        let c = ctx(&body, None);
        let results = evaluate_fixture_fields(&fixture, &c);
        let jp = results.iter().find(|r| r.field == "body_jsonpath").unwrap();
        // compiled is None → the else branch returns false.
        assert!(!jp.passed);
    }
}