infernum-server 0.2.0-rc.2

HTTP API server for local LLM inference
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
//! Tool Use Processing for Chat Completions
//!
//! This module handles:
//! - Formatting tools into model-specific prompts
//! - Detecting tool calls in model output
//! - Extracting text content from mixed tool/text responses
//!
//! # Supported Models
//!
//! Currently supports Qwen format. Llama and Mistral formats are planned.
//!
//! # Example
//!
//! ```rust,ignore
//! use infernum_server::tool_use::{ModelFamily, format_tools_for_prompt, detect_tool_calls};
//!
//! let family = ModelFamily::from_model_name("Qwen/Qwen2.5-7B-Instruct");
//! let prompt = format_tools_for_prompt(&tools, family);
//! let detected = detect_tool_calls(&model_output, family);
//! ```

use std::sync::OnceLock;

use regex::Regex;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::api_types::{FunctionCall, Tool, ToolCall, ToolChoice};

// Re-export ModelFamily from infernum-core (shared across server + agent crates)
pub use infernum_core::ModelFamily;

/// Static regex for detecting tool calls (compiled once).
static TOOL_CALL_REGEX: OnceLock<Regex> = OnceLock::new();

/// Static regex for extracting text content (compiled once).
static TOOL_CALL_EXTRACT_REGEX: OnceLock<Regex> = OnceLock::new();

fn get_tool_call_regex() -> &'static Regex {
    TOOL_CALL_REGEX.get_or_init(|| {
        Regex::new(r"(?s)<tool_call>\s*(.*?)\s*</tool_call>").expect("invalid tool_call regex")
    })
}

fn get_tool_call_extract_regex() -> &'static Regex {
    TOOL_CALL_EXTRACT_REGEX.get_or_init(|| {
        Regex::new(r"(?s)<tool_call>.*?</tool_call>").expect("invalid tool_call_extract regex")
    })
}

/// A detected tool call from model output.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DetectedToolCall {
    /// Unique ID for this tool call.
    pub id: String,
    /// Function name.
    pub name: String,
    /// Arguments as JSON string.
    pub arguments: String,
}

impl DetectedToolCall {
    /// Convert to API ToolCall format.
    #[must_use]
    pub fn to_tool_call(&self) -> ToolCall {
        ToolCall {
            id: self.id.clone(),
            call_type: "function".to_string(),
            function: FunctionCall {
                name: self.name.clone(),
                arguments: self.arguments.clone(),
            },
        }
    }
}

/// Result of processing model output for tool calls.
#[derive(Debug, Clone)]
pub struct ToolProcessingResult {
    /// Text content (if any) after removing tool calls.
    pub content: Option<String>,
    /// Detected tool calls.
    pub tool_calls: Vec<ToolCall>,
    /// Finish reason ("stop" or "tool_calls").
    pub finish_reason: String,
}

/// Format tools for inclusion in the model prompt.
///
/// Different model families require different formatting:
/// - Qwen: Uses markdown-style tool definitions with `<tool_call>` output format
/// - Llama: (planned) Uses different tags
/// - Mistral: (planned) Uses different tags
///
/// # Arguments
/// * `tools` - The tools to format
/// * `model_family` - The model family for format selection
///
/// # Returns
/// A string to append to the system prompt
#[must_use]
pub fn format_tools_for_prompt(tools: &[Tool], model_family: ModelFamily) -> String {
    if tools.is_empty() {
        return String::new();
    }

    match model_family {
        ModelFamily::Qwen | ModelFamily::Unknown => format_tools_qwen(tools),
        ModelFamily::Llama => format_tools_llama(tools),
        ModelFamily::Mistral => format_tools_mistral(tools),
    }
}

/// Format tools in Qwen2.5 native style.
///
/// Matches the exact format from Qwen2.5's Jinja chat template in
/// `tokenizer_config.json`. Tools are wrapped in `<tools></tools>` XML tags
/// as full JSON function definitions, and the instruction text matches the
/// native training format verbatim.
///
/// See TOOL-CALLING-SPEC.md §5.1.
fn format_tools_qwen(tools: &[Tool]) -> String {
    let mut result = String::from(
        "\n\n# Tools\n\n\
         You may call one or more functions to assist with the user query.\n\n\
         You are provided with function signatures within <tools></tools> XML tags:\n\
         <tools>",
    );

    for tool in tools {
        let func_json = serde_json::json!({
            "type": "function",
            "function": {
                "name": tool.function.name,
                "description": tool.function.description,
                "parameters": tool.function.parameters
            }
        });
        result.push('\n');
        result.push_str(&serde_json::to_string(&func_json).unwrap_or_default());
    }

    result.push_str(
        "\n</tools>\n\n\
         For each function call, return a json object with function name and arguments \
         within <tool_call></tool_call> XML tags:\n\
         <tool_call>\n\
         {\"name\": <function-name>, \"arguments\": <args-json-object>}\n\
         </tool_call>",
    );

    result
}

/// Format tools in Llama 3 style.
///
/// Llama 3 uses a JSON-based function calling format with `<|python_tag|>` for tool calls.
fn format_tools_llama(tools: &[Tool]) -> String {
    let mut result = String::from("\n\nYou have access to the following functions:\n\n");

    for tool in tools {
        // Build JSON schema for the function
        let func_json = serde_json::json!({
            "name": tool.function.name,
            "description": tool.function.description,
            "parameters": tool.function.parameters
        });

        result.push_str(&serde_json::to_string_pretty(&func_json).unwrap_or_default());
        result.push_str("\n\n");
    }

    result.push_str("To call a function, respond with a JSON object in the following format:\n");
    result.push_str(
        "<|python_tag|>{\"name\": \"function_name\", \"arguments\": {\"arg1\": \"value1\"}}\n",
    );
    result.push_str("\nOnly call functions when necessary to answer the user's request.\n");

    result
}

/// Format tools in Mistral style.
///
/// Mistral uses `[AVAILABLE_TOOLS]` for defining tools and `[TOOL_CALLS]` for responses.
fn format_tools_mistral(tools: &[Tool]) -> String {
    let mut result = String::from("\n\n[AVAILABLE_TOOLS]\n");

    // Format tools as JSON array
    let tools_json: Vec<serde_json::Value> = tools
        .iter()
        .map(|t| {
            serde_json::json!({
                "type": "function",
                "function": {
                    "name": t.function.name,
                    "description": t.function.description,
                    "parameters": t.function.parameters
                }
            })
        })
        .collect();

    result.push_str(&serde_json::to_string(&tools_json).unwrap_or_default());
    result.push_str("\n[/AVAILABLE_TOOLS]\n\n");
    result.push_str("When you need to call a tool, respond with:\n");
    result.push_str(
        "[TOOL_CALLS] [{\"name\": \"function_name\", \"arguments\": {\"arg1\": \"value1\"}}]\n",
    );

    result
}

/// Detect tool calls in model output.
///
/// Parses the model output for tool call patterns based on the model family.
///
/// # Arguments
/// * `output` - The raw model output text
/// * `model_family` - The model family for pattern selection
///
/// # Returns
/// A vector of detected tool calls (may be empty)
#[must_use]
pub fn detect_tool_calls(output: &str, model_family: ModelFamily) -> Vec<DetectedToolCall> {
    match model_family {
        ModelFamily::Qwen | ModelFamily::Unknown => detect_tool_calls_qwen(output),
        ModelFamily::Llama => detect_tool_calls_llama(output),
        ModelFamily::Mistral => detect_tool_calls_mistral(output),
    }
}

/// Detect Qwen-style tool calls using `<tool_call>...</tool_call>` tags.
fn detect_tool_calls_qwen(output: &str) -> Vec<DetectedToolCall> {
    let re = get_tool_call_regex();
    let mut calls = Vec::new();

    for cap in re.captures_iter(output) {
        if let Some(json_match) = cap.get(1) {
            let json_str = json_match.as_str();
            if let Ok(parsed) = serde_json::from_str::<ToolCallJson>(json_str) {
                // Use full UUID for safety (no slicing that could panic)
                let id = format!("call_{}", Uuid::new_v4().simple());
                calls.push(DetectedToolCall {
                    id,
                    name: parsed.name,
                    arguments: serde_json::to_string(&parsed.arguments).unwrap_or_default(),
                });
            }
        }
    }

    calls
}

/// Internal struct for parsing tool call JSON.
#[derive(Debug, Deserialize)]
struct ToolCallJson {
    name: String,
    arguments: serde_json::Value,
}

/// Detect Llama-style tool calls using `<|python_tag|>` markers.
fn detect_tool_calls_llama(output: &str) -> Vec<DetectedToolCall> {
    let marker = "<|python_tag|>";
    let mut calls = Vec::new();
    let mut search_start = 0;

    // Use deep JSON parsing instead of regex for nested structures
    while let Some(marker_pos) = output[search_start..].find(marker) {
        let abs_marker_pos = search_start + marker_pos;
        let json_start = abs_marker_pos + marker.len();
        let remaining = &output[json_start..];

        if let Some(json_str) = extract_json_object(remaining, 0) {
            if let Ok(parsed) = serde_json::from_str::<ToolCallJson>(&json_str) {
                let id = format!("call_{}", Uuid::new_v4().simple());
                calls.push(DetectedToolCall {
                    id,
                    name: parsed.name,
                    arguments: serde_json::to_string(&parsed.arguments).unwrap_or_default(),
                });
                search_start = json_start + json_str.len();
                continue;
            }
        }
        // Move past this marker if we couldn't parse
        search_start = json_start;
    }

    // Fallback: also check for Qwen-style tags (models sometimes use both)
    if calls.is_empty() {
        calls = detect_tool_calls_qwen(output);
    }

    calls
}

/// Static regex for Mistral TOOL_CALLS detection.
static MISTRAL_TOOL_CALL_REGEX: OnceLock<Regex> = OnceLock::new();

fn get_mistral_tool_call_regex() -> &'static Regex {
    MISTRAL_TOOL_CALL_REGEX.get_or_init(|| {
        Regex::new(r#"\[TOOL_CALLS\]\s*\[([^\]]+)\]"#).expect("invalid mistral tool_call regex")
    })
}

/// Detect Mistral-style tool calls using `[TOOL_CALLS]` markers.
fn detect_tool_calls_mistral(output: &str) -> Vec<DetectedToolCall> {
    let re = get_mistral_tool_call_regex();
    let mut calls = Vec::new();

    for cap in re.captures_iter(output) {
        if let Some(json_match) = cap.get(1) {
            // Mistral wraps the calls in an array, so we need to parse it
            let json_str = format!("[{}]", json_match.as_str());
            if let Ok(parsed) = serde_json::from_str::<Vec<ToolCallJson>>(&json_str) {
                for tool_call in parsed {
                    let id = format!("call_{}", Uuid::new_v4().simple());
                    calls.push(DetectedToolCall {
                        id,
                        name: tool_call.name,
                        arguments: serde_json::to_string(&tool_call.arguments).unwrap_or_default(),
                    });
                }
            }
        }
    }

    // Fallback: also check for Qwen-style tags
    if calls.is_empty() {
        calls = detect_tool_calls_qwen(output);
    }

    calls
}

/// Extract text content from model output, removing tool call sections.
///
/// # Arguments
/// * `output` - The raw model output text
/// * `model_family` - The model family for pattern selection
///
/// # Returns
/// The text content with tool calls removed, or None if only tool calls
#[must_use]
pub fn extract_text_content(output: &str, model_family: ModelFamily) -> Option<String> {
    match model_family {
        ModelFamily::Qwen | ModelFamily::Unknown => extract_text_content_qwen(output),
        ModelFamily::Llama => extract_text_content_llama(output),
        ModelFamily::Mistral => extract_text_content_mistral(output),
    }
}

/// Extract text content for Qwen format.
fn extract_text_content_qwen(output: &str) -> Option<String> {
    let re = get_tool_call_extract_regex();
    let cleaned = re.replace_all(output, "");
    let trimmed = cleaned.trim();

    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Static regex for Llama text extraction.
static LLAMA_EXTRACT_REGEX: OnceLock<Regex> = OnceLock::new();

fn get_llama_extract_regex() -> &'static Regex {
    LLAMA_EXTRACT_REGEX.get_or_init(|| {
        // Match <|python_tag|> followed by JSON object with nested braces
        Regex::new(r#"<\|python_tag\|>\s*\{(?:[^{}]|\{[^{}]*\})*\}"#)
            .expect("invalid llama extract regex")
    })
}

/// Extract text content for Llama format.
fn extract_text_content_llama(output: &str) -> Option<String> {
    let re = get_llama_extract_regex();
    let cleaned = re.replace_all(output, "");
    // Also remove Qwen-style tags as fallback
    let qwen_re = get_tool_call_extract_regex();
    let cleaned = qwen_re.replace_all(&cleaned, "");
    let trimmed = cleaned.trim();

    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Static regex for Mistral text extraction.
static MISTRAL_EXTRACT_REGEX: OnceLock<Regex> = OnceLock::new();

fn get_mistral_extract_regex() -> &'static Regex {
    MISTRAL_EXTRACT_REGEX.get_or_init(|| {
        Regex::new(r#"\[TOOL_CALLS\]\s*\[[^\]]+\]"#).expect("invalid mistral extract regex")
    })
}

/// Extract text content for Mistral format.
fn extract_text_content_mistral(output: &str) -> Option<String> {
    let re = get_mistral_extract_regex();
    let cleaned = re.replace_all(output, "");
    // Also remove Qwen-style tags as fallback
    let qwen_re = get_tool_call_extract_regex();
    let cleaned = qwen_re.replace_all(&cleaned, "");
    let trimmed = cleaned.trim();

    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Process model output for tool calls and content.
///
/// This is the main entry point for processing model output. It detects
/// tool calls, extracts text content, and determines the finish reason.
///
/// # Arguments
/// * `output` - The raw model output text
/// * `model_family` - The model family for format selection
///
/// # Returns
/// A `ToolProcessingResult` with content, tool calls, and finish reason
#[must_use]
pub fn process_model_output(output: &str, model_family: ModelFamily) -> ToolProcessingResult {
    let detected = detect_tool_calls(output, model_family);
    let content = extract_text_content(output, model_family);

    let tool_calls: Vec<ToolCall> = detected
        .iter()
        .map(DetectedToolCall::to_tool_call)
        .collect();

    let finish_reason = if tool_calls.is_empty() {
        "stop".to_string()
    } else {
        "tool_calls".to_string()
    };

    ToolProcessingResult {
        content,
        tool_calls,
        finish_reason,
    }
}

/// Validate that a tool exists in the provided tools list.
///
/// # Arguments
/// * `tool_name` - The name of the tool to validate
/// * `tools` - The list of available tools
///
/// # Returns
/// True if the tool exists, false otherwise
#[must_use]
pub fn validate_tool_exists(tool_name: &str, tools: &[Tool]) -> bool {
    tools.iter().any(|t| t.function.name == tool_name)
}

/// Check if tools should be included in the prompt based on tool_choice.
///
/// # Arguments
/// * `tool_choice` - The tool choice setting from the request
///
/// # Returns
/// True if tools should be formatted into the prompt
#[must_use]
pub fn should_include_tools(tool_choice: Option<&ToolChoice>) -> bool {
    match tool_choice {
        None => true, // Default is "auto"
        Some(ToolChoice::String(s)) => s != "none",
        Some(ToolChoice::Tool(_)) => true, // Specific tool requested
    }
}

/// Get the specific tool name if tool_choice forces a specific tool.
///
/// # Arguments
/// * `tool_choice` - The tool choice setting from the request
///
/// # Returns
/// Some(tool_name) if a specific tool is forced, None otherwise
#[must_use]
pub fn get_forced_tool(tool_choice: Option<&ToolChoice>) -> Option<&str> {
    match tool_choice {
        Some(ToolChoice::Tool(tc)) => Some(&tc.function.name),
        _ => None,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PHASE 3: STREAMING TOOL DETECTION
// ═══════════════════════════════════════════════════════════════════════════════

/// Tool call start markers by model family.
const QWEN_START_MARKERS: &[&str] = &["<tool_call>", "<tool_call", "<tool_", "<tool"];
const LLAMA_START_MARKERS: &[&str] = &[
    "<|python_tag|>",
    "<|python_tag",
    "<|python_",
    "<|python",
    "<|",
];
const MISTRAL_START_MARKERS: &[&str] = &["[TOOL_CALLS]", "[TOOL_CALLS", "[TOOL_", "[TOOL"];

/// Check if a buffer might contain the start of a tool call marker.
///
/// Used during streaming to decide whether to buffer content instead of
/// immediately sending it to the client.
///
/// # Arguments
/// * `buffer` - The current buffer content
/// * `model_family` - The model family for marker selection
///
/// # Returns
/// True if the buffer ends with a potential tool marker prefix
#[must_use]
pub fn buffer_might_contain_tool_start(buffer: &str, model_family: ModelFamily) -> bool {
    let markers = match model_family {
        ModelFamily::Qwen | ModelFamily::Unknown => QWEN_START_MARKERS,
        ModelFamily::Llama => LLAMA_START_MARKERS,
        ModelFamily::Mistral => MISTRAL_START_MARKERS,
    };

    // Check if buffer ends with any prefix of any marker
    for marker in markers {
        // Check all prefixes of the marker
        for prefix_len in 1..=marker.len() {
            let prefix = &marker[..prefix_len];
            if buffer.ends_with(prefix) {
                return true;
            }
        }
    }

    false
}

/// Check if buffered content is definitely not a tool call marker.
///
/// Used to release buffered content when we've accumulated enough
/// characters to know it's not a tool marker.
///
/// # Arguments
/// * `buffer` - The current buffer content
/// * `model_family` - The model family for marker selection
///
/// # Returns
/// True if we can be certain this isn't a tool call
#[must_use]
pub fn definitely_not_tool_call(buffer: &str, model_family: ModelFamily) -> bool {
    let full_marker = match model_family {
        ModelFamily::Qwen | ModelFamily::Unknown => "<tool_call>",
        ModelFamily::Llama => "<|python_tag|>",
        ModelFamily::Mistral => "[TOOL_CALLS]",
    };

    // If buffer contains the full marker, it's definitely a tool call
    if buffer.contains(full_marker) {
        return false;
    }

    // If buffer is longer than the marker and doesn't contain it,
    // check if it could still be starting one at the end
    if buffer.len() > full_marker.len() {
        // Get the tail that could potentially be a partial marker
        let tail_start = buffer.len().saturating_sub(full_marker.len());
        let tail = &buffer[tail_start..];

        // If tail doesn't start any valid marker prefix, we're safe
        !buffer_might_contain_tool_start(tail, model_family)
    } else {
        // Buffer is short - check if it matches any prefix
        !buffer_might_contain_tool_start(buffer, model_family)
    }
}

/// Result of attempting to extract a complete tool call from a buffer.
#[derive(Debug, Clone)]
pub struct StreamingExtractResult {
    /// Whether a complete tool call was found.
    pub found: bool,
    /// Text content before the tool call (if any).
    pub text_before: Option<String>,
    /// The extracted tool call (if found).
    pub call: Option<DetectedToolCall>,
    /// Remaining buffer content after the tool call.
    pub remaining: String,
}

/// Try to extract a complete tool call from a streaming buffer.
///
/// # Arguments
/// * `buffer` - The accumulated buffer content
/// * `model_family` - The model family for pattern selection
///
/// # Returns
/// Extraction result with tool call and remaining content
#[must_use]
pub fn try_extract_complete_tool_call(
    buffer: &str,
    model_family: ModelFamily,
) -> StreamingExtractResult {
    match model_family {
        ModelFamily::Qwen | ModelFamily::Unknown => try_extract_qwen(buffer),
        ModelFamily::Llama => try_extract_llama(buffer),
        ModelFamily::Mistral => try_extract_mistral(buffer),
    }
}

fn try_extract_qwen(buffer: &str) -> StreamingExtractResult {
    let start_tag = "<tool_call>";
    let end_tag = "</tool_call>";

    if let Some(start_idx) = buffer.find(start_tag) {
        let json_start = start_idx + start_tag.len();
        // CRITICAL: Search for end tag AFTER start tag, not from beginning
        // Bug fix: buffer.find(end_tag) would find stray end tags before start
        if let Some(end_offset) = buffer[json_start..].find(end_tag) {
            let end_idx = json_start + end_offset;
            let json_content = buffer[json_start..end_idx].trim();

            if let Ok(parsed) = serde_json::from_str::<ToolCallJson>(json_content) {
                let id = format!("call_{}", Uuid::new_v4().simple());
                let call = DetectedToolCall {
                    id,
                    name: parsed.name,
                    arguments: serde_json::to_string(&parsed.arguments).unwrap_or_default(),
                };

                let text_before = if start_idx > 0 {
                    Some(buffer[..start_idx].to_string())
                } else {
                    None
                };

                let remaining = buffer[end_idx + end_tag.len()..].to_string();

                return StreamingExtractResult {
                    found: true,
                    text_before,
                    call: Some(call),
                    remaining,
                };
            }
        }
    }

    StreamingExtractResult {
        found: false,
        text_before: None,
        call: None,
        remaining: buffer.to_string(),
    }
}

fn try_extract_llama(buffer: &str) -> StreamingExtractResult {
    let marker = "<|python_tag|>";

    if let Some(start_idx) = buffer.find(marker) {
        let json_start = start_idx + marker.len();
        let json_part = &buffer[json_start..];

        // Try to extract complete JSON object
        if let Some(json_str) = extract_json_object(json_part, 0) {
            if let Ok(parsed) = serde_json::from_str::<ToolCallJson>(&json_str) {
                let id = format!("call_{}", Uuid::new_v4().simple());
                let call = DetectedToolCall {
                    id,
                    name: parsed.name,
                    arguments: serde_json::to_string(&parsed.arguments).unwrap_or_default(),
                };

                let text_before = if start_idx > 0 {
                    Some(buffer[..start_idx].to_string())
                } else {
                    None
                };

                let remaining = buffer[json_start + json_str.len()..].to_string();

                return StreamingExtractResult {
                    found: true,
                    text_before,
                    call: Some(call),
                    remaining,
                };
            }
        }
    }

    // Fallback to Qwen style
    try_extract_qwen(buffer)
}

fn try_extract_mistral(buffer: &str) -> StreamingExtractResult {
    let marker = "[TOOL_CALLS]";

    if let Some(start_idx) = buffer.find(marker) {
        let after_marker = &buffer[start_idx + marker.len()..];

        // Look for JSON array
        if let Some(arr_start) = after_marker.find('[') {
            if let Some(arr_end) = find_matching_bracket(after_marker, arr_start) {
                let json_arr = &after_marker[arr_start..=arr_end];

                if let Ok(parsed) = serde_json::from_str::<Vec<ToolCallJson>>(json_arr) {
                    if let Some(first) = parsed.into_iter().next() {
                        let id = format!("call_{}", Uuid::new_v4().simple());
                        let call = DetectedToolCall {
                            id,
                            name: first.name,
                            arguments: serde_json::to_string(&first.arguments).unwrap_or_default(),
                        };

                        let text_before = if start_idx > 0 {
                            Some(buffer[..start_idx].to_string())
                        } else {
                            None
                        };

                        let remaining = after_marker[arr_end + 1..].to_string();

                        return StreamingExtractResult {
                            found: true,
                            text_before,
                            call: Some(call),
                            remaining,
                        };
                    }
                }
            }
        }
    }

    // Fallback to Qwen style
    try_extract_qwen(buffer)
}

/// Find the matching closing bracket for an opening bracket.
fn find_matching_bracket(s: &str, start: usize) -> Option<usize> {
    let bytes = s.as_bytes();
    let open_char = bytes.get(start)?;
    let close_char = match open_char {
        b'[' => b']',
        b'{' => b'}',
        _ => return None,
    };

    let mut depth = 0;
    let mut in_string = false;
    let mut escape_next = false;

    for (i, &b) in bytes.iter().enumerate().skip(start) {
        if escape_next {
            escape_next = false;
            continue;
        }

        if b == b'\\' && in_string {
            escape_next = true;
            continue;
        }

        if b == b'"' {
            in_string = !in_string;
            continue;
        }

        if in_string {
            continue;
        }

        if b == *open_char {
            depth += 1;
        } else if b == close_char {
            depth -= 1;
            if depth == 0 {
                return Some(i);
            }
        }
    }

    None
}

// ═══════════════════════════════════════════════════════════════════════════════
// PHASE 3: DEEP JSON PARSING
// ═══════════════════════════════════════════════════════════════════════════════

/// Extract a complete JSON object from a string starting at the given position.
///
/// This handles arbitrarily nested JSON, unlike regex-based approaches.
///
/// # Arguments
/// * `s` - The string to extract from
/// * `start` - The position to start searching from
///
/// # Returns
/// The extracted JSON string if a complete object is found
#[must_use]
pub fn extract_json_object(s: &str, start: usize) -> Option<String> {
    let bytes = s.as_bytes();

    // Find the opening brace
    let obj_start = bytes.iter().skip(start).position(|&b| b == b'{')? + start;

    // Find the matching closing brace
    let obj_end = find_matching_bracket(s, obj_start)?;

    Some(s[obj_start..=obj_end].to_string())
}

// ═══════════════════════════════════════════════════════════════════════════════
// PHASE 3: PARALLEL TOOL CALLS ENFORCEMENT
// ═══════════════════════════════════════════════════════════════════════════════

/// Options for processing model output.
///
/// For validation of tool calls against schemas, use `process_model_output_with_validation`
/// which takes a tools list directly.
#[derive(Debug, Clone, Default)]
pub struct ProcessingOptions {
    /// Whether parallel tool calls are allowed.
    /// When false, only the first tool call is returned.
    pub parallel_tool_calls: bool,
}

/// Enforce parallel_tool_calls setting on detected calls.
///
/// When `parallel` is false, only the first tool call is returned.
///
/// # Arguments
/// * `calls` - The detected tool calls
/// * `parallel` - Whether parallel calls are allowed
///
/// # Returns
/// Filtered list of tool calls
#[must_use]
pub fn enforce_parallel_tool_calls(
    calls: Vec<DetectedToolCall>,
    parallel: bool,
) -> Vec<DetectedToolCall> {
    if parallel {
        calls
    } else {
        // Take only the first call when parallel is disabled
        calls.into_iter().take(1).collect()
    }
}

/// Process model output with additional options.
///
/// This is an extended version of `process_model_output` that supports
/// parallel_tool_calls enforcement.
///
/// # Arguments
/// * `output` - The raw model output text
/// * `model_family` - The model family for format selection
/// * `options` - Processing options
///
/// # Returns
/// A `ToolProcessingResult` with content, tool calls, and finish reason
#[must_use]
pub fn process_model_output_with_options(
    output: &str,
    model_family: ModelFamily,
    options: ProcessingOptions,
) -> ToolProcessingResult {
    let detected = detect_tool_calls(output, model_family);
    let detected = enforce_parallel_tool_calls(detected, options.parallel_tool_calls);
    let content = extract_text_content(output, model_family);

    let tool_calls: Vec<ToolCall> = detected
        .iter()
        .map(DetectedToolCall::to_tool_call)
        .collect();

    let finish_reason = if tool_calls.is_empty() {
        "stop".to_string()
    } else {
        "tool_calls".to_string()
    };

    ToolProcessingResult {
        content,
        tool_calls,
        finish_reason,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PHASE 3: STRICT MODE SCHEMA VALIDATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Validate tool arguments against a JSON schema.
///
/// This performs basic validation including:
/// - Required field checking
/// - Type validation (string, integer, number, boolean, array, object)
/// - Enum value validation
///
/// # Arguments
/// * `arguments` - JSON string of the arguments
/// * `schema` - The JSON schema to validate against
///
/// # Returns
/// Ok(()) if valid, Err(message) if invalid
pub fn validate_tool_arguments(arguments: &str, schema: &serde_json::Value) -> Result<(), String> {
    let args: serde_json::Value =
        serde_json::from_str(arguments).map_err(|e| format!("Invalid JSON: {e}"))?;

    validate_value_against_schema(&args, schema, "")
}

fn validate_value_against_schema(
    value: &serde_json::Value,
    schema: &serde_json::Value,
    path: &str,
) -> Result<(), String> {
    // Check type
    if let Some(expected_type) = schema.get("type").and_then(|t| t.as_str()) {
        let actual_type = match value {
            serde_json::Value::Null => "null",
            serde_json::Value::Bool(_) => "boolean",
            serde_json::Value::Number(n) => {
                if n.is_i64() || n.is_u64() {
                    "integer"
                } else {
                    "number"
                }
            },
            serde_json::Value::String(_) => "string",
            serde_json::Value::Array(_) => "array",
            serde_json::Value::Object(_) => "object",
        };

        // Allow integer for number type
        let type_matches =
            actual_type == expected_type || (expected_type == "number" && actual_type == "integer");

        if !type_matches {
            return Err(format!(
                "Type mismatch at {}: expected {expected_type}, got {actual_type}",
                if path.is_empty() { "root" } else { path }
            ));
        }
    }

    // Check enum
    if let Some(enum_values) = schema.get("enum").and_then(|e| e.as_array()) {
        if !enum_values.contains(value) {
            return Err(format!(
                "Invalid enum value at {}: {:?} not in {:?}",
                if path.is_empty() { "root" } else { path },
                value,
                enum_values
            ));
        }
    }

    // Check object properties and required fields
    if let serde_json::Value::Object(obj) = value {
        // Check required fields
        if let Some(required) = schema.get("required").and_then(|r| r.as_array()) {
            for req in required {
                if let Some(field_name) = req.as_str() {
                    if !obj.contains_key(field_name) {
                        return Err(format!("Missing required field: {field_name}"));
                    }
                }
            }
        }

        // Validate each property
        if let Some(properties) = schema.get("properties").and_then(|p| p.as_object()) {
            for (key, prop_value) in obj {
                if let Some(prop_schema) = properties.get(key) {
                    let prop_path = if path.is_empty() {
                        key.clone()
                    } else {
                        format!("{path}.{key}")
                    };
                    validate_value_against_schema(prop_value, prop_schema, &prop_path)?;
                }
            }
        }
    }

    // Check array items
    if let serde_json::Value::Array(arr) = value {
        if let Some(items_schema) = schema.get("items") {
            for (i, item) in arr.iter().enumerate() {
                let item_path = format!("{path}[{i}]");
                validate_value_against_schema(item, items_schema, &item_path)?;
            }
        }
    }

    Ok(())
}

/// Result of processing with strict mode validation.
#[derive(Debug, Clone)]
pub struct ToolValidationResult {
    /// The standard processing result.
    pub result: ToolProcessingResult,
    /// Validation errors (tool name -> error message).
    pub validation_errors: Vec<(String, String)>,
}

/// Process model output with strict mode validation.
///
/// # Arguments
/// * `output` - The raw model output text
/// * `model_family` - The model family for format selection
/// * `tools` - Available tools (for schema lookup)
///
/// # Returns
/// Processing result with validation errors
#[must_use]
pub fn process_model_output_with_validation(
    output: &str,
    model_family: ModelFamily,
    tools: &[Tool],
) -> ToolValidationResult {
    let detected = detect_tool_calls(output, model_family);
    let content = extract_text_content(output, model_family);

    let mut validation_errors = Vec::new();

    // Validate each tool call against its schema if strict mode is enabled
    for call in &detected {
        if let Some(tool) = tools.iter().find(|t| t.function.name == call.name) {
            if tool.function.strict == Some(true) {
                if let Some(schema) = &tool.function.parameters {
                    if let Err(e) = validate_tool_arguments(&call.arguments, schema) {
                        validation_errors.push((call.name.clone(), e));
                    }
                }
            }
        }
    }

    let tool_calls: Vec<ToolCall> = detected
        .iter()
        .map(DetectedToolCall::to_tool_call)
        .collect();

    let finish_reason = if tool_calls.is_empty() {
        "stop".to_string()
    } else {
        "tool_calls".to_string()
    };

    ToolValidationResult {
        result: ToolProcessingResult {
            content,
            tool_calls,
            finish_reason,
        },
        validation_errors,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PHASE 3: UNKNOWN TOOL VALIDATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of validating detected tool calls.
#[derive(Debug, Clone)]
pub struct DetectedCallsValidation {
    /// Tool calls that passed validation.
    pub valid_calls: Vec<DetectedToolCall>,
    /// Names of tools that were not found in the tools list.
    pub unknown_tools: Vec<String>,
}

/// Validate detected tool calls against the available tools list.
///
/// Separates detected calls into known tools (valid_calls) and unknown tools.
/// Only calls to tools in the provided list are considered valid.
///
/// # Arguments
/// * `detected` - The detected tool calls
/// * `tools` - The available tools
///
/// # Returns
/// Validation result with valid calls and unknown tool names
#[must_use]
pub fn validate_detected_calls(
    detected: &[DetectedToolCall],
    tools: &[Tool],
) -> DetectedCallsValidation {
    let mut valid_calls = Vec::new();
    let mut unknown_tools = Vec::new();

    for call in detected {
        if validate_tool_exists(&call.name, tools) {
            valid_calls.push(call.clone());
        } else {
            unknown_tools.push(call.name.clone());
        }
    }

    DetectedCallsValidation {
        valid_calls,
        unknown_tools,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// STREAMING TOOL DETECTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// Events emitted by the streaming tool detector.
#[derive(Debug, Clone, PartialEq)]
pub enum ToolDetectionEvent {
    /// Regular text content to stream to client.
    Text(String),
    /// A complete tool call was detected.
    ToolCall(DetectedToolCall),
    /// Currently buffering potential tool call (internal state indicator).
    Buffering,
}

/// Stateful detector for tool calls in streaming output.
///
/// This detector manages a buffer to handle cases where tool call markers
/// span multiple streaming chunks. It emits events indicating when to:
/// - Stream text immediately
/// - Buffer content (potential tool call starting)
/// - Emit a complete tool call
///
/// # Example
///
/// ```rust,ignore
/// use infernum_server::tool_use::{StreamingToolDetector, ModelFamily, ToolDetectionEvent};
///
/// let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);
///
/// // Process chunks as they arrive from the model
/// for chunk in streaming_response {
///     for event in detector.process_chunk(&chunk) {
///         match event {
///             ToolDetectionEvent::Text(text) => stream_to_client(text),
///             ToolDetectionEvent::ToolCall(call) => emit_tool_call_event(call),
///             ToolDetectionEvent::Buffering => { /* wait for more data */ }
///         }
///     }
/// }
///
/// // Flush any remaining buffer at end of stream
/// for event in detector.finish() {
///     // handle final events
/// }
/// ```
#[derive(Debug)]
pub struct StreamingToolDetector {
    /// Accumulated buffer for potential tool calls.
    buffer: String,
    /// Model family for format-specific detection.
    model_family: ModelFamily,
    /// Whether we're currently inside a potential tool call.
    in_potential_tool_call: bool,
}

impl StreamingToolDetector {
    /// Create a new streaming tool detector for the given model family.
    #[must_use]
    pub fn new(model_family: ModelFamily) -> Self {
        Self {
            buffer: String::new(),
            model_family,
            in_potential_tool_call: false,
        }
    }

    /// Process an incoming chunk of text and return detection events.
    ///
    /// Returns a vector of events that should be handled by the caller.
    /// Multiple events may be returned if a chunk contains both text and tool calls.
    pub fn process_chunk(&mut self, chunk: &str) -> Vec<ToolDetectionEvent> {
        self.buffer.push_str(chunk);
        self.evaluate_buffer()
    }

    /// Finish processing and flush any remaining buffer.
    ///
    /// Call this when the stream ends to emit any buffered content.
    pub fn finish(&mut self) -> Vec<ToolDetectionEvent> {
        if self.buffer.is_empty() {
            return vec![];
        }

        // If we have buffered content that never became a tool call, emit as text
        let remaining = std::mem::take(&mut self.buffer);
        self.in_potential_tool_call = false;
        vec![ToolDetectionEvent::Text(remaining)]
    }

    /// Evaluate the current buffer and emit appropriate events.
    fn evaluate_buffer(&mut self) -> Vec<ToolDetectionEvent> {
        let mut events = Vec::new();

        loop {
            // Try to extract a complete tool call
            let result = try_extract_complete_tool_call(&self.buffer, self.model_family);

            if result.found {
                // Emit any text before the tool call
                if let Some(text) = result.text_before {
                    if !text.is_empty() {
                        events.push(ToolDetectionEvent::Text(text));
                    }
                }

                // Emit the tool call
                if let Some(call) = result.call {
                    events.push(ToolDetectionEvent::ToolCall(call));
                }

                // Update buffer with remaining content
                self.buffer = result.remaining;
                self.in_potential_tool_call = false;

                // Continue loop to check for more tool calls
                continue;
            }

            // No complete tool call found - check if we might be starting one
            if buffer_might_contain_tool_start(&self.buffer, self.model_family) {
                self.in_potential_tool_call = true;
                // Don't emit anything yet, keep buffering
                if events.is_empty() {
                    events.push(ToolDetectionEvent::Buffering);
                }
                break;
            }

            // Definitely not a tool call - emit buffered text
            if definitely_not_tool_call(&self.buffer, self.model_family)
                || !self.in_potential_tool_call
            {
                if !self.buffer.is_empty() {
                    let text = std::mem::take(&mut self.buffer);
                    events.push(ToolDetectionEvent::Text(text));
                }
                self.in_potential_tool_call = false;
                break;
            }

            // Ambiguous state - keep buffering
            break;
        }

        events
    }

    /// Check if the detector is currently buffering potential tool call content.
    #[must_use]
    pub fn is_buffering(&self) -> bool {
        self.in_potential_tool_call
    }

    /// Get the current buffer contents (for debugging/testing).
    #[must_use]
    pub fn buffer(&self) -> &str {
        &self.buffer
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// AGENT-CENTRIC SSE EVENTS
// See INFERNUM-SPEC.md §10 for protocol specification
// ═══════════════════════════════════════════════════════════════════════════════

/// Agent-centric SSE event types.
///
/// Designed for AI agent consumption - complete, typed, immediately parseable.
/// Infernum-native format. See INFERNUM-SPEC.md §10 for rationale.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SseEvent {
    /// Streamed text content.
    Text {
        /// The text content chunk.
        content: String,
    },

    /// Complete tool call (buffered, not partial).
    ToolCall {
        /// Unique identifier for this tool call.
        id: String,
        /// Name of the function to call.
        name: String,
        /// Parsed JSON arguments.
        arguments: serde_json::Value,
    },

    /// Error during streaming.
    Error {
        /// Error code (e.g., "rate_limit", "context_length").
        code: String,
        /// Human-readable error message.
        message: String,
        /// Optional additional error details.
        #[serde(skip_serializing_if = "Option::is_none")]
        details: Option<serde_json::Value>,
    },

    /// Stream complete.
    Done {
        /// Reason for completion: "stop", "tool_calls", "length", "error".
        finish_reason: String,
        /// Token usage statistics.
        #[serde(skip_serializing_if = "Option::is_none")]
        usage: Option<SseUsage>,
    },
}

/// Token usage for SSE done event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SseUsage {
    /// Number of tokens in the prompt.
    pub prompt_tokens: u32,
    /// Number of tokens in the completion.
    pub completion_tokens: u32,
    /// Total tokens used (prompt + completion).
    pub total_tokens: u32,
}

impl SseEvent {
    /// Create a text event.
    #[must_use]
    pub fn text(content: impl Into<String>) -> Self {
        Self::Text {
            content: content.into(),
        }
    }

    /// Create a tool call event from a DetectedToolCall.
    #[must_use]
    pub fn tool_call(call: &DetectedToolCall) -> Self {
        // Parse arguments as JSON, fall back to raw string if invalid
        let arguments = serde_json::from_str(&call.arguments)
            .unwrap_or_else(|_| serde_json::Value::String(call.arguments.clone()));

        Self::ToolCall {
            id: call.id.clone(),
            name: call.name.clone(),
            arguments,
        }
    }

    /// Create an error event.
    #[must_use]
    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Error {
            code: code.into(),
            message: message.into(),
            details: None,
        }
    }

    /// Create an error event with details.
    #[must_use]
    pub fn error_with_details(
        code: impl Into<String>,
        message: impl Into<String>,
        details: serde_json::Value,
    ) -> Self {
        Self::Error {
            code: code.into(),
            message: message.into(),
            details: Some(details),
        }
    }

    /// Create a done event.
    #[must_use]
    pub fn done(finish_reason: impl Into<String>) -> Self {
        Self::Done {
            finish_reason: finish_reason.into(),
            usage: None,
        }
    }

    /// Create a done event with usage stats.
    #[must_use]
    pub fn done_with_usage(
        finish_reason: impl Into<String>,
        prompt_tokens: u32,
        completion_tokens: u32,
    ) -> Self {
        Self::Done {
            finish_reason: finish_reason.into(),
            usage: Some(SseUsage {
                prompt_tokens,
                completion_tokens,
                total_tokens: prompt_tokens + completion_tokens,
            }),
        }
    }

    /// Serialize to JSON string for SSE data field.
    #[must_use]
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| {
            r#"{"type":"error","code":"serialization_error","message":"Failed to serialize event"}"#.to_string()
        })
    }
}

/// Convert ToolDetectionEvent to SseEvent.
impl From<ToolDetectionEvent> for Option<SseEvent> {
    fn from(event: ToolDetectionEvent) -> Self {
        match event {
            ToolDetectionEvent::Text(content) => Some(SseEvent::text(content)),
            ToolDetectionEvent::ToolCall(call) => Some(SseEvent::tool_call(&call)),
            ToolDetectionEvent::Buffering => None, // Skip buffering events
        }
    }
}

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

    fn make_tool(name: &str, description: &str, params: serde_json::Value) -> Tool {
        Tool {
            tool_type: "function".to_string(),
            function: crate::api_types::FunctionDefinition {
                name: name.to_string(),
                description: Some(description.to_string()),
                parameters: Some(params),
                strict: None,
            },
        }
    }

    // === Model Family Tests ===

    #[test]
    fn test_model_family_qwen() {
        assert_eq!(
            ModelFamily::from_model_name("Qwen/Qwen2.5-7B-Instruct"),
            ModelFamily::Qwen
        );
        assert_eq!(
            ModelFamily::from_model_name("qwen2.5-coder"),
            ModelFamily::Qwen
        );
    }

    #[test]
    fn test_model_family_llama() {
        assert_eq!(
            ModelFamily::from_model_name("meta-llama/Llama-3.2-3B-Instruct"),
            ModelFamily::Llama
        );
        assert_eq!(
            ModelFamily::from_model_name("llama-3.1"),
            ModelFamily::Llama
        );
    }

    #[test]
    fn test_model_family_mistral() {
        assert_eq!(
            ModelFamily::from_model_name("mistralai/Mistral-7B-Instruct"),
            ModelFamily::Mistral
        );
        assert_eq!(
            ModelFamily::from_model_name("Mixtral-8x7B"),
            ModelFamily::Mistral
        );
    }

    #[test]
    fn test_model_family_unknown() {
        assert_eq!(
            ModelFamily::from_model_name("unknown-model"),
            ModelFamily::Unknown
        );
    }

    // === Tool Formatting Tests ===

    #[test]
    fn test_format_empty_tools() {
        let result = format_tools_for_prompt(&[], ModelFamily::Qwen);
        assert!(result.is_empty());
    }

    // === Spec §5.1: Qwen Native Format Tests ===
    //
    // These tests validate TOOL-CALLING-SPEC.md §5.1 (Qwen Format).
    // Qwen2.5 native format uses <tools></tools> XML tags with full JSON
    // function definitions, NOT markdown-style descriptions.

    #[test]
    fn test_format_single_tool_qwen_native() {
        let tool = make_tool(
            "get_weather",
            "Get current weather for a location",
            json!({
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City name"
                    }
                },
                "required": ["location"]
            }),
        );

        let result = format_tools_for_prompt(&[tool], ModelFamily::Qwen);

        // §5.1: Must use native preamble
        assert!(result.contains("# Tools"), "Missing '# Tools' header");
        assert!(
            result.contains("You may call one or more functions to assist with the user query"),
            "Missing native preamble text"
        );

        // §5.1: Tools wrapped in <tools></tools> XML tags
        assert!(result.contains("<tools>"), "Missing <tools> opening tag");
        assert!(result.contains("</tools>"), "Missing </tools> closing tag");

        // §5.1: Each tool as full JSON function definition
        assert!(
            result.contains("\"type\":\"function\""),
            "Tool not serialized as JSON function definition"
        );
        assert!(
            result.contains("\"name\":\"get_weather\""),
            "Tool name not in JSON format"
        );

        // §5.1: Must NOT use old markdown format
        assert!(
            !result.contains("## get_weather"),
            "Still using old markdown-style format"
        );
        assert!(
            !result.contains("Parameters:\n-"),
            "Still using old markdown parameter list"
        );

        // §5.1: Instruction text for tool call format
        assert!(
            result.contains("<tool_call>"),
            "Missing <tool_call> instruction"
        );
    }

    #[test]
    fn test_format_multiple_tools_qwen_native() {
        let tools = vec![
            make_tool(
                "tool_a",
                "First tool",
                json!({"type": "object", "properties": {}}),
            ),
            make_tool(
                "tool_b",
                "Second tool",
                json!({"type": "object", "properties": {}}),
            ),
        ];

        let result = format_tools_for_prompt(&tools, ModelFamily::Qwen);

        // Both tools must appear as JSON function definitions inside <tools> tags
        assert!(result.contains("<tools>"));
        assert!(result.contains("</tools>"));
        assert!(result.contains("\"name\":\"tool_a\""));
        assert!(result.contains("\"name\":\"tool_b\""));
        assert!(result.contains("\"description\":\"First tool\""));
        assert!(result.contains("\"description\":\"Second tool\""));

        // Must NOT use old markdown headers
        assert!(!result.contains("## tool_a"));
        assert!(!result.contains("## tool_b"));
    }

    // === Tool Detection Tests ===

    #[test]
    fn test_detect_qwen_tool_call() {
        let output = r#"I'll get the weather for you.
<tool_call>
{"name": "get_weather", "arguments": {"location": "Seattle"}}
</tool_call>"#;

        let calls = detect_tool_calls(output, ModelFamily::Qwen);

        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "get_weather");
        assert!(calls[0].arguments.contains("Seattle"));
        assert!(calls[0].id.starts_with("call_"));
    }

    #[test]
    fn test_detect_multiple_tool_calls() {
        let output = r#"<tool_call>
{"name": "tool_a", "arguments": {}}
</tool_call>
Some text
<tool_call>
{"name": "tool_b", "arguments": {"x": 1}}
</tool_call>"#;

        let calls = detect_tool_calls(output, ModelFamily::Qwen);

        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].name, "tool_a");
        assert_eq!(calls[1].name, "tool_b");
    }

    #[test]
    fn test_detect_no_tool_calls() {
        let output = "Just a regular response without any tool calls.";
        let calls = detect_tool_calls(output, ModelFamily::Qwen);
        assert!(calls.is_empty());
    }

    #[test]
    fn test_detect_malformed_tool_call() {
        let output = r#"<tool_call>
not valid json
</tool_call>"#;

        let calls = detect_tool_calls(output, ModelFamily::Qwen);
        assert!(calls.is_empty()); // Gracefully handle malformed JSON
    }

    // === Text Extraction Tests ===

    #[test]
    fn test_extract_text_with_tool_call() {
        let output = r#"Here is some text.
<tool_call>
{"name": "test", "arguments": {}}
</tool_call>
More text after."#;

        let content = extract_text_content(output, ModelFamily::Qwen);

        assert!(content.is_some());
        let text = content.unwrap();
        assert!(text.contains("Here is some text."));
        assert!(text.contains("More text after."));
        assert!(!text.contains("<tool_call>"));
    }

    #[test]
    fn test_extract_text_only_tool_call() {
        let output = r#"<tool_call>
{"name": "test", "arguments": {}}
</tool_call>"#;

        let content = extract_text_content(output, ModelFamily::Qwen);
        assert!(content.is_none());
    }

    #[test]
    fn test_extract_text_no_tool_call() {
        let output = "Just plain text.";
        let content = extract_text_content(output, ModelFamily::Qwen);

        assert!(content.is_some());
        assert_eq!(content.unwrap(), "Just plain text.");
    }

    // === Processing Tests ===

    #[test]
    fn test_process_model_output_with_tool_call() {
        let output = r#"<tool_call>
{"name": "get_weather", "arguments": {"location": "Seattle"}}
</tool_call>"#;

        let result = process_model_output(output, ModelFamily::Qwen);

        assert_eq!(result.finish_reason, "tool_calls");
        assert!(result.content.is_none());
        assert_eq!(result.tool_calls.len(), 1);
        assert_eq!(result.tool_calls[0].function.name, "get_weather");
    }

    #[test]
    fn test_process_model_output_no_tool_call() {
        let output = "This is a regular response.";

        let result = process_model_output(output, ModelFamily::Qwen);

        assert_eq!(result.finish_reason, "stop");
        assert!(result.content.is_some());
        assert!(result.tool_calls.is_empty());
    }

    #[test]
    fn test_process_model_output_mixed() {
        let output = r#"Let me help you with that.
<tool_call>
{"name": "search", "arguments": {"query": "test"}}
</tool_call>"#;

        let result = process_model_output(output, ModelFamily::Qwen);

        assert_eq!(result.finish_reason, "tool_calls");
        assert!(result.content.is_some());
        assert!(result.content.unwrap().contains("Let me help you"));
        assert_eq!(result.tool_calls.len(), 1);
    }

    // === Validation Tests ===

    #[test]
    fn test_validate_tool_exists() {
        let tools = vec![
            make_tool("tool_a", "A", json!({})),
            make_tool("tool_b", "B", json!({})),
        ];

        assert!(validate_tool_exists("tool_a", &tools));
        assert!(validate_tool_exists("tool_b", &tools));
        assert!(!validate_tool_exists("tool_c", &tools));
    }

    // === DetectedToolCall Conversion ===

    #[test]
    fn test_detected_to_tool_call() {
        let detected = DetectedToolCall {
            id: "call_abc123".to_string(),
            name: "test_function".to_string(),
            arguments: r#"{"key": "value"}"#.to_string(),
        };

        let tool_call = detected.to_tool_call();

        assert_eq!(tool_call.id, "call_abc123");
        assert_eq!(tool_call.call_type, "function");
        assert_eq!(tool_call.function.name, "test_function");
        assert_eq!(tool_call.function.arguments, r#"{"key": "value"}"#);
    }

    // === Tool Choice Tests ===

    #[test]
    fn test_should_include_tools_none_default() {
        // Default (None) should include tools
        assert!(should_include_tools(None));
    }

    #[test]
    fn test_should_include_tools_auto() {
        let choice = ToolChoice::String("auto".to_string());
        assert!(should_include_tools(Some(&choice)));
    }

    #[test]
    fn test_should_include_tools_none_string() {
        let choice = ToolChoice::String("none".to_string());
        assert!(!should_include_tools(Some(&choice)));
    }

    #[test]
    fn test_should_include_tools_required() {
        let choice = ToolChoice::String("required".to_string());
        assert!(should_include_tools(Some(&choice)));
    }

    #[test]
    fn test_should_include_tools_specific_tool() {
        use crate::api_types::{ToolChoiceFunction, ToolChoiceFunctionName};
        let choice = ToolChoice::Tool(ToolChoiceFunction {
            choice_type: "function".to_string(),
            function: ToolChoiceFunctionName {
                name: "get_weather".to_string(),
            },
        });
        assert!(should_include_tools(Some(&choice)));
    }

    #[test]
    fn test_get_forced_tool_none() {
        assert!(get_forced_tool(None).is_none());
    }

    #[test]
    fn test_get_forced_tool_auto() {
        let choice = ToolChoice::String("auto".to_string());
        assert!(get_forced_tool(Some(&choice)).is_none());
    }

    #[test]
    fn test_get_forced_tool_specific() {
        use crate::api_types::{ToolChoiceFunction, ToolChoiceFunctionName};
        let choice = ToolChoice::Tool(ToolChoiceFunction {
            choice_type: "function".to_string(),
            function: ToolChoiceFunctionName {
                name: "get_weather".to_string(),
            },
        });
        assert_eq!(get_forced_tool(Some(&choice)), Some("get_weather"));
    }

    // === Llama Format Tests ===

    #[test]
    fn test_format_single_tool_llama() {
        let tool = make_tool(
            "get_weather",
            "Get current weather for a location",
            json!({
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"}
                },
                "required": ["location"]
            }),
        );

        let result = format_tools_for_prompt(&[tool], ModelFamily::Llama);

        assert!(result.contains("get_weather"));
        assert!(result.contains("Get current weather"));
        assert!(result.contains("<|python_tag|>"));
    }

    #[test]
    fn test_detect_llama_tool_call() {
        let output = r#"I'll check the weather.
<|python_tag|>{"name": "get_weather", "arguments": {"location": "Seattle"}}"#;

        let calls = detect_tool_calls(output, ModelFamily::Llama);

        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "get_weather");
        assert!(calls[0].arguments.contains("Seattle"));
    }

    #[test]
    fn test_extract_text_llama() {
        let output = r#"Here is some text.
<|python_tag|>{"name": "test", "arguments": {}}
More text after."#;

        let content = extract_text_content(output, ModelFamily::Llama);

        assert!(content.is_some());
        let text = content.unwrap();
        assert!(text.contains("Here is some text."));
        assert!(text.contains("More text after."));
        assert!(!text.contains("<|python_tag|>"));
    }

    // === Mistral Format Tests ===

    #[test]
    fn test_format_single_tool_mistral() {
        let tool = make_tool(
            "get_weather",
            "Get current weather for a location",
            json!({
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"}
                },
                "required": ["location"]
            }),
        );

        let result = format_tools_for_prompt(&[tool], ModelFamily::Mistral);

        assert!(result.contains("[AVAILABLE_TOOLS]"));
        assert!(result.contains("get_weather"));
        assert!(result.contains("[TOOL_CALLS]"));
    }

    #[test]
    fn test_detect_mistral_tool_call() {
        let output = r#"I'll check the weather.
[TOOL_CALLS] [{"name": "get_weather", "arguments": {"location": "Seattle"}}]"#;

        let calls = detect_tool_calls(output, ModelFamily::Mistral);

        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "get_weather");
        assert!(calls[0].arguments.contains("Seattle"));
    }

    #[test]
    fn test_extract_text_mistral() {
        let output = r#"Here is some text.
[TOOL_CALLS] [{"name": "test", "arguments": {}}]
More text after."#;

        let content = extract_text_content(output, ModelFamily::Mistral);

        assert!(content.is_some());
        let text = content.unwrap();
        assert!(text.contains("Here is some text."));
        assert!(text.contains("More text after."));
        assert!(!text.contains("[TOOL_CALLS]"));
    }

    #[test]
    fn test_llama_falls_back_to_qwen_format() {
        // Llama detection should fall back to Qwen format if <|python_tag|> not found
        let output = r#"<tool_call>
{"name": "get_weather", "arguments": {"location": "Seattle"}}
</tool_call>"#;

        let calls = detect_tool_calls(output, ModelFamily::Llama);

        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "get_weather");
    }

    #[test]
    fn test_mistral_falls_back_to_qwen_format() {
        // Mistral detection should fall back to Qwen format if [TOOL_CALLS] not found
        let output = r#"<tool_call>
{"name": "get_weather", "arguments": {"location": "Seattle"}}
</tool_call>"#;

        let calls = detect_tool_calls(output, ModelFamily::Mistral);

        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "get_weather");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // PHASE 3 TDD TESTS - RED PHASE
    // These tests specify Phase 3 behavior. They should FAIL until implemented.
    // ═══════════════════════════════════════════════════════════════════════════

    mod phase3_streaming {
        use super::*;

        /// Streaming buffer should detect when we're potentially inside a tool call marker.
        /// This is needed to avoid streaming partial tool call content to the client.
        #[test]
        fn test_buffer_detects_potential_tool_start_qwen() {
            // "<tool" could be start of "<tool_call>"
            assert!(buffer_might_contain_tool_start("<tool", ModelFamily::Qwen));
            assert!(buffer_might_contain_tool_start("<tool_", ModelFamily::Qwen));
            assert!(buffer_might_contain_tool_start(
                "<tool_call",
                ModelFamily::Qwen
            ));

            // Regular text should not trigger buffering
            assert!(!buffer_might_contain_tool_start(
                "hello world",
                ModelFamily::Qwen
            ));
            assert!(!buffer_might_contain_tool_start(
                "the tool is ready",
                ModelFamily::Qwen
            ));
        }

        #[test]
        fn test_buffer_detects_potential_tool_start_llama() {
            assert!(buffer_might_contain_tool_start(
                "<|python",
                ModelFamily::Llama
            ));
            assert!(buffer_might_contain_tool_start(
                "<|python_tag",
                ModelFamily::Llama
            ));
            assert!(!buffer_might_contain_tool_start(
                "hello",
                ModelFamily::Llama
            ));
        }

        #[test]
        fn test_buffer_detects_potential_tool_start_mistral() {
            assert!(buffer_might_contain_tool_start(
                "[TOOL",
                ModelFamily::Mistral
            ));
            assert!(buffer_might_contain_tool_start(
                "[TOOL_CALLS",
                ModelFamily::Mistral
            ));
            assert!(!buffer_might_contain_tool_start(
                "hello",
                ModelFamily::Mistral
            ));
        }

        /// Should extract a complete tool call from a buffer, returning remaining content.
        #[test]
        fn test_try_extract_complete_tool_call_qwen() {
            let buffer = r#"Some text<tool_call>
{"name": "test", "arguments": {"key": "value"}}
</tool_call>More text"#;

            let result = try_extract_complete_tool_call(buffer, ModelFamily::Qwen);

            assert!(result.found);
            assert_eq!(result.text_before, Some("Some text".to_string()));
            assert_eq!(result.call.as_ref().unwrap().name, "test");
            assert_eq!(result.remaining, "More text");
        }

        #[test]
        fn test_try_extract_incomplete_tool_call() {
            // Incomplete - no closing tag yet
            let buffer = r#"<tool_call>
{"name": "test", "arguments": {"key": "value"}}"#;

            let result = try_extract_complete_tool_call(buffer, ModelFamily::Qwen);

            assert!(!result.found);
            assert!(result.call.is_none());
        }

        #[test]
        fn test_definitely_not_tool_call() {
            // If we've buffered enough and it's clearly not a tool marker
            assert!(definitely_not_tool_call(
                "<tooltip>hover</tooltip>",
                ModelFamily::Qwen
            ));
            assert!(!definitely_not_tool_call("<tool_call>", ModelFamily::Qwen));
        }
    }

    mod phase3_parallel_tool_calls {
        use super::*;

        /// When parallel_tool_calls is false, only the first tool call should be returned.
        #[test]
        fn test_enforce_single_tool_call() {
            let calls = vec![
                DetectedToolCall {
                    id: "call_1".to_string(),
                    name: "tool_a".to_string(),
                    arguments: "{}".to_string(),
                },
                DetectedToolCall {
                    id: "call_2".to_string(),
                    name: "tool_b".to_string(),
                    arguments: "{}".to_string(),
                },
            ];

            // When parallel_tool_calls = false, should return only first call
            let enforced = enforce_parallel_tool_calls(calls.clone(), false);
            assert_eq!(enforced.len(), 1);
            assert_eq!(enforced[0].name, "tool_a");

            // When parallel_tool_calls = true (or default), return all
            let all = enforce_parallel_tool_calls(calls, true);
            assert_eq!(all.len(), 2);
        }

        /// Processing should respect parallel_tool_calls setting.
        #[test]
        fn test_process_model_output_respects_parallel() {
            let output = r#"<tool_call>
{"name": "tool_a", "arguments": {}}
</tool_call>
<tool_call>
{"name": "tool_b", "arguments": {}}
</tool_call>"#;

            // With parallel disabled, should only get first tool
            let result = process_model_output_with_options(
                output,
                ModelFamily::Qwen,
                ProcessingOptions {
                    parallel_tool_calls: false,
                    ..Default::default()
                },
            );
            assert_eq!(result.tool_calls.len(), 1);
            assert_eq!(result.tool_calls[0].function.name, "tool_a");
        }
    }

    mod phase3_strict_mode {
        use super::*;

        /// Strict mode should validate tool arguments against the JSON schema.
        #[test]
        fn test_validate_tool_arguments_valid() {
            let schema = json!({
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            });

            let arguments = r#"{"location": "Seattle", "units": "celsius"}"#;
            let result = validate_tool_arguments(arguments, &schema);

            assert!(result.is_ok());
        }

        #[test]
        fn test_validate_tool_arguments_missing_required() {
            let schema = json!({
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
                "required": ["location"]
            });

            let arguments = r#"{}"#; // Missing required "location"
            let result = validate_tool_arguments(arguments, &schema);

            assert!(result.is_err());
            assert!(result.unwrap_err().contains("location"));
        }

        #[test]
        fn test_validate_tool_arguments_wrong_type() {
            let schema = json!({
                "type": "object",
                "properties": {
                    "count": {"type": "integer"}
                }
            });

            let arguments = r#"{"count": "not a number"}"#;
            let result = validate_tool_arguments(arguments, &schema);

            assert!(result.is_err());
        }

        #[test]
        fn test_validate_tool_arguments_invalid_enum() {
            let schema = json!({
                "type": "object",
                "properties": {
                    "status": {"type": "string", "enum": ["active", "inactive"]}
                }
            });

            let arguments = r#"{"status": "unknown"}"#;
            let result = validate_tool_arguments(arguments, &schema);

            assert!(result.is_err());
        }

        /// When strict=true on a tool, arguments should be validated.
        #[test]
        fn test_process_validates_strict_tools() {
            let tool = Tool {
                tool_type: "function".to_string(),
                function: crate::api_types::FunctionDefinition {
                    name: "get_weather".to_string(),
                    description: Some("Get weather".to_string()),
                    parameters: Some(json!({
                        "type": "object",
                        "properties": {
                            "location": {"type": "string"}
                        },
                        "required": ["location"]
                    })),
                    strict: Some(true), // Strict mode enabled
                },
            };

            let output = r#"<tool_call>
{"name": "get_weather", "arguments": {}}
</tool_call>"#; // Missing required location

            let result = process_model_output_with_validation(output, ModelFamily::Qwen, &[tool]);

            // Should report validation errors
            assert!(!result.validation_errors.is_empty());
        }
    }

    mod phase3_deep_json_parsing {
        use super::*;

        /// Current regex fails with deeply nested JSON. This test ensures proper parsing.
        #[test]
        fn test_extract_deeply_nested_json() {
            // 3 levels of nesting - current regex fails
            let json_str =
                r#"{"name": "test", "arguments": {"outer": {"middle": {"inner": "value"}}}}"#;

            let result = extract_json_object(json_str, 0);

            assert!(result.is_some());
            let extracted = result.unwrap();
            assert!(extracted.contains("inner"));
            assert!(extracted.contains("value"));
        }

        #[test]
        fn test_extract_json_with_arrays() {
            let json_str = r#"{"items": [{"a": 1}, {"b": [1, 2, {"c": 3}]}]}"#;

            let result = extract_json_object(json_str, 0);

            assert!(result.is_some());
            let parsed: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
            assert!(parsed.get("items").is_some());
        }

        #[test]
        fn test_extract_json_with_escaped_quotes() {
            let json_str = r#"{"message": "He said \"hello\""}"#;

            let result = extract_json_object(json_str, 0);

            assert!(result.is_some());
        }

        #[test]
        fn test_detect_deeply_nested_tool_call() {
            // This should work with proper JSON parsing (currently fails with regex)
            let output = r#"<tool_call>
{"name": "complex_tool", "arguments": {"data": {"level1": {"level2": {"level3": "deep"}}}}}
</tool_call>"#;

            let calls = detect_tool_calls(output, ModelFamily::Qwen);

            assert_eq!(calls.len(), 1);
            let args: serde_json::Value = serde_json::from_str(&calls[0].arguments).unwrap();
            assert!(args["data"]["level1"]["level2"]["level3"].as_str() == Some("deep"));
        }

        #[test]
        fn test_llama_deeply_nested() {
            let output = r#"<|python_tag|>{"name": "test", "arguments": {"a": {"b": {"c": {"d": "deep"}}}}}"#;

            let calls = detect_tool_calls(output, ModelFamily::Llama);

            assert_eq!(calls.len(), 1);
            let args: serde_json::Value = serde_json::from_str(&calls[0].arguments).unwrap();
            assert_eq!(args["a"]["b"]["c"]["d"], "deep");
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // PHASE 3 EDGE CASES - Tests for bugs found during code review
    // These tests are expected to FAIL until the bugs are fixed (TDD RED phase)
    // ═══════════════════════════════════════════════════════════════════════════

    mod phase3_edge_cases {
        use super::*;

        // ─────────────────────────────────────────────────────────────────────────
        // BUG 1: try_extract_qwen finds end tag before start tag
        // Line 660: buffer.find(end_tag) finds FIRST occurrence, not matched one
        // ─────────────────────────────────────────────────────────────────────────

        /// If a stray end tag appears before the real tool call, extraction should
        /// still find the correct tool call, not fail or extract garbage.
        #[test]
        fn test_qwen_end_tag_before_start_tag() {
            // Pathological case: end tag appears before start tag
            let buffer = r#"</tool_call>garbage<tool_call>
{"name": "real_tool", "arguments": {"key": "value"}}
</tool_call>remaining"#;

            let result = try_extract_complete_tool_call(buffer, ModelFamily::Qwen);

            // Should find the real tool call, not extract garbage
            assert!(result.found, "Should find the valid tool call");
            assert_eq!(result.call.as_ref().unwrap().name, "real_tool");
            assert_eq!(result.remaining, "remaining");
        }

        /// Multiple tool calls with stray end tags should parse correctly.
        #[test]
        fn test_qwen_multiple_stray_end_tags() {
            let buffer = r#"text</tool_call></tool_call><tool_call>
{"name": "test", "arguments": {}}
</tool_call>"#;

            let result = try_extract_complete_tool_call(buffer, ModelFamily::Qwen);

            assert!(result.found);
            assert_eq!(result.call.as_ref().unwrap().name, "test");
        }

        // ─────────────────────────────────────────────────────────────────────────
        // BUG 2: ProcessingOptions.tools is dead code
        // Line 866: The tools field is never used in process_model_output_with_options
        // ─────────────────────────────────────────────────────────────────────────

        /// For tool validation, use process_model_output_with_validation.
        /// ProcessingOptions is focused on parallel_tool_calls setting only.
        #[test]
        fn test_use_validation_function_for_tool_checking() {
            let tool = Tool {
                tool_type: "function".to_string(),
                function: crate::api_types::FunctionDefinition {
                    name: "known_tool".to_string(),
                    description: Some("A known tool".to_string()),
                    parameters: Some(json!({
                        "type": "object",
                        "properties": {},
                    })),
                    strict: Some(true),
                },
            };

            let output = r#"<tool_call>
{"name": "unknown_tool", "arguments": {}}
</tool_call>"#;

            // Use the validation function (not ProcessingOptions) for tool checking
            let result = process_model_output_with_validation(output, ModelFamily::Qwen, &[tool]);

            // Tool calls are still returned, but validation errors are reported
            assert_eq!(result.result.tool_calls.len(), 1);
            // Unknown tool validation is separate from schema validation
            // (schema validation only runs for tools with strict=true)
        }

        // ─────────────────────────────────────────────────────────────────────────
        // BUG 3: DetectedCallsValidation.valid_calls misleading name
        // Line 1104: Returns ALL calls, not just valid ones
        // ─────────────────────────────────────────────────────────────────────────

        /// The valid_calls field should only contain calls to known tools.
        /// Currently it returns ALL calls, which is misleading.
        #[test]
        fn test_valid_calls_only_contains_valid() {
            let tools = vec![make_tool("known_tool", "A known tool", json!({}))];

            let detected = vec![
                DetectedToolCall {
                    id: "call_1".to_string(),
                    name: "known_tool".to_string(),
                    arguments: "{}".to_string(),
                },
                DetectedToolCall {
                    id: "call_2".to_string(),
                    name: "unknown_tool".to_string(),
                    arguments: "{}".to_string(),
                },
            ];

            let result = validate_detected_calls(&detected, &tools);

            // Expected: valid_calls should ONLY contain known tools
            // Current bug: valid_calls contains ALL calls
            assert_eq!(result.unknown_tools.len(), 1);
            assert_eq!(result.unknown_tools[0], "unknown_tool");

            // This assertion will fail until bug is fixed:
            // valid_calls should only have the known tool
            assert_eq!(
                result.valid_calls.len(),
                1,
                "valid_calls should only contain calls to known tools"
            );
            assert_eq!(result.valid_calls[0].name, "known_tool");
        }

        // ─────────────────────────────────────────────────────────────────────────
        // EDGE CASE: Mismatched brackets in JSON
        // ─────────────────────────────────────────────────────────────────────────

        /// Mismatched brackets should not cause infinite loops or panics.
        #[test]
        fn test_mismatched_brackets_no_panic() {
            let json_str = r#"{"key": {"unclosed": "value"}"#;
            let result = extract_json_object(json_str, 0);

            // Should return None, not panic or loop infinitely
            assert!(result.is_none());
        }

        #[test]
        fn test_extra_closing_bracket() {
            let json_str = r#"{"key": "value"}}"#;
            let result = extract_json_object(json_str, 0);

            // Should extract the valid JSON, ignoring extra bracket
            assert!(result.is_some());
            let extracted = result.unwrap();
            assert_eq!(extracted, r#"{"key": "value"}"#);
        }

        // ─────────────────────────────────────────────────────────────────────────
        // EDGE CASE: Empty or whitespace inputs
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_empty_tool_name() {
            let output = r#"<tool_call>
{"name": "", "arguments": {"key": "value"}}
</tool_call>"#;

            let calls = detect_tool_calls(output, ModelFamily::Qwen);

            // Should still parse, empty name is valid JSON
            assert_eq!(calls.len(), 1);
            assert_eq!(calls[0].name, "");
        }

        #[test]
        fn test_whitespace_only_buffer() {
            let buffer = "   \n\t   ";
            let result = try_extract_complete_tool_call(buffer, ModelFamily::Qwen);

            assert!(!result.found);
            assert!(result.call.is_none());
        }

        #[test]
        fn test_null_arguments() {
            let output = r#"<tool_call>
{"name": "test", "arguments": null}
</tool_call>"#;

            let calls = detect_tool_calls(output, ModelFamily::Qwen);

            assert_eq!(calls.len(), 1);
            assert_eq!(calls[0].arguments, "null");
        }

        // ─────────────────────────────────────────────────────────────────────────
        // EDGE CASE: Unicode and special characters
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_unicode_in_arguments() {
            let output = r#"<tool_call>
{"name": "test", "arguments": {"message": "Hello 世界 🌍"}}
</tool_call>"#;

            let calls = detect_tool_calls(output, ModelFamily::Qwen);

            assert_eq!(calls.len(), 1);
            let args: serde_json::Value = serde_json::from_str(&calls[0].arguments).unwrap();
            assert_eq!(args["message"], "Hello 世界 🌍");
        }

        #[test]
        fn test_brackets_in_string_values() {
            // Brackets inside strings should not confuse the parser
            let output = r#"<tool_call>
{"name": "test", "arguments": {"code": "arr[0] = {a: 1}"}}
</tool_call>"#;

            let calls = detect_tool_calls(output, ModelFamily::Qwen);

            assert_eq!(calls.len(), 1);
            let args: serde_json::Value = serde_json::from_str(&calls[0].arguments).unwrap();
            assert_eq!(args["code"], "arr[0] = {a: 1}");
        }

        // ─────────────────────────────────────────────────────────────────────────
        // EDGE CASE: Very deeply nested JSON (stress test)
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_ten_levels_deep_nesting() {
            let output = r#"<tool_call>
{"name": "deep", "arguments": {"l1": {"l2": {"l3": {"l4": {"l5": {"l6": {"l7": {"l8": {"l9": {"l10": "bottom"}}}}}}}}}}}
</tool_call>"#;

            let calls = detect_tool_calls(output, ModelFamily::Qwen);

            assert_eq!(calls.len(), 1);
            let args: serde_json::Value = serde_json::from_str(&calls[0].arguments).unwrap();
            assert_eq!(
                args["l1"]["l2"]["l3"]["l4"]["l5"]["l6"]["l7"]["l8"]["l9"]["l10"],
                "bottom"
            );
        }
    }

    mod phase3_unknown_tool_logging {
        use super::*;

        /// Detected tool calls should be validated against available tools.
        #[test]
        fn test_validate_detected_calls_known_tools() {
            let tools = vec![
                make_tool("tool_a", "A", json!({})),
                make_tool("tool_b", "B", json!({})),
            ];

            let detected = vec![DetectedToolCall {
                id: "call_1".to_string(),
                name: "tool_a".to_string(),
                arguments: "{}".to_string(),
            }];

            let result = validate_detected_calls(&detected, &tools);

            assert!(result.unknown_tools.is_empty());
            assert_eq!(result.valid_calls.len(), 1);
        }

        #[test]
        fn test_validate_detected_calls_unknown_tools() {
            let tools = vec![make_tool("tool_a", "A", json!({}))];

            let detected = vec![DetectedToolCall {
                id: "call_1".to_string(),
                name: "unknown_tool".to_string(),
                arguments: "{}".to_string(),
            }];

            let result = validate_detected_calls(&detected, &tools);

            // Unknown tool should be reported
            assert_eq!(result.unknown_tools.len(), 1);
            assert_eq!(result.unknown_tools[0], "unknown_tool");
            // valid_calls should NOT contain unknown tools
            assert_eq!(result.valid_calls.len(), 0);
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // STREAMING TOOL DETECTOR TESTS
    // ═══════════════════════════════════════════════════════════════════════════

    mod streaming_tool_detector {
        use super::*;

        // ─────────────────────────────────────────────────────────────────────────
        // Basic functionality
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_new_detector() {
            let detector = StreamingToolDetector::new(ModelFamily::Qwen);
            assert!(!detector.is_buffering());
            assert!(detector.buffer().is_empty());
        }

        #[test]
        fn test_plain_text_streams_immediately() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let events = detector.process_chunk("Hello, world!");

            assert_eq!(events.len(), 1);
            assert!(matches!(&events[0], ToolDetectionEvent::Text(t) if t == "Hello, world!"));
            assert!(!detector.is_buffering());
        }

        #[test]
        fn test_multiple_plain_text_chunks() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let events1 = detector.process_chunk("Hello ");
            let events2 = detector.process_chunk("world!");

            assert_eq!(events1.len(), 1);
            assert!(matches!(&events1[0], ToolDetectionEvent::Text(t) if t == "Hello "));

            assert_eq!(events2.len(), 1);
            assert!(matches!(&events2[0], ToolDetectionEvent::Text(t) if t == "world!"));
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Tool call detection
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_complete_tool_call_in_one_chunk() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let chunk = r#"<tool_call>
{"name": "get_weather", "arguments": {"location": "NYC"}}
</tool_call>"#;

            let events = detector.process_chunk(chunk);

            assert_eq!(events.len(), 1);
            match &events[0] {
                ToolDetectionEvent::ToolCall(call) => {
                    assert_eq!(call.name, "get_weather");
                    assert!(call.arguments.contains("NYC"));
                },
                other => panic!("Expected ToolCall, got {:?}", other),
            }
        }

        #[test]
        fn test_tool_call_split_across_chunks() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            // First chunk: partial tool marker
            let events1 = detector.process_chunk("<tool");
            assert!(detector.is_buffering());
            assert_eq!(events1.len(), 1);
            assert!(matches!(events1[0], ToolDetectionEvent::Buffering));

            // Second chunk: more of the marker
            let events2 = detector.process_chunk("_call>");
            assert!(detector.is_buffering());

            // Third chunk: JSON content
            let events3 = detector.process_chunk(
                r#"
{"name": "test", "arguments": {}}"#,
            );
            assert!(detector.is_buffering());

            // Fourth chunk: closing tag
            let events4 = detector.process_chunk("\n</tool_call>");

            // Should now have the complete tool call
            assert!(!detector.is_buffering());
            assert_eq!(events4.len(), 1);
            match &events4[0] {
                ToolDetectionEvent::ToolCall(call) => {
                    assert_eq!(call.name, "test");
                },
                other => panic!("Expected ToolCall, got {:?}", other),
            }
        }

        #[test]
        fn test_text_before_tool_call() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let chunk = r#"Some intro text<tool_call>
{"name": "test", "arguments": {}}
</tool_call>"#;

            let events = detector.process_chunk(chunk);

            assert_eq!(events.len(), 2);
            assert!(matches!(&events[0], ToolDetectionEvent::Text(t) if t == "Some intro text"));
            assert!(matches!(&events[1], ToolDetectionEvent::ToolCall(_)));
        }

        #[test]
        fn test_text_after_tool_call() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let chunk = r#"<tool_call>
{"name": "test", "arguments": {}}
</tool_call>Some trailing text"#;

            let events = detector.process_chunk(chunk);

            // Should have: ToolCall, then Text (trailing text emitted immediately)
            assert_eq!(events.len(), 2);
            assert!(matches!(&events[0], ToolDetectionEvent::ToolCall(_)));
            assert!(matches!(&events[1], ToolDetectionEvent::Text(t) if t == "Some trailing text"));

            // finish() should return empty since buffer was already flushed
            let final_events = detector.finish();
            assert!(final_events.is_empty());
        }

        #[test]
        fn test_multiple_tool_calls() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let chunk = r#"<tool_call>
{"name": "tool_a", "arguments": {}}
</tool_call>
<tool_call>
{"name": "tool_b", "arguments": {}}
</tool_call>"#;

            let events = detector.process_chunk(chunk);

            // Should have both tool calls
            let tool_calls: Vec<_> = events
                .iter()
                .filter(|e| matches!(e, ToolDetectionEvent::ToolCall(_)))
                .collect();
            assert_eq!(tool_calls.len(), 2);
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Edge cases
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_finish_flushes_incomplete_buffer() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            // Start what looks like a tool call but never completes
            detector.process_chunk("<tool_call>");
            detector.process_chunk(r#"{"name": "incomplete""#);

            assert!(detector.is_buffering());

            // Finish should flush the buffer as text
            let events = detector.finish();
            assert_eq!(events.len(), 1);
            match &events[0] {
                ToolDetectionEvent::Text(text) => {
                    assert!(text.contains("<tool_call>"));
                    assert!(text.contains("incomplete"));
                },
                other => panic!("Expected Text, got {:?}", other),
            }
        }

        #[test]
        fn test_empty_finish() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            // Process complete tool call leaving empty buffer
            detector.process_chunk(r#"<tool_call>{"name": "t", "arguments": {}}</tool_call>"#);

            let events = detector.finish();
            assert!(events.is_empty());
        }

        #[test]
        fn test_false_positive_tool_start() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            // Looks like it might start a tool call but doesn't
            let events1 = detector.process_chunk("<tool");
            assert!(detector.is_buffering());

            // Continues into something that's clearly not a tool call
            let events2 = detector.process_chunk("tip>helpful tip</tooltip>");

            // Should emit the whole thing as text
            assert!(!detector.is_buffering());
            let has_text = events2
                .iter()
                .any(|e| matches!(e, ToolDetectionEvent::Text(_)));
            assert!(has_text);
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Model family variations
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_llama_format() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Llama);

            let chunk = r#"<|python_tag|>{"name": "test", "arguments": {"x": 1}}"#;
            let events = detector.process_chunk(chunk);

            assert_eq!(events.len(), 1);
            assert!(matches!(&events[0], ToolDetectionEvent::ToolCall(c) if c.name == "test"));
        }

        #[test]
        fn test_mistral_format() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Mistral);

            let chunk = r#"[TOOL_CALLS][{"name": "test", "arguments": {}}]"#;
            let events = detector.process_chunk(chunk);

            assert_eq!(events.len(), 1);
            assert!(matches!(&events[0], ToolDetectionEvent::ToolCall(c) if c.name == "test"));
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Stress tests
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_character_by_character_streaming() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let full_text = r#"Hi<tool_call>{"name": "t", "arguments": {}}</tool_call>bye"#;

            let mut all_events = Vec::new();
            for c in full_text.chars() {
                all_events.extend(detector.process_chunk(&c.to_string()));
            }
            all_events.extend(detector.finish());

            // Should have: Text("Hi"), ToolCall, Text("bye")
            let text_events: Vec<_> = all_events
                .iter()
                .filter(|e| matches!(e, ToolDetectionEvent::Text(_)))
                .collect();
            let tool_events: Vec<_> = all_events
                .iter()
                .filter(|e| matches!(e, ToolDetectionEvent::ToolCall(_)))
                .collect();

            assert_eq!(tool_events.len(), 1);
            // Text events may be merged or separate depending on buffering
            assert!(!text_events.is_empty());
        }

        #[test]
        fn test_deeply_nested_json() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);

            let chunk = r#"<tool_call>
{"name": "nested", "arguments": {"a": {"b": {"c": {"d": "deep"}}}}}
</tool_call>"#;

            let events = detector.process_chunk(chunk);

            assert_eq!(events.len(), 1);
            match &events[0] {
                ToolDetectionEvent::ToolCall(call) => {
                    assert_eq!(call.name, "nested");
                    let args: serde_json::Value = serde_json::from_str(&call.arguments).unwrap();
                    assert_eq!(args["a"]["b"]["c"]["d"], "deep");
                },
                other => panic!("Expected ToolCall, got {:?}", other),
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // AGENT-CENTRIC SSE EVENT TESTS
    // See INFERNUM-SPEC.md §10 for protocol specification
    // ═══════════════════════════════════════════════════════════════════════════

    mod sse_events {
        use super::*;

        // ─────────────────────────────────────────────────────────────────────────
        // JSON serialization format tests
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_text_event_json_format() {
            let event = SseEvent::text("Hello world");
            let json = event.to_json();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["type"], "text");
            assert_eq!(parsed["content"], "Hello world");
            // Should NOT have other fields
            assert!(parsed.get("id").is_none());
            assert!(parsed.get("name").is_none());
        }

        #[test]
        fn test_tool_call_event_json_format() {
            let call = DetectedToolCall {
                id: "call_abc123".to_string(),
                name: "get_weather".to_string(),
                arguments: r#"{"location":"NYC","units":"celsius"}"#.to_string(),
            };
            let event = SseEvent::tool_call(&call);
            let json = event.to_json();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["type"], "tool_call");
            assert_eq!(parsed["id"], "call_abc123");
            assert_eq!(parsed["name"], "get_weather");
            assert_eq!(parsed["arguments"]["location"], "NYC");
            assert_eq!(parsed["arguments"]["units"], "celsius");
        }

        #[test]
        fn test_error_event_json_format() {
            let event = SseEvent::error("rate_limit", "Too many requests");
            let json = event.to_json();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["type"], "error");
            assert_eq!(parsed["code"], "rate_limit");
            assert_eq!(parsed["message"], "Too many requests");
            // details should be absent (not null)
            assert!(parsed.get("details").is_none());
        }

        #[test]
        fn test_error_event_with_details_json_format() {
            let event = SseEvent::error_with_details(
                "validation_error",
                "Invalid arguments",
                json!({"field": "location", "reason": "required"}),
            );
            let json = event.to_json();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["type"], "error");
            assert_eq!(parsed["details"]["field"], "location");
        }

        #[test]
        fn test_done_event_json_format() {
            let event = SseEvent::done("stop");
            let json = event.to_json();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["type"], "done");
            assert_eq!(parsed["finish_reason"], "stop");
            // usage should be absent (not null)
            assert!(parsed.get("usage").is_none());
        }

        #[test]
        fn test_done_event_with_usage_json_format() {
            let event = SseEvent::done_with_usage("tool_calls", 42, 18);
            let json = event.to_json();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["type"], "done");
            assert_eq!(parsed["finish_reason"], "tool_calls");
            assert_eq!(parsed["usage"]["prompt_tokens"], 42);
            assert_eq!(parsed["usage"]["completion_tokens"], 18);
            assert_eq!(parsed["usage"]["total_tokens"], 60);
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Deserialization tests (agents parsing our events)
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_deserialize_text_event() {
            let json = r#"{"type":"text","content":"Hello"}"#;
            let event: SseEvent = serde_json::from_str(json).unwrap();

            match event {
                SseEvent::Text { content } => assert_eq!(content, "Hello"),
                other => panic!("Expected Text, got {:?}", other),
            }
        }

        #[test]
        fn test_deserialize_tool_call_event() {
            let json = r#"{"type":"tool_call","id":"call_123","name":"test","arguments":{"x":1}}"#;
            let event: SseEvent = serde_json::from_str(json).unwrap();

            match event {
                SseEvent::ToolCall {
                    id,
                    name,
                    arguments,
                } => {
                    assert_eq!(id, "call_123");
                    assert_eq!(name, "test");
                    assert_eq!(arguments["x"], 1);
                },
                other => panic!("Expected ToolCall, got {:?}", other),
            }
        }

        #[test]
        fn test_deserialize_done_event() {
            let json = r#"{"type":"done","finish_reason":"stop"}"#;
            let event: SseEvent = serde_json::from_str(json).unwrap();

            match event {
                SseEvent::Done {
                    finish_reason,
                    usage,
                } => {
                    assert_eq!(finish_reason, "stop");
                    assert!(usage.is_none());
                },
                other => panic!("Expected Done, got {:?}", other),
            }
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Conversion from ToolDetectionEvent
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_convert_text_detection_to_sse() {
            let detection = ToolDetectionEvent::Text("Hello".to_string());
            let sse: Option<SseEvent> = detection.into();

            assert!(sse.is_some());
            match sse.unwrap() {
                SseEvent::Text { content } => assert_eq!(content, "Hello"),
                other => panic!("Expected Text, got {:?}", other),
            }
        }

        #[test]
        fn test_convert_tool_call_detection_to_sse() {
            let call = DetectedToolCall {
                id: "call_xyz".to_string(),
                name: "my_tool".to_string(),
                arguments: r#"{"a":1}"#.to_string(),
            };
            let detection = ToolDetectionEvent::ToolCall(call);
            let sse: Option<SseEvent> = detection.into();

            assert!(sse.is_some());
            match sse.unwrap() {
                SseEvent::ToolCall {
                    id,
                    name,
                    arguments,
                } => {
                    assert_eq!(id, "call_xyz");
                    assert_eq!(name, "my_tool");
                    assert_eq!(arguments["a"], 1);
                },
                other => panic!("Expected ToolCall, got {:?}", other),
            }
        }

        #[test]
        fn test_convert_buffering_detection_to_sse() {
            let detection = ToolDetectionEvent::Buffering;
            let sse: Option<SseEvent> = detection.into();

            // Buffering events should be skipped (None)
            assert!(sse.is_none());
        }

        // ─────────────────────────────────────────────────────────────────────────
        // Integration: StreamingToolDetector -> SseEvent stream
        // ─────────────────────────────────────────────────────────────────────────

        #[test]
        fn test_detector_to_sse_stream_text_only() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);
            let events = detector.process_chunk("Hello world");

            let sse_events: Vec<SseEvent> = events.into_iter().filter_map(|e| e.into()).collect();

            assert_eq!(sse_events.len(), 1);
            let json = sse_events[0].to_json();
            assert!(json.contains(r#""type":"text""#));
            assert!(json.contains(r#""content":"Hello world""#));
        }

        #[test]
        fn test_detector_to_sse_stream_with_tool_call() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);
            let chunk = r#"Let me help<tool_call>
{"name": "search", "arguments": {"query": "rust"}}
</tool_call>"#;

            let events = detector.process_chunk(chunk);
            let sse_events: Vec<SseEvent> = events.into_iter().filter_map(|e| e.into()).collect();

            assert_eq!(sse_events.len(), 2);

            // First: text
            match &sse_events[0] {
                SseEvent::Text { content } => assert_eq!(content, "Let me help"),
                other => panic!("Expected Text, got {:?}", other),
            }

            // Second: tool call
            match &sse_events[1] {
                SseEvent::ToolCall {
                    name, arguments, ..
                } => {
                    assert_eq!(name, "search");
                    assert_eq!(arguments["query"], "rust");
                },
                other => panic!("Expected ToolCall, got {:?}", other),
            }
        }

        #[test]
        fn test_full_streaming_session_to_sse() {
            let mut detector = StreamingToolDetector::new(ModelFamily::Qwen);
            let mut all_sse: Vec<SseEvent> = Vec::new();

            // Simulate streaming chunks
            let chunks = vec![
                "I'll check ",
                "the weather",
                "<tool_call>",
                r#"{"name": "get_weather", "arguments": {"location": "NYC"}}"#,
                "</tool_call>",
                " for you.",
            ];

            for chunk in chunks {
                let events = detector.process_chunk(chunk);
                all_sse.extend(events.into_iter().filter_map(|e| e.into()));
            }
            all_sse.extend(detector.finish().into_iter().filter_map(|e| e.into()));

            // Should have text events and a tool call
            let text_count = all_sse
                .iter()
                .filter(|e| matches!(e, SseEvent::Text { .. }))
                .count();
            let tool_count = all_sse
                .iter()
                .filter(|e| matches!(e, SseEvent::ToolCall { .. }))
                .count();

            assert!(text_count >= 1, "Should have text events");
            assert_eq!(tool_count, 1, "Should have exactly one tool call");

            // Verify the tool call is correct
            let tool_event = all_sse
                .iter()
                .find(|e| matches!(e, SseEvent::ToolCall { .. }))
                .unwrap();
            match tool_event {
                SseEvent::ToolCall {
                    name, arguments, ..
                } => {
                    assert_eq!(name, "get_weather");
                    assert_eq!(arguments["location"], "NYC");
                },
                _ => unreachable!(),
            }
        }
    }
}