everruns-core 0.14.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
// Chat Driver Abstractions
//
// This module encapsulates all abstractions needed to interact with LLM Providers:
// - ChatDriver trait and types for provider-agnostic LLM interactions
// - DriverRegistry for dynamic driver registration at startup
// - Message types for LLM calls
//
// Supports both simple text content and multipart content (text, images, audio).
//
// IMPORTANT: API keys must be provided from the database. The registry does NOT read
// from environment variables. Keys should be decrypted and passed via ProviderConfig.
//
// Design: Dependency inversion - provider crates (everruns-anthropic, everruns-openai)
// depend on core and register their drivers at startup. Core has no knowledge of
// specific provider implementations.

use crate::credential_schema::CredentialFormSchema;
use crate::error::{AgentLoopError, Result};
use crate::openresponses_protocol::{CompactRequest, CompactResponse};
use crate::runtime_agent::RuntimeAgent;
use crate::tool_types::{ToolCall, ToolDefinition};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::Stream;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;

// ============================================================================
// ChatDriver Trait
// ============================================================================

/// Type alias for the LLM response stream
pub type LlmResponseStream = Pin<Box<dyn Stream<Item = Result<LlmStreamEvent>> + Send>>;

/// Events emitted during LLM streaming
#[derive(Debug, Clone)]
pub enum LlmStreamEvent {
    /// Text delta (incremental content)
    TextDelta(String),
    /// Thinking delta (incremental reasoning content from extended thinking models)
    ThinkingDelta(String),
    /// Cryptographic signature for thinking content (Anthropic Claude)
    /// Emitted when a thinking block completes, before the Done event
    ThinkingSignature(String),
    /// Opaque assistant reasoning response item (OpenAI Responses).
    /// Carries provider-supplied opaque/encrypted reasoning artifacts plus safe
    /// summary text and per-item metadata. Plaintext hidden reasoning content is
    /// intentionally excluded so callers can persist this without exposing
    /// chain-of-thought.
    ReasonItem {
        /// Provider name (e.g., "openai").
        provider: String,
        /// Model identifier reported by the provider, if known.
        model: Option<String>,
        /// Provider-assigned identifier for the reasoning item.
        item_id: String,
        /// Provider-encrypted reasoning context, if supplied.
        encrypted_content: Option<String>,
        /// Safe summary text segments curated by the provider.
        summary: Vec<String>,
        /// Per-item reasoning token count, when the provider reports one.
        token_count: Option<u32>,
    },
    /// Tool calls from the LLM
    ToolCalls(Vec<ToolCall>),
    /// Streaming completed
    Done(Box<LlmCompletionMetadata>),
    /// Error during streaming
    Error(String),
}

/// Model information discovered from a provider's list_models API
///
/// Represents a model available from a provider. Used for dynamic model discovery
/// to sync available models from provider APIs into the database.
///
/// The `discovered_profile` field carries structured capability/limit metadata
/// parsed from the provider's API response (e.g., Anthropic's capabilities object).
/// During model sync, this profile is merged with hardcoded profiles: hardcoded
/// values take precedence (they include cost data not available from APIs),
/// but discovered data fills gaps for models without hardcoded profiles.
#[derive(Debug, Clone)]
pub struct DiscoveredModel {
    /// Model identifier (e.g., "gpt-5.2", "claude-opus-4-5-20251101")
    pub model_id: String,
    /// Human-readable display name (if provided by API)
    pub display_name: Option<String>,
    /// When the model was created/released
    pub created_at: Option<DateTime<Utc>>,
    /// Owner or organization (e.g., "openai", "system")
    pub owned_by: Option<String>,
    /// Structured profile built from provider API metadata (capabilities, limits).
    /// Populated by drivers that return rich model metadata (e.g., Anthropic /v1/models).
    pub discovered_profile: Option<crate::model::ModelProfile>,
}

/// Metadata about LLM completion
///
/// Contains token usage and completion information from the LLM response.
/// Cache token fields are provider-specific:
/// - OpenAI: `cache_read_tokens` from prompt_tokens_details.cached_tokens
/// - Anthropic: `cache_read_tokens` from cache_read_input_tokens,
///   `cache_creation_tokens` from cache_creation_input_tokens
#[derive(Debug, Clone, Default)]
pub struct LlmCompletionMetadata {
    /// Total tokens used
    pub total_tokens: Option<u32>,
    /// Prompt tokens
    pub prompt_tokens: Option<u32>,
    /// Completion tokens
    pub completion_tokens: Option<u32>,
    /// Tokens read from cache (reduces cost)
    pub cache_read_tokens: Option<u32>,
    /// Tokens written to cache (Anthropic-specific)
    pub cache_creation_tokens: Option<u32>,
    /// Authoritative cost of this generation in USD, when the provider reports
    /// it inline (e.g. OpenRouter's `usage.cost`). `None` for providers that do
    /// not return a cost.
    pub provider_cost_usd: Option<f64>,
    /// Model used
    pub model: Option<String>,
    /// Finish reason
    pub finish_reason: Option<String>,
    /// Retry metadata (present if rate limit retries occurred)
    pub retry_metadata: Option<crate::llm_retry::RetryMetadata>,
    /// Provider's response ID (e.g., OpenAI response ID from response.completed).
    /// Used for `previous_response_id` chaining and OTel tracing.
    pub response_id: Option<String>,
    /// Execution phase from the provider's response (e.g., "commentary", "final_answer").
    /// When present, this value should be preserved on the assistant message and sent
    /// back as-is in subsequent requests. Only set by providers with native phase support.
    pub phase: Option<String>,
}

/// Trait for LLM drivers
///
/// Implementations handle provider-specific API calls and response parsing.
///
/// # Error contract
///
/// Drivers surface provider failures as `AgentLoopError` and classify them
/// semantically at the provider boundary, where HTTP status and response body
/// are still available:
///
/// - request-too-large conditions => `AgentLoopError::request_too_large`
/// - missing/unknown model => `AgentLoopError::model_not_available`
/// - everything else => `AgentLoopError::llm_kind(LlmErrorKind::..., msg)`,
///   using `LlmErrorKind::from_provider_status` (HTTP drivers) or
///   `LlmErrorKind::from_error_text` (SDK drivers without a status). Plain
///   `AgentLoopError::llm` is reserved for unclassifiable errors; downstream
///   then falls back to string classification.
///
/// Quota/billing exhaustion (`LlmErrorKind::QuotaExhausted`) is non-transient
/// and must not be retried by driver retry loops even when the provider
/// reports it under a transient status like 429.
#[async_trait]
pub trait ChatDriver: Send + Sync {
    /// Call the LLM with streaming response
    async fn chat_completion_stream(
        &self,
        messages: Vec<LlmMessage>,
        config: &LlmCallConfig,
    ) -> Result<LlmResponseStream>;

    /// Call the LLM without streaming (convenience method)
    async fn chat_completion(
        &self,
        messages: Vec<LlmMessage>,
        config: &LlmCallConfig,
    ) -> Result<LlmResponse> {
        use futures::StreamExt;

        let mut stream = self.chat_completion_stream(messages, config).await?;
        let mut text = String::new();
        let mut thinking = String::new();
        let mut thinking_signature: Option<String> = None;
        let mut tool_calls = Vec::new();
        let mut metadata = LlmCompletionMetadata::default();

        while let Some(event) = stream.next().await {
            match event? {
                LlmStreamEvent::TextDelta(delta) => text.push_str(&delta),
                LlmStreamEvent::ThinkingDelta(delta) => thinking.push_str(&delta),
                LlmStreamEvent::ThinkingSignature(sig) => thinking_signature = Some(sig),
                LlmStreamEvent::ReasonItem {
                    encrypted_content, ..
                } => {
                    if let Some(sig) = encrypted_content {
                        thinking_signature = Some(sig);
                    }
                }
                LlmStreamEvent::ToolCalls(calls) => tool_calls = calls,
                LlmStreamEvent::Done(meta) => metadata = *meta,
                LlmStreamEvent::Error(err) => return Err(crate::error::AgentLoopError::llm(err)),
            }
        }

        Ok(LlmResponse {
            text,
            thinking: if thinking.is_empty() {
                None
            } else {
                Some(thinking)
            },
            thinking_signature,
            tool_calls: if tool_calls.is_empty() {
                None
            } else {
                Some(tool_calls)
            },
            metadata,
        })
    }

    /// List available models from the provider
    ///
    /// Returns `Ok(Some(models))` if the provider supports model listing,
    /// or `Ok(None)` if not supported (e.g., custom endpoints, proxies).
    ///
    /// Implementations should filter to chat/completion models only,
    /// excluding embedding models, TTS, whisper, etc.
    async fn list_models(&self) -> Result<Option<Vec<DiscoveredModel>>> {
        // Default: not supported. Providers override if they support listing.
        Ok(None)
    }

    /// Check if this driver supports the compact endpoint
    ///
    /// The compact endpoint compresses conversation history by replacing
    /// assistant messages, tool calls, and tool results with an encrypted
    /// compaction item. User messages are kept verbatim.
    ///
    /// Returns `true` if the driver supports compaction, `false` otherwise.
    /// Currently only supported by OpenAI's Responses API.
    fn supports_compact(&self) -> bool {
        // Default: not supported
        false
    }

    /// Compact a conversation to reduce context size
    ///
    /// This method compresses conversation history by calling the provider's
    /// compact endpoint. User messages are kept verbatim, while assistant
    /// messages, tool calls, and tool results are replaced by an encrypted
    /// compaction item that preserves latent context but is opaque.
    ///
    /// # Arguments
    ///
    /// * `request` - The compact request containing the model and input items
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(response))` if compaction succeeded,
    /// `Ok(None)` if compaction is not supported by this driver,
    /// or `Err` if an error occurred.
    ///
    /// The response contains the compacted output items which can be used
    /// directly as input for the next chat completion call.
    async fn compact(&self, _request: CompactRequest) -> Result<Option<CompactResponse>> {
        // Default: not supported
        Ok(None)
    }
}

/// Implement ChatDriver for `Box<dyn ChatDriver>` to allow dynamic dispatch
#[async_trait]
impl ChatDriver for Box<dyn ChatDriver> {
    async fn chat_completion_stream(
        &self,
        messages: Vec<LlmMessage>,
        config: &LlmCallConfig,
    ) -> Result<LlmResponseStream> {
        (**self).chat_completion_stream(messages, config).await
    }

    async fn chat_completion(
        &self,
        messages: Vec<LlmMessage>,
        config: &LlmCallConfig,
    ) -> Result<LlmResponse> {
        (**self).chat_completion(messages, config).await
    }

    async fn list_models(&self) -> Result<Option<Vec<DiscoveredModel>>> {
        (**self).list_models().await
    }

    fn supports_compact(&self) -> bool {
        (**self).supports_compact()
    }

    async fn compact(&self, request: CompactRequest) -> Result<Option<CompactResponse>> {
        (**self).compact(request).await
    }
}

// ============================================================================
// Message Types
// ============================================================================

/// Message format for LLM calls (provider-agnostic)
#[derive(Debug, Clone)]
pub struct LlmMessage {
    pub role: LlmMessageRole,
    pub content: LlmMessageContent,
    pub tool_calls: Option<Vec<ToolCall>>,
    pub tool_call_id: Option<String>,
    /// Execution phase for assistant messages.
    /// Helps models distinguish between intermediate working commentary (`Commentary`)
    /// and completed answers (`FinalAnswer`) in multi-step tool-calling flows.
    /// Only set on assistant messages. Must be preserved when replaying conversation history.
    pub phase: Option<crate::message::ExecutionPhase>,
    /// Thinking content from extended thinking models (Anthropic Claude)
    /// Must be included in subsequent API calls when thinking is enabled
    pub thinking: Option<String>,
    /// Cryptographic signature for thinking content (Anthropic Claude)
    /// Required when sending thinking back in subsequent API calls
    pub thinking_signature: Option<String>,
}

impl LlmMessage {
    /// Create a message with text content
    pub fn text(role: LlmMessageRole, content: impl Into<String>) -> Self {
        Self {
            role,
            content: LlmMessageContent::Text(content.into()),
            tool_calls: None,
            tool_call_id: None,
            phase: None,
            thinking: None,
            thinking_signature: None,
        }
    }

    /// Create a message with content parts (text, images, audio)
    pub fn parts(role: LlmMessageRole, parts: Vec<LlmContentPart>) -> Self {
        Self {
            role,
            content: LlmMessageContent::Parts(parts),
            tool_calls: None,
            tool_call_id: None,
            phase: None,
            thinking: None,
            thinking_signature: None,
        }
    }

    /// Get content as plain text string (for simple cases)
    pub fn content_as_text(&self) -> String {
        self.content.to_text()
    }

    /// Prepend a prefix to the first text content.
    ///
    /// Used by ReasonAtom to inject external actor identity (e.g. `"[Alice] "`)
    /// into user messages from external channels.
    pub fn prepend_text_prefix(&mut self, prefix: &str) {
        match &mut self.content {
            LlmMessageContent::Text(text) => {
                *text = format!("{}{}", prefix, text);
            }
            LlmMessageContent::Parts(parts) => {
                for part in parts.iter_mut() {
                    if let LlmContentPart::Text { text } = part {
                        *text = format!("{}{}", prefix, text);
                        return;
                    }
                }
                // No text part found — prepend one
                parts.insert(
                    0,
                    LlmContentPart::Text {
                        text: prefix.to_string(),
                    },
                );
            }
        }
    }
}

/// Fold every `System`-role message into a single string, joined in order with
/// blank lines.
///
/// Multiple system messages legitimately occur in one request: the agent system
/// prompt plus, e.g., `infinity_context`'s hidden-history notice or
/// `compaction`'s `[CONVERSATION_SUMMARY]`. Drivers that map the system role into
/// a dedicated top-level field (Anthropic `system`, Gemini `system_instruction`,
/// OpenResponses `instructions`) must accumulate rather than overwrite — otherwise
/// the real agent system prompt is silently dropped and only the last notice
/// survives. Returns `None` when there are no system messages.
pub fn fold_system_messages(messages: &[LlmMessage]) -> Option<String> {
    let mut system: Option<String> = None;
    for msg in messages {
        if msg.role == LlmMessageRole::System {
            let text = msg.content.to_text();
            system = Some(match system.take() {
                Some(existing) if !existing.is_empty() => format!("{existing}\n\n{text}"),
                _ => text,
            });
        }
    }
    system
}

/// Message content - either a simple string or array of content parts
#[derive(Debug, Clone)]
pub enum LlmMessageContent {
    /// Simple text content
    Text(String),
    /// Array of content parts (text, images, audio)
    Parts(Vec<LlmContentPart>),
}

impl LlmMessageContent {
    /// Convert to plain text (concatenates text parts, ignores media)
    pub fn to_text(&self) -> String {
        match self {
            LlmMessageContent::Text(s) => s.clone(),
            LlmMessageContent::Parts(parts) => parts
                .iter()
                .filter_map(|p| match p {
                    LlmContentPart::Text { text } => Some(text.clone()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join(""),
        }
    }

    /// Check if content is simple text
    pub fn is_text(&self) -> bool {
        matches!(self, LlmMessageContent::Text(_))
    }

    /// Check if content has multiple parts
    pub fn is_parts(&self) -> bool {
        matches!(self, LlmMessageContent::Parts(_))
    }
}

impl From<String> for LlmMessageContent {
    fn from(s: String) -> Self {
        LlmMessageContent::Text(s)
    }
}

impl From<&str> for LlmMessageContent {
    fn from(s: &str) -> Self {
        LlmMessageContent::Text(s.to_string())
    }
}

/// A single content part within a message
#[derive(Debug, Clone)]
pub enum LlmContentPart {
    /// Text content
    Text { text: String },
    /// Image content (base64 data URL or HTTP URL)
    Image { url: String },
    /// Audio content (base64 data URL)
    Audio { url: String },
}

impl LlmContentPart {
    /// Create a text content part
    pub fn text(text: impl Into<String>) -> Self {
        LlmContentPart::Text { text: text.into() }
    }

    /// Create an image content part from URL (can be data URL or HTTP URL)
    pub fn image(url: impl Into<String>) -> Self {
        LlmContentPart::Image { url: url.into() }
    }

    /// Create an audio content part from URL (typically a data URL)
    pub fn audio(url: impl Into<String>) -> Self {
        LlmContentPart::Audio { url: url.into() }
    }
}

/// Message role for LLM calls
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LlmMessageRole {
    System,
    User,
    Assistant,
    Tool,
}

// ============================================================================
// Configuration and Response Types
// ============================================================================

/// Configuration for tool_search (deferred tool loading).
///
/// When enabled, the driver groups tools into namespaces and marks them with
/// `defer_loading: true` so the model only loads full schemas on-demand.
/// This reduces token usage for agents with many tools.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ToolSearchConfig {
    /// Enable tool_search for this request (requires model support)
    pub enabled: bool,
    /// Minimum number of tools before activating tool_search.
    /// Below this threshold, full schemas are sent even when enabled.
    pub threshold: usize,
}

/// Strategy for prompt caching.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum PromptCacheStrategy {
    /// Let each driver choose the safest provider-specific behavior.
    #[default]
    Auto,
}

/// Configuration for prompt caching.
///
/// Drivers translate this into provider-specific request options when possible.
/// Unsupported providers or models should ignore it without failing the call.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct PromptCacheConfig {
    /// Enable prompt caching for this request.
    pub enabled: bool,
    /// Strategy the driver should use when enabling prompt caching.
    #[serde(default)]
    pub strategy: PromptCacheStrategy,
    /// Existing Gemini cached content resource name (`cachedContents/{id}`).
    ///
    /// When set, the Gemini driver uses explicit caching via the
    /// `cachedContent` request field. When absent, Gemini falls back to its
    /// default provider behavior (for example implicit caching on supported
    /// models).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gemini_cached_content: Option<String>,
}

/// High-level intent presets that compile into OpenRouter provider-routing
/// controls. Presets let callers express quality, cost, privacy, and capability
/// goals without knowing every OpenRouter `provider` flag.
///
/// Multiple presets may be combined. When a preset and an explicit `provider`
/// field target the same control, the explicit field wins. Presets applied
/// earlier in the list may be overridden by later ones for the same field.
///
/// Compilation happens in `OpenRouterRoutingConfig::apply_presets()`.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OpenRouterRoutingPreset {
    /// Prefer the cheapest providers that support function-calling parameters.
    CheapestWithTools,
    /// Prefer the highest-throughput providers for quick review or triage tasks.
    LowestLatencyReview,
    /// Route only to zero-data-retention (ZDR) endpoints.
    ZdrOnly,
    /// Try BYOK-registered providers first; fall back to shared capacity.
    ByokFirst,
    /// Deny all provider-side data collection (logs and training).
    NoDataCollection,
    /// Route only to providers that support strict JSON / structured output.
    StrictJson,
    /// Route only to providers that natively support reasoning/thinking models.
    ReasoningRequired,
    /// Cap per-token provider cost. Values are USD per million tokens; `None`
    /// means no cap on that dimension.
    MaxPrice {
        /// Maximum prompt cost in USD per million tokens.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prompt_usd_per_million: Option<f64>,
        /// Maximum completion cost in USD per million tokens.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        completion_usd_per_million: Option<f64>,
    },
}

/// OpenRouter model fallback and provider routing controls.
///
/// Organization-level strategy for how OpenRouter should allocate compute capacity.
///
/// Controls whether requests use OpenRouter shared credits, prefer customer-owned
/// upstream keys (BYOK), or require BYOK-only routing. Compiled into OpenRouter
/// `provider` routing controls before dispatch; not sent verbatim on the wire.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OpenRouterCapacityStrategy {
    /// Use OpenRouter shared capacity (credits). No routing changes. Default.
    #[default]
    SharedCapacity,
    /// Prefer providers where the org has registered its own upstream key.
    /// Falls back to shared capacity when BYOK providers are unavailable.
    /// Sets `provider.allow_fallbacks = true` unless the caller overrides it.
    ByokFirst,
    /// Require a provider where the org has its own upstream key.
    /// Routing fails if `provider.only` is not explicitly configured with at
    /// least one BYOK provider slug.
    /// Sets `provider.allow_fallbacks = false`.
    ByokOnly,
}

/// These fields mirror OpenRouter's request-level routing extensions. Drivers
/// must only forward this config to OpenRouter-compatible endpoints.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterRoutingConfig {
    /// Candidate models to try in OpenRouter's fallback order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub models: Vec<String>,
    /// OpenRouter route strategy. Currently `fallback` is the stable route
    /// value used with `models`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route: Option<OpenRouterRoute>,
    /// Provider ordering, policy, and sorting preferences.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<OpenRouterProviderRouting>,
    /// Optional plugin activations (web search, file reader).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugins: Option<OpenRouterPluginConfig>,
    /// Org-level capacity strategy. Compiled into `provider` routing before
    /// dispatch; not forwarded verbatim. `None` and `SharedCapacity` are
    /// equivalent (no routing changes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capacity_strategy: Option<OpenRouterCapacityStrategy>,
    /// High-level routing quality/policy presets. Compiled into `provider`
    /// flags by `apply_presets()` before the request is serialized.
    /// Explicit `provider` fields override preset-derived values.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub presets: Vec<OpenRouterRoutingPreset>,
}

impl OpenRouterRoutingConfig {
    pub fn is_empty(&self) -> bool {
        self.models.is_empty()
            && self.route.is_none()
            && self.provider.is_none()
            && self.plugins.as_ref().is_none_or(|p| p.is_empty())
            && matches!(
                self.capacity_strategy,
                None | Some(OpenRouterCapacityStrategy::SharedCapacity)
            )
            && self.presets.is_empty()
    }

    /// Build an ordered model-fallback routing config.
    pub fn fallback_models(models: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let models = models.into_iter().map(Into::into).collect::<Vec<_>>();
        let route = (!models.is_empty()).then_some(OpenRouterRoute::Fallback);
        Self {
            models,
            route,
            provider: None,
            plugins: None,
            capacity_strategy: None,
            presets: vec![],
        }
    }

    pub fn validate_for_primary_model(
        &self,
        primary_model: &str,
    ) -> std::result::Result<(), String> {
        if self.route == Some(OpenRouterRoute::Fallback) && self.models.is_empty() {
            return Err(
                "OpenRouter fallback routing requires at least one model in `models`".to_string(),
            );
        }

        if let Some(first_model) = self.models.first()
            && first_model != primary_model
        {
            return Err(format!(
                "OpenRouter routing models[0] ('{first_model}') must match primary model ('{primary_model}')"
            ));
        }

        Ok(())
    }

    /// Apply the capacity strategy, returning a derived config with `provider`
    /// routing adjusted accordingly.
    ///
    /// - `SharedCapacity` / `None` — returns `self` unchanged.
    /// - `ByokFirst` — sets `provider.allow_fallbacks = true` when not already set.
    /// - `ByokOnly` — requires `provider.only` to list at least one provider slug;
    ///   sets `provider.allow_fallbacks = false`.
    ///
    /// Returns `Err` when the strategy constraints cannot be satisfied.
    pub fn apply_capacity_strategy(&self) -> std::result::Result<Self, String> {
        match self.capacity_strategy {
            None | Some(OpenRouterCapacityStrategy::SharedCapacity) => Ok(self.clone()),
            Some(OpenRouterCapacityStrategy::ByokFirst) => {
                let mut result = self.clone();
                let provider = result.provider.get_or_insert_with(Default::default);
                if provider.allow_fallbacks.is_none() {
                    provider.allow_fallbacks = Some(true);
                }
                Ok(result)
            }
            Some(OpenRouterCapacityStrategy::ByokOnly) => {
                let only_is_empty = self.provider.as_ref().is_none_or(|p| p.only.is_empty());
                if only_is_empty {
                    return Err(
                        "OpenRouter BYOK-only strategy requires provider.only to list at least \
                         one upstream provider slug. Configure the provider list to match the \
                         BYOK providers registered in your OpenRouter workspace."
                            .to_string(),
                    );
                }
                let mut result = self.clone();
                let provider = result.provider.get_or_insert_with(Default::default);
                provider.allow_fallbacks = Some(false);
                Ok(result)
            }
        }
    }

    /// Compile `presets` into `OpenRouterProviderRouting` flags and merge with
    /// any explicit `provider` overrides. Returns a derived config with the
    /// `presets` list cleared and `provider` reflecting the merged result.
    ///
    /// Explicit `provider` fields always win over preset-derived values. When
    /// multiple presets target the same provider field, later presets in the
    /// list override earlier ones.
    ///
    /// Returns `Err` if any preset values are invalid (e.g. negative `MaxPrice` values).
    pub fn apply_presets(&self) -> std::result::Result<Self, String> {
        if self.presets.is_empty() {
            return Ok(self.clone());
        }

        let mut derived = OpenRouterProviderRouting::default();

        for preset in &self.presets {
            match preset {
                OpenRouterRoutingPreset::CheapestWithTools => {
                    derived.require_parameters = Some(true);
                    derived.sort = Some(OpenRouterProviderSort::Simple(
                        OpenRouterProviderSortBy::Price,
                    ));
                }
                OpenRouterRoutingPreset::LowestLatencyReview => {
                    derived.sort = Some(OpenRouterProviderSort::Simple(
                        OpenRouterProviderSortBy::Throughput,
                    ));
                }
                OpenRouterRoutingPreset::ZdrOnly => {
                    derived.zdr = Some(true);
                }
                OpenRouterRoutingPreset::ByokFirst => {
                    if derived.allow_fallbacks.is_none() {
                        derived.allow_fallbacks = Some(true);
                    }
                }
                OpenRouterRoutingPreset::NoDataCollection => {
                    derived.data_collection = Some(OpenRouterDataCollection::Deny);
                }
                OpenRouterRoutingPreset::StrictJson
                | OpenRouterRoutingPreset::ReasoningRequired => {
                    derived.require_parameters = Some(true);
                }
                OpenRouterRoutingPreset::MaxPrice {
                    prompt_usd_per_million,
                    completion_usd_per_million,
                } => {
                    if prompt_usd_per_million.is_some_and(|v| v < 0.0)
                        || completion_usd_per_million.is_some_and(|v| v < 0.0)
                    {
                        return Err(
                            "MaxPrice preset values must be non-negative USD per million tokens"
                                .to_string(),
                        );
                    }
                    if prompt_usd_per_million.is_some() || completion_usd_per_million.is_some() {
                        let mp = derived.max_price.get_or_insert_with(Default::default);
                        if let Some(p) = prompt_usd_per_million {
                            mp.prompt = Some(p / 1_000_000.0);
                        }
                        if let Some(c) = completion_usd_per_million {
                            mp.completion = Some(c / 1_000_000.0);
                        }
                    }
                }
            }
        }

        // Explicit provider fields override preset-derived values.
        let merged = merge_provider_routing(derived, self.provider.clone().unwrap_or_default());

        let mut result = self.clone();
        result.presets = vec![];
        result.provider = if merged.is_empty() {
            None
        } else {
            Some(merged)
        };
        Ok(result)
    }
}

/// Merge preset-derived provider routing with explicit provider overrides.
/// Explicit fields always win; preset-derived fields fill gaps where explicit
/// fields are absent (None / empty Vec).
fn merge_provider_routing(
    derived: OpenRouterProviderRouting,
    explicit: OpenRouterProviderRouting,
) -> OpenRouterProviderRouting {
    OpenRouterProviderRouting {
        order: if !explicit.order.is_empty() {
            explicit.order
        } else {
            derived.order
        },
        only: if !explicit.only.is_empty() {
            explicit.only
        } else {
            derived.only
        },
        ignore: if !explicit.ignore.is_empty() {
            explicit.ignore
        } else {
            derived.ignore
        },
        allow_fallbacks: explicit.allow_fallbacks.or(derived.allow_fallbacks),
        require_parameters: explicit.require_parameters.or(derived.require_parameters),
        data_collection: explicit.data_collection.or(derived.data_collection),
        zdr: explicit.zdr.or(derived.zdr),
        enforce_distillable_text: explicit
            .enforce_distillable_text
            .or(derived.enforce_distillable_text),
        quantizations: if !explicit.quantizations.is_empty() {
            explicit.quantizations
        } else {
            derived.quantizations
        },
        sort: explicit.sort.or(derived.sort),
        max_price: explicit.max_price.or(derived.max_price),
    }
}

/// OpenRouter route strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OpenRouterRoute {
    Fallback,
}

/// OpenRouter provider routing preferences.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterProviderRouting {
    /// Provider slugs to try first, in order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub order: Vec<String>,
    /// Restrict routing to these provider slugs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub only: Vec<String>,
    /// Provider slugs to skip.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ignore: Vec<String>,
    /// Whether OpenRouter may fall back outside the ordered/allowed providers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_fallbacks: Option<bool>,
    /// Require routed providers to support all request parameters.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub require_parameters: Option<bool>,
    /// Restrict routing by provider data-retention policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data_collection: Option<OpenRouterDataCollection>,
    /// Restrict routing to zero-data-retention endpoints.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub zdr: Option<bool>,
    /// Restrict routing to distillable-text endpoints.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enforce_distillable_text: Option<bool>,
    /// Restrict routing to provider quantization levels.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub quantizations: Vec<String>,
    /// Sort provider endpoints by price, throughput, or latency.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sort: Option<OpenRouterProviderSort>,
    /// Maximum accepted per-unit provider price.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_price: Option<OpenRouterMaxPrice>,
}

impl OpenRouterProviderRouting {
    pub fn is_empty(&self) -> bool {
        self.order.is_empty()
            && self.only.is_empty()
            && self.ignore.is_empty()
            && self.allow_fallbacks.is_none()
            && self.require_parameters.is_none()
            && self.data_collection.is_none()
            && self.zdr.is_none()
            && self.enforce_distillable_text.is_none()
            && self.quantizations.is_empty()
            && self.sort.is_none()
            && self.max_price.is_none()
    }
}

/// OpenRouter provider data-retention preference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OpenRouterDataCollection {
    Allow,
    Deny,
}

/// OpenRouter provider sort preference.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(untagged)]
pub enum OpenRouterProviderSort {
    Simple(OpenRouterProviderSortBy),
    Advanced(OpenRouterProviderSortOptions),
}

/// OpenRouter provider sorting dimension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OpenRouterProviderSortBy {
    Price,
    Throughput,
    Latency,
}

/// OpenRouter advanced provider sort options.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterProviderSortOptions {
    pub by: OpenRouterProviderSortBy,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub partition: Option<OpenRouterSortPartition>,
}

/// How OpenRouter sorts endpoints when multiple fallback models are present.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OpenRouterSortPartition {
    Model,
    None,
}

/// Maximum accepted OpenRouter provider pricing, expressed in dollars per
/// million prompt/completion tokens or per request/image where supported.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterMaxPrice {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completion: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image: Option<f64>,
}

/// OpenRouter web-search plugin configuration.
///
/// Instructs OpenRouter to retrieve and inject web search results before the
/// model sees the prompt. Only sent when the resolved provider type is
/// OpenRouter.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterWebSearchPlugin {
    /// Maximum number of search results to include.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_results: Option<u32>,
    /// Custom search prompt hint passed to the web-search step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub search_prompt: Option<String>,
}

/// OpenRouter file-reader plugin configuration.
///
/// Instructs OpenRouter to read and attach file contents before the model
/// sees the prompt. Only sent when the resolved provider type is OpenRouter.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterFilePlugin {}

/// OpenRouter plugin configuration bundling optional plugin activations.
///
/// Any `None` plugin is omitted from the wire request. When all plugins are
/// `None`, no `plugins` field is emitted.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OpenRouterPluginConfig {
    /// Web-search plugin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub web: Option<OpenRouterWebSearchPlugin>,
    /// File-reader plugin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<OpenRouterFilePlugin>,
}

impl OpenRouterPluginConfig {
    pub fn is_empty(&self) -> bool {
        self.web.is_none() && self.file.is_none()
    }
}

/// Metadata key consumed by the OpenRouter driver as `HTTP-Referer`.
pub const OPENROUTER_HTTP_REFERER_METADATA_KEY: &str = "openrouter.http_referer";
/// Metadata key consumed by the OpenRouter driver as `X-Title`.
pub const OPENROUTER_X_TITLE_METADATA_KEY: &str = "openrouter.x_title";

/// Configuration for an LLM call
#[derive(Debug, Clone)]
pub struct LlmCallConfig {
    pub model: String,
    pub temperature: Option<f32>,
    pub max_tokens: Option<u32>,
    pub tools: Vec<ToolDefinition>,
    /// Reasoning effort level (for models that support it: low, medium, high)
    pub reasoning_effort: Option<String>,
    /// Metadata to send with the API request for tracking and debugging.
    /// Keys and values are strings. Both OpenAI and Anthropic support metadata fields.
    /// Typically includes: session_id, agent_id, org_id, turn_id, exec_id.
    pub metadata: HashMap<String, String>,
    /// Previous response ID for stateful continuation (OpenAI Responses API).
    /// When set, the provider can skip re-encoding cached context.
    pub previous_response_id: Option<String>,
    /// Tool search configuration for deferred tool loading
    pub tool_search: Option<ToolSearchConfig>,
    /// Prompt caching configuration for provider-specific cache controls.
    pub prompt_cache: Option<PromptCacheConfig>,
    /// OpenRouter-only model fallback and provider routing controls.
    pub openrouter_routing: Option<OpenRouterRoutingConfig>,
}

impl From<&RuntimeAgent> for LlmCallConfig {
    fn from(runtime_agent: &RuntimeAgent) -> Self {
        Self {
            model: runtime_agent.model.clone(),
            temperature: runtime_agent.temperature,
            max_tokens: runtime_agent.max_tokens,
            tools: runtime_agent.tools.clone(),
            reasoning_effort: None, // Set by ReasonAtom from user message controls
            metadata: HashMap::new(), // Set by ReasonAtom with session/agent context
            previous_response_id: None,
            tool_search: runtime_agent.tool_search.clone(),
            prompt_cache: runtime_agent.prompt_cache.clone(),
            openrouter_routing: None,
        }
    }
}

/// Response from an LLM call (non-streaming)
#[derive(Debug, Clone)]
pub struct LlmResponse {
    pub text: String,
    /// Thinking content from extended thinking models (e.g., Claude with thinking enabled)
    pub thinking: Option<String>,
    /// Cryptographic signature for thinking content (Anthropic Claude)
    pub thinking_signature: Option<String>,
    pub tool_calls: Option<Vec<ToolCall>>,
    pub metadata: LlmCompletionMetadata,
}

/// Builder for LlmCallConfig with fluent API
///
/// Use `from(&runtime_agent)` to start building from a RuntimeAgent, then chain
/// methods like `reasoning_effort()`, `temperature()`, etc. Call `build()`
/// to get the final config.
///
/// # Example
///
/// ```ignore
/// use everruns_core::llm::LlmCallConfigBuilder;
/// use everruns_core::runtime_agent::RuntimeAgent;
///
/// let runtime_agent = RuntimeAgent::new("You are helpful", "gpt-4o");
/// let llm_config = LlmCallConfigBuilder::from(&runtime_agent)
///     .reasoning_effort("high")
///     .temperature(0.7)
///     .build();
/// ```
pub struct LlmCallConfigBuilder {
    config: LlmCallConfig,
}

impl LlmCallConfigBuilder {
    /// Start building from a RuntimeAgent
    pub fn from(runtime_agent: &RuntimeAgent) -> Self {
        Self {
            config: LlmCallConfig::from(runtime_agent),
        }
    }

    /// Set reasoning effort level (for models that support it: low, medium, high)
    pub fn reasoning_effort(mut self, effort: impl Into<String>) -> Self {
        self.config.reasoning_effort = Some(effort.into());
        self
    }

    /// Set the model
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.config.model = model.into();
        self
    }

    /// Set temperature
    pub fn temperature(mut self, temp: f32) -> Self {
        self.config.temperature = Some(temp);
        self
    }

    /// Set max tokens
    pub fn max_tokens(mut self, tokens: u32) -> Self {
        self.config.max_tokens = Some(tokens);
        self
    }

    /// Set tools
    pub fn tools(mut self, tools: Vec<ToolDefinition>) -> Self {
        self.config.tools = tools;
        self
    }

    /// Set metadata for API tracking
    ///
    /// This metadata is sent to the LLM provider for tracking and debugging.
    /// Typically includes session_id, agent_id, org_id, turn_id, exec_id.
    pub fn metadata(mut self, metadata: HashMap<String, String>) -> Self {
        self.config.metadata = metadata;
        self
    }

    /// Add a single metadata key-value pair
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config.metadata.insert(key.into(), value.into());
        self
    }

    /// Set previous response ID for stateful continuation
    pub fn previous_response_id(mut self, id: Option<String>) -> Self {
        self.config.previous_response_id = id;
        self
    }

    /// Set tool_search configuration
    pub fn tool_search(mut self, config: ToolSearchConfig) -> Self {
        self.config.tool_search = Some(config);
        self
    }

    /// Set prompt caching configuration
    pub fn prompt_cache(mut self, config: PromptCacheConfig) -> Self {
        self.config.prompt_cache = Some(config);
        self
    }

    /// Set OpenRouter model fallback and provider routing controls.
    pub fn openrouter_routing(mut self, config: OpenRouterRoutingConfig) -> Self {
        self.config.openrouter_routing = (!config.is_empty()).then_some(config);
        self
    }

    /// Build the configuration
    pub fn build(self) -> LlmCallConfig {
        self.config
    }
}

// ============================================================================
// Conversion from Message
// ============================================================================

impl From<&crate::message::Message> for LlmMessage {
    /// Convert a Message to LlmMessage (text-only, images become placeholders)
    ///
    /// This conversion is suitable for messages without images or when image
    /// resolution is not available. For multimodal messages, use
    /// `LlmMessage::from_message_with_images()` instead.
    fn from(msg: &crate::message::Message) -> Self {
        let role = match msg.role {
            crate::message::MessageRole::System => LlmMessageRole::System,
            crate::message::MessageRole::User => LlmMessageRole::User,
            crate::message::MessageRole::Agent => LlmMessageRole::Assistant,
            crate::message::MessageRole::ToolResult => LlmMessageRole::Tool,
        };

        // Convert tool calls from ContentPart format to ToolCall format
        let tool_calls: Vec<ToolCall> = msg
            .tool_calls()
            .into_iter()
            .map(|tc| ToolCall {
                id: tc.id.clone(),
                name: tc.name.clone(),
                arguments: tc.arguments.clone(),
            })
            .collect();

        LlmMessage {
            role,
            content: LlmMessageContent::Text(msg.content_to_llm_string()),
            tool_calls: if tool_calls.is_empty() {
                None
            } else {
                Some(tool_calls)
            },
            tool_call_id: msg.tool_call_id().map(|s| s.to_string()),
            phase: msg.phase,
            thinking: msg.thinking.clone(),
            thinking_signature: msg.thinking_signature.clone(),
        }
    }
}

// ============================================================================
// Message Conversion with Images
// ============================================================================

use crate::traits::ResolvedImage;
use uuid::Uuid;

impl LlmMessage {
    /// Convert a Message to LlmMessage with resolved images
    ///
    /// This method handles multimodal messages by converting:
    /// - `text` content parts → `LlmContentPart::Text`
    /// - `image` content parts → `LlmContentPart::Image` (data URL)
    /// - `image_file` content parts → `LlmContentPart::Image` (resolved to data URL)
    /// - `tool_call` content parts → extracted to `tool_calls` field
    /// - `tool_result` content parts → text representation
    ///
    /// # Provider-specific formatting
    ///
    /// The `LlmContentPart::Image` uses data URLs which are converted by each provider:
    /// - **OpenAI**: `{ "type": "image_url", "image_url": { "url": "data:..." } }`
    /// - **Anthropic**: `{ "type": "image", "source": { "type": "base64", ... } }`
    ///
    /// # Arguments
    ///
    /// * `msg` - The message to convert
    /// * `resolved_images` - Pre-resolved images keyed by image_id
    pub fn from_message_with_images(
        msg: &crate::message::Message,
        resolved_images: &HashMap<Uuid, ResolvedImage>,
    ) -> Self {
        use crate::message::{ContentPart, MessageRole};

        let role = match msg.role {
            MessageRole::System => LlmMessageRole::System,
            MessageRole::User => LlmMessageRole::User,
            MessageRole::Agent => LlmMessageRole::Assistant,
            MessageRole::ToolResult => LlmMessageRole::Tool,
        };

        // Convert content parts to LlmContentParts
        let mut parts: Vec<LlmContentPart> = Vec::new();
        let mut tool_calls: Vec<ToolCall> = Vec::new();

        for part in &msg.content {
            match part {
                ContentPart::Text(t) => {
                    parts.push(LlmContentPart::Text {
                        text: t.text.clone(),
                    });
                }
                ContentPart::Image(img) => {
                    // Convert inline image to data URL
                    if let Some(url) = &img.url {
                        parts.push(LlmContentPart::Image { url: url.clone() });
                    } else if let (Some(base64), Some(media_type)) = (&img.base64, &img.media_type)
                    {
                        let data_url = format!("data:{};base64,{}", media_type, base64);
                        parts.push(LlmContentPart::Image { url: data_url });
                    }
                }
                ContentPart::ImageFile(img_file) => {
                    // Resolve image_file to actual image data
                    if let Some(resolved) = resolved_images.get(&img_file.image_id.uuid()) {
                        parts.push(LlmContentPart::Image {
                            url: resolved.to_data_url(),
                        });
                    } else {
                        // Image not found - add placeholder text
                        parts.push(LlmContentPart::Text {
                            text: format!("[Image not found: {}]", img_file.image_id),
                        });
                    }
                }
                ContentPart::ToolCall(tc) => {
                    // Extract tool calls to separate field (don't include in content)
                    tool_calls.push(ToolCall {
                        id: tc.id.clone(),
                        name: tc.name.clone(),
                        arguments: tc.arguments.clone(),
                    });
                }
                ContentPart::ToolResult(tr) => {
                    // Convert tool result to text representation
                    let text = if let Some(err) = &tr.error {
                        format!("Tool error: {}", err)
                    } else if let Some(res) = &tr.result {
                        serde_json::to_string(res).unwrap_or_else(|_| "{}".to_string())
                    } else {
                        "{}".to_string()
                    };
                    // Primary hard limit enforced by OutputHardLimitHook (EVE-225)
                    // at tool execution time. This backstop catches tool results
                    // that bypass ActAtom hooks (client-submitted, stored events).
                    let text = truncate_tool_result(text);
                    parts.push(LlmContentPart::Text { text });
                }
            }
        }

        // Determine content format
        let content = if parts.len() == 1 && matches!(&parts[0], LlmContentPart::Text { .. }) {
            // Single text part - use simple Text format
            if let LlmContentPart::Text { text } = &parts[0] {
                LlmMessageContent::Text(text.clone())
            } else {
                LlmMessageContent::Parts(parts)
            }
        } else if parts.is_empty() {
            // No content parts - use empty text
            LlmMessageContent::Text(String::new())
        } else {
            // Multiple parts or non-text - use Parts format
            LlmMessageContent::Parts(parts)
        };

        LlmMessage {
            role,
            content,
            tool_calls: if tool_calls.is_empty() {
                None
            } else {
                Some(tool_calls)
            },
            tool_call_id: msg.tool_call_id().map(|s| s.to_string()),
            phase: msg.phase,
            thinking: msg.thinking.clone(),
            thinking_signature: msg.thinking_signature.clone(),
        }
    }

    /// Check if a message contains image_file references that need resolution
    pub fn message_has_image_files(msg: &crate::message::Message) -> bool {
        msg.content.iter().any(|p| p.is_image_file())
    }

    /// Extract all image_file IDs from a message
    pub fn extract_image_file_ids(msg: &crate::message::Message) -> Vec<Uuid> {
        msg.content
            .iter()
            .filter_map(|p| match p {
                crate::message::ContentPart::ImageFile(f) => Some(f.image_id.uuid()),
                _ => None,
            })
            .collect()
    }
}

// ============================================================================
// Driver Factory Types
// ============================================================================

pub use crate::provider::DriverId;

/// Extra provider-specific authentication/metadata beyond an API key.
///
/// Built-in providers ignore this; embedder-defined ([`DriverId::External`])
/// providers use it to carry OAuth tokens, account ids, or arbitrary extras
/// their driver factory needs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProviderMetadata {
    /// OAuth refresh token, when the provider authenticates via OAuth.
    pub refresh_token: Option<String>,
    /// Provider-side account identifier, when required.
    pub account_id: Option<String>,
    /// Arbitrary extra fields the driver factory understands.
    pub extra: Option<serde_json::Value>,
}

/// Configuration for creating an LLM provider
#[derive(Debug, Clone)]
pub struct ProviderConfig {
    /// Type of provider
    pub provider_type: DriverId,
    /// API key for authentication
    pub api_key: Option<String>,
    /// Base URL override (optional)
    pub base_url: Option<String>,
    /// Extra provider-specific metadata (OAuth tokens, account ids, etc.).
    pub metadata: ProviderMetadata,
}

impl ProviderConfig {
    /// Create a new provider config
    pub fn new(provider_type: DriverId) -> Self {
        Self {
            provider_type,
            api_key: None,
            base_url: None,
            metadata: ProviderMetadata::default(),
        }
    }

    /// Set the API key
    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Set the base URL
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Set provider-specific metadata.
    pub fn with_metadata(mut self, metadata: ProviderMetadata) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Everything a [`DriverFactory`] receives to build a driver instance.
///
/// Replaces the old `(api_key, base_url)` factory arguments so that
/// embedder-defined providers can receive richer auth via [`ProviderMetadata`]
/// without changing the factory signature again.
#[derive(Debug, Clone)]
pub struct DriverConfig {
    /// Provider type being created.
    pub provider_type: DriverId,
    /// API key, when one is configured. `None` for keyless providers (LlmSim,
    /// or external providers that authenticate via [`ProviderMetadata`]).
    pub api_key: Option<String>,
    /// Base URL override, when configured.
    pub base_url: Option<String>,
    /// Extra provider-specific metadata.
    pub metadata: ProviderMetadata,
}

impl From<&crate::traits::ResolvedModel> for ProviderConfig {
    fn from(model: &crate::traits::ResolvedModel) -> Self {
        Self {
            provider_type: model.provider_type.clone(),
            api_key: model.api_key.clone(),
            base_url: model.base_url.clone(),
            metadata: model.provider_metadata.clone().unwrap_or_default(),
        }
    }
}

/// Boxed chat driver for dynamic dispatch
pub type BoxedChatDriver = Box<dyn ChatDriver>;

// ============================================================================
// EmbeddingsDriver Trait
// ============================================================================

/// Request to embed a batch of text strings into dense vectors.
#[derive(Debug, Clone)]
pub struct EmbedRequest {
    /// Texts to embed. All texts in a batch share the same model.
    pub texts: Vec<String>,
    /// Provider-side model id (e.g. `text-embedding-3-small`).
    pub model: String,
}

/// Response from an embedding request.
#[derive(Debug, Clone)]
pub struct EmbedResponse {
    /// One float vector per input text, in the same order.
    pub embeddings: Vec<Vec<f32>>,
    /// Total tokens consumed (for usage tracking). `None` if the provider
    /// does not report token counts.
    pub usage_tokens: Option<u32>,
}

/// Error returned by [`EmbeddingsDriver::embed`].
#[derive(Debug, thiserror::Error)]
pub enum EmbeddingsDriverError {
    #[error("embeddings provider returned an error: {0}")]
    Provider(String),
    #[error("embeddings request failed: {0}")]
    Transport(String),
}

/// Driver trait for text embedding services.
///
/// Implementors call their provider's embedding API and return dense float
/// vectors. Used by knowledge-base hybrid retrieval (see specs/knowledge-bases.md
/// and specs/providers.md phase 6).
#[async_trait]
pub trait EmbeddingsDriver: Send + Sync {
    /// Embed a batch of texts and return one vector per input.
    async fn embed(
        &self,
        request: EmbedRequest,
    ) -> std::result::Result<EmbedResponse, EmbeddingsDriverError>;
}

/// Boxed embeddings driver for dynamic dispatch.
pub type BoxedEmbeddingsDriver = Box<dyn EmbeddingsDriver>;

/// Factory function type for creating embeddings drivers.
pub type EmbeddingsDriverFactory =
    Arc<dyn Fn(&DriverConfig) -> BoxedEmbeddingsDriver + Send + Sync>;

// ============================================================================
// Driver Registry
// ============================================================================

/// Factory function type for creating chat drivers.
///
/// Receives a [`DriverConfig`] (provider type, optional key/base URL, and
/// provider metadata) and returns a boxed driver.
pub type DriverFactory = Arc<dyn Fn(&DriverConfig) -> BoxedChatDriver + Send + Sync>;

/// A typed service a provider driver can offer (see specs/providers.md).
///
/// Declared in code by each driver, never stored in the database. Only `Chat`
/// has a driver trait today; the set is additive and new kinds gain factories
/// on [`DriverDescriptor`] when their first consumer lands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServiceKind {
    /// Chat completion ([`ChatDriver`]).
    Chat,
    /// Text embeddings (planned: knowledge-base hybrid retrieval).
    Embeddings,
    /// Realtime voice sessions (server-side adapter using provider credentials).
    Realtime,
    /// Image generation.
    Images,
    /// Search-result reranking.
    Rerank,
}

impl std::fmt::Display for ServiceKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            ServiceKind::Chat => "chat",
            ServiceKind::Embeddings => "embeddings",
            ServiceKind::Realtime => "realtime",
            ServiceKind::Images => "images",
            ServiceKind::Rerank => "rerank",
        };
        f.write_str(s)
    }
}

/// A registered provider driver: identity, declared services, the credential
/// shape its providers must supply, and per-service factories.
///
/// The descriptor is the code-side unit of the providers domain model
/// (specs/providers.md): one descriptor per driver id, instantiated as many
/// org-scoped providers.
#[derive(Clone)]
pub struct DriverDescriptor {
    /// Driver id (also the registry key).
    pub id: DriverId,
    /// Human-readable driver name (e.g. "OpenAI", "AWS Bedrock").
    pub display_name: String,
    /// Services this driver's providers can power. Declared, not stored.
    pub services: Vec<ServiceKind>,
    /// Credential fields a provider instance must supply.
    pub credential_schema: CredentialFormSchema,
    /// Chat service factory. `None` for drivers that only offer other services.
    pub chat: Option<DriverFactory>,
    /// Embeddings service factory. `None` for drivers that do not support embeddings.
    pub embeddings: Option<EmbeddingsDriverFactory>,
}

impl DriverDescriptor {
    /// Descriptor for a chat-only driver with the default credential schema
    /// for the driver id (a single required `api_key` field for real
    /// providers; empty for `LlmSim` and `External`, which may authenticate
    /// via [`ProviderMetadata`]) and a display name derived from the id.
    pub fn chat_only<F>(id: impl Into<DriverId>, factory: F) -> Self
    where
        F: Fn(&DriverConfig) -> BoxedChatDriver + Send + Sync + 'static,
    {
        let id = id.into();
        Self {
            display_name: default_display_name(&id),
            credential_schema: default_credential_schema(&id),
            services: vec![ServiceKind::Chat],
            chat: Some(Arc::new(factory)),
            embeddings: None,
            id,
        }
    }

    /// Whether the driver declares the given service.
    pub fn supports(&self, service: ServiceKind) -> bool {
        self.services.contains(&service)
    }
}

impl std::fmt::Debug for DriverDescriptor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DriverDescriptor")
            .field("id", &self.id)
            .field("display_name", &self.display_name)
            .field("services", &self.services)
            .field("chat", &self.chat.is_some())
            .field("embeddings", &self.embeddings.is_some())
            .finish()
    }
}

fn default_display_name(id: &DriverId) -> String {
    match id {
        DriverId::OpenAI => "OpenAI".to_string(),
        DriverId::OpenRouter => "OpenRouter".to_string(),
        DriverId::AzureOpenAI => "Azure OpenAI".to_string(),
        DriverId::OpenAICompletions => "OpenAI (Chat Completions)".to_string(),
        DriverId::Anthropic => "Anthropic".to_string(),
        DriverId::Gemini => "Google Gemini".to_string(),
        DriverId::Bedrock => "AWS Bedrock".to_string(),
        DriverId::Mai => "Microsoft MAI".to_string(),
        DriverId::LlmSim => "LLM Simulator".to_string(),
        DriverId::External(id) => id.to_string(),
    }
}

fn default_credential_schema(id: &DriverId) -> CredentialFormSchema {
    match id {
        // Keyless: simulator always; external drivers may auth via metadata.
        DriverId::LlmSim | DriverId::External(_) => CredentialFormSchema::empty(),
        _ => CredentialFormSchema::api_key(String::new()),
    }
}

/// Registry for LLM drivers
///
/// Enables dependency inversion: provider crates (everruns-anthropic, everruns-openai)
/// register their drivers at startup. The core has no direct knowledge of implementations.
///
/// # Example
///
/// ```ignore
/// use everruns_core::{DriverRegistry, DriverId};
/// use everruns_anthropic::register_driver;
/// use everruns_openai::register_driver as register_openai;
///
/// let mut registry = DriverRegistry::new();
/// everruns_anthropic::register_driver(&mut registry);
/// everruns_openai::register_driver(&mut registry);
///
/// // Later, create a driver from config
/// let driver = registry.create_chat_driver(&config)?;
/// ```
#[derive(Clone, Default)]
pub struct DriverRegistry {
    descriptors: HashMap<DriverId, DriverDescriptor>,
}

impl DriverRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            descriptors: HashMap::new(),
        }
    }

    /// Register a full driver descriptor.
    ///
    /// Panics if a descriptor is already registered for the same driver id —
    /// silent overwrites hide double-registration bugs. Use
    /// [`Self::register_descriptor_or_replace`] to overwrite intentionally.
    pub fn register_descriptor(&mut self, descriptor: DriverDescriptor) {
        if self.descriptors.contains_key(&descriptor.id) {
            panic!(
                "driver already registered for provider '{}'; \
                 use register_descriptor_or_replace to overwrite intentionally",
                descriptor.id
            );
        }
        self.descriptors.insert(descriptor.id.clone(), descriptor);
    }

    /// Register a full driver descriptor, replacing any existing one.
    pub fn register_descriptor_or_replace(&mut self, descriptor: DriverDescriptor) {
        self.descriptors.insert(descriptor.id.clone(), descriptor);
    }

    /// Register a driver factory for a provider type.
    ///
    /// Panics if a factory is already registered for `provider_type` — silent
    /// overwrites hide double-registration bugs. Use
    /// [`Self::register_or_replace`] to overwrite intentionally.
    pub fn register<F>(&mut self, provider_type: impl Into<DriverId>, factory: F)
    where
        F: Fn(&DriverConfig) -> BoxedChatDriver + Send + Sync + 'static,
    {
        self.register_descriptor(DriverDescriptor::chat_only(provider_type, factory));
    }

    /// Register a driver factory, replacing any existing one for the provider.
    ///
    /// Use when overwriting is intentional (e.g. swapping in an `LlmSim` driver
    /// for tests). Prefer [`Self::register`] otherwise so duplicates surface.
    pub fn register_or_replace<F>(&mut self, provider_type: impl Into<DriverId>, factory: F)
    where
        F: Fn(&DriverConfig) -> BoxedChatDriver + Send + Sync + 'static,
    {
        self.register_descriptor_or_replace(DriverDescriptor::chat_only(provider_type, factory));
    }

    /// Register a driver factory for an embedder-defined external provider,
    /// keyed by its canonical id. The id is normalized to lowercase (via
    /// [`DriverId::external`]) so it matches parsed lookups regardless of
    /// the casing stored in the database or sent on the wire.
    pub fn register_external<F>(&mut self, id: impl Into<Arc<str>>, factory: F)
    where
        F: Fn(&DriverConfig) -> BoxedChatDriver + Send + Sync + 'static,
    {
        self.register(DriverId::external(id), factory);
    }

    /// Create an LLM driver based on configuration
    ///
    /// API keys must be provided in the config for real providers. This function does NOT fall back to
    /// environment variables. Keys should be decrypted from the database and passed here.
    /// Exception: `LlmSim` and `External` providers do not require an API key
    /// (external providers may authenticate via [`ProviderMetadata`]).
    ///
    /// Returns `DriverNotRegistered` error if no driver is registered for the provider type.
    pub fn create_chat_driver(&self, config: &ProviderConfig) -> Result<BoxedChatDriver> {
        // API key is required for real built-in providers, but not for LlmSim
        // (testing), External providers, or Mai (which may all authenticate via
        // metadata-based auth — Mai supports Entra ID OAuth without an api_key).
        let requires_api_key = !matches!(
            config.provider_type,
            DriverId::LlmSim | DriverId::External(_) | DriverId::Mai
        );
        if requires_api_key && config.api_key.is_none() {
            return Err(AgentLoopError::llm(
                "API key is required. Configure the API key in provider settings.",
            ));
        }

        // Look up the descriptor and its chat factory for this provider type
        let descriptor = self.descriptors.get(&config.provider_type).ok_or_else(|| {
            AgentLoopError::driver_not_registered(config.provider_type.to_string())
        })?;
        let factory = descriptor.chat.as_ref().ok_or_else(|| {
            AgentLoopError::llm(format!(
                "Provider driver '{}' does not implement the chat service.",
                config.provider_type
            ))
        })?;

        // Create the driver using the factory
        let driver_config = DriverConfig {
            provider_type: config.provider_type.clone(),
            api_key: config.api_key.clone(),
            base_url: config.base_url.clone(),
            metadata: config.metadata.clone(),
        };
        Ok(factory(&driver_config))
    }

    /// Check if a driver is registered for a provider type
    pub fn has_driver(&self, provider_type: &DriverId) -> bool {
        self.descriptors.contains_key(provider_type)
    }

    /// Get the registered descriptor for a provider type.
    pub fn descriptor(&self, provider_type: &DriverId) -> Option<&DriverDescriptor> {
        self.descriptors.get(provider_type)
    }

    /// Whether the registered driver declares the given service.
    pub fn supports(&self, provider_type: &DriverId, service: ServiceKind) -> bool {
        self.descriptors
            .get(provider_type)
            .is_some_and(|d| d.supports(service))
    }

    /// Driver ids whose descriptors declare the given service.
    pub fn providers_for(&self, service: ServiceKind) -> Vec<DriverId> {
        self.descriptors
            .values()
            .filter(|d| d.supports(service))
            .map(|d| d.id.clone())
            .collect()
    }

    /// Get the list of registered provider types
    pub fn registered_providers(&self) -> Vec<DriverId> {
        self.descriptors.keys().cloned().collect()
    }

    /// Create an embeddings driver based on configuration.
    ///
    /// API keys must be provided in the config for real providers. Exception:
    /// `LlmSim` and `External` providers do not require an API key.
    ///
    /// Returns an error if the driver is not registered or does not implement
    /// the embeddings service.
    pub fn create_embeddings_driver(
        &self,
        config: &ProviderConfig,
    ) -> std::result::Result<BoxedEmbeddingsDriver, EmbeddingsDriverError> {
        let requires_api_key = !matches!(
            config.provider_type,
            DriverId::LlmSim | DriverId::External(_)
        );
        if requires_api_key && config.api_key.is_none() {
            return Err(EmbeddingsDriverError::Provider(
                "API key is required. Configure the API key in provider settings.".to_string(),
            ));
        }
        let descriptor = self.descriptors.get(&config.provider_type).ok_or_else(|| {
            EmbeddingsDriverError::Provider(format!(
                "No driver registered for provider '{}'",
                config.provider_type
            ))
        })?;
        let factory = descriptor.embeddings.as_ref().ok_or_else(|| {
            EmbeddingsDriverError::Provider(format!(
                "Provider driver '{}' does not implement the embeddings service.",
                config.provider_type
            ))
        })?;
        let driver_config = DriverConfig {
            provider_type: config.provider_type.clone(),
            api_key: config.api_key.clone(),
            base_url: config.base_url.clone(),
            metadata: config.metadata.clone(),
        };
        Ok(factory(&driver_config))
    }
}

/// Maximum tool result size in bytes before truncation (64 KiB).
/// Defense-in-depth backstop for tool results that bypass ActAtom hooks
/// (e.g. client-submitted or stored events). The primary hard limit is
/// enforced by `OutputHardLimitHook` (EVE-225) at tool execution time.
const MAX_TOOL_RESULT_BYTES: usize = 64 * 1024;

const TRUNCATION_SUFFIX: &str =
    "\n\n[Output truncated — exceeded 64 KiB limit. Try quiet flags, pipes, or redirect to file.]";

fn truncate_tool_result(text: String) -> String {
    if text.len() <= MAX_TOOL_RESULT_BYTES {
        return text;
    }
    let content_budget = MAX_TOOL_RESULT_BYTES.saturating_sub(TRUNCATION_SUFFIX.len());
    let mut end = content_budget;
    while end > 0 && !text.is_char_boundary(end) {
        end -= 1;
    }
    let mut truncated = text[..end].to_string();
    truncated.push_str(TRUNCATION_SUFFIX);
    truncated
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_fold_system_messages_none_when_absent() {
        let messages = vec![
            LlmMessage::text(LlmMessageRole::User, "hi"),
            LlmMessage::text(LlmMessageRole::Assistant, "ok"),
        ];
        assert_eq!(fold_system_messages(&messages), None);
    }

    #[test]
    fn test_fold_system_messages_single() {
        let messages = vec![
            LlmMessage::text(LlmMessageRole::System, "AGENT-PROMPT"),
            LlmMessage::text(LlmMessageRole::User, "hi"),
        ];
        assert_eq!(
            fold_system_messages(&messages),
            Some("AGENT-PROMPT".to_string())
        );
    }

    #[test]
    fn test_fold_system_messages_accumulates_in_order() {
        // The agent system prompt plus a later notice/summary System message
        // (infinity_context / compaction) must both survive, in order — the
        // later one must not overwrite the real agent system prompt.
        let messages = vec![
            LlmMessage::text(LlmMessageRole::System, "A"),
            LlmMessage::text(LlmMessageRole::User, "hi"),
            LlmMessage::text(LlmMessageRole::Assistant, "ok"),
            LlmMessage::text(LlmMessageRole::System, "B"),
        ];
        assert_eq!(fold_system_messages(&messages), Some("A\n\nB".to_string()));
    }

    #[test]
    fn test_fold_system_messages_concatenates_parts() {
        let messages = vec![LlmMessage::parts(
            LlmMessageRole::System,
            vec![
                LlmContentPart::text("foo"),
                LlmContentPart::image("data:image/png;base64,xxx"),
                LlmContentPart::text("bar"),
            ],
        )];
        assert_eq!(fold_system_messages(&messages), Some("foobar".to_string()));
    }

    #[test]
    fn test_llm_call_config_builder_from_runtime_agent() {
        let runtime_agent = RuntimeAgent::new("You are helpful", "gpt-4o");
        let llm_config = LlmCallConfigBuilder::from(&runtime_agent).build();

        assert_eq!(llm_config.model, "gpt-4o");
        assert!(llm_config.reasoning_effort.is_none());
        assert!(llm_config.temperature.is_none());
        assert!(llm_config.max_tokens.is_none());
        assert!(llm_config.tools.is_empty());
        assert!(llm_config.metadata.is_empty());
    }

    #[test]
    fn test_llm_call_config_builder_with_metadata() {
        let runtime_agent = RuntimeAgent::new("You are helpful", "gpt-4o");
        let llm_config = LlmCallConfigBuilder::from(&runtime_agent)
            .with_metadata("session_id", "session_abc123")
            .with_metadata("agent_id", "agent_xyz789")
            .build();

        assert_eq!(
            llm_config.metadata.get("session_id"),
            Some(&"session_abc123".to_string())
        );
        assert_eq!(
            llm_config.metadata.get("agent_id"),
            Some(&"agent_xyz789".to_string())
        );
    }

    #[test]
    fn test_llm_call_config_builder_with_metadata_hashmap() {
        let runtime_agent = RuntimeAgent::new("You are helpful", "gpt-4o");
        let mut metadata = HashMap::new();
        metadata.insert("key1".to_string(), "value1".to_string());
        metadata.insert("key2".to_string(), "value2".to_string());

        let llm_config = LlmCallConfigBuilder::from(&runtime_agent)
            .metadata(metadata)
            .build();

        assert_eq!(llm_config.metadata.get("key1"), Some(&"value1".to_string()));
        assert_eq!(llm_config.metadata.get("key2"), Some(&"value2".to_string()));
    }

    #[test]
    fn test_llm_call_config_builder_with_reasoning_effort() {
        let runtime_agent = RuntimeAgent::new("You are helpful", "gpt-4o");
        let llm_config = LlmCallConfigBuilder::from(&runtime_agent)
            .reasoning_effort("high")
            .build();

        assert_eq!(llm_config.reasoning_effort, Some("high".to_string()));
    }

    #[test]
    fn test_llm_call_config_builder_with_all_options() {
        let runtime_agent = RuntimeAgent::new("You are helpful", "gpt-4o");
        let llm_config = LlmCallConfigBuilder::from(&runtime_agent)
            .model("claude-3-opus")
            .reasoning_effort("medium")
            .temperature(0.7)
            .max_tokens(1000)
            .build();

        assert_eq!(llm_config.model, "claude-3-opus");
        assert_eq!(llm_config.reasoning_effort, Some("medium".to_string()));
        assert_eq!(llm_config.temperature, Some(0.7));
        assert_eq!(llm_config.max_tokens, Some(1000));
    }

    #[test]
    fn test_llm_call_config_builder_with_openrouter_routing() {
        let runtime_agent = RuntimeAgent::new("You are helpful", "openai/gpt-5-mini");
        let routing = OpenRouterRoutingConfig::fallback_models([
            "openai/gpt-5-mini",
            "anthropic/claude-sonnet-4.5",
        ]);

        let llm_config = LlmCallConfigBuilder::from(&runtime_agent)
            .openrouter_routing(routing.clone())
            .build();

        assert_eq!(llm_config.openrouter_routing, Some(routing));
    }

    #[test]
    fn test_openrouter_fallback_models_empty_is_empty() {
        let routing = OpenRouterRoutingConfig::fallback_models(std::iter::empty::<String>());

        assert!(routing.is_empty());
        assert_eq!(routing.route, None);
    }

    #[test]
    fn test_openrouter_routing_validates_primary_model() {
        let routing = OpenRouterRoutingConfig::fallback_models([
            "openai/gpt-5-mini",
            "anthropic/claude-sonnet-4.5",
        ]);

        assert!(
            routing
                .validate_for_primary_model("openai/gpt-5-mini")
                .is_ok()
        );
        let err = routing
            .validate_for_primary_model("anthropic/claude-sonnet-4.5")
            .unwrap_err();
        assert!(err.contains("models[0]"));
    }

    #[test]
    fn test_openrouter_routing_rejects_fallback_without_models() {
        let routing = OpenRouterRoutingConfig {
            route: Some(OpenRouterRoute::Fallback),
            ..Default::default()
        };

        let err = routing
            .validate_for_primary_model("openai/gpt-5-mini")
            .unwrap_err();
        assert!(err.contains("requires at least one model"));
    }

    #[test]
    fn test_openrouter_routing_serializes_request_fields() {
        let routing = OpenRouterRoutingConfig {
            models: vec![
                "openai/gpt-5-mini".to_string(),
                "anthropic/claude-sonnet-4.5".to_string(),
            ],
            route: Some(OpenRouterRoute::Fallback),
            provider: Some(OpenRouterProviderRouting {
                order: vec!["anthropic".to_string(), "openai".to_string()],
                allow_fallbacks: Some(false),
                require_parameters: Some(true),
                data_collection: Some(OpenRouterDataCollection::Deny),
                zdr: Some(true),
                sort: Some(OpenRouterProviderSort::Advanced(
                    OpenRouterProviderSortOptions {
                        by: OpenRouterProviderSortBy::Throughput,
                        partition: Some(OpenRouterSortPartition::None),
                    },
                )),
                max_price: Some(OpenRouterMaxPrice {
                    prompt: Some(1.0),
                    completion: Some(2.0),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };

        let json = serde_json::to_value(routing).unwrap();

        assert_eq!(
            json,
            serde_json::json!({
                "models": [
                    "openai/gpt-5-mini",
                    "anthropic/claude-sonnet-4.5"
                ],
                "route": "fallback",
                "provider": {
                    "order": ["anthropic", "openai"],
                    "allow_fallbacks": false,
                    "require_parameters": true,
                    "data_collection": "deny",
                    "zdr": true,
                    "sort": {
                        "by": "throughput",
                        "partition": "none"
                    },
                    "max_price": {
                        "prompt": 1.0,
                        "completion": 2.0
                    }
                }
            })
        );
    }

    #[test]
    fn test_provider_type_parsing() {
        assert_eq!("openai".parse::<DriverId>().unwrap(), DriverId::OpenAI);
        assert_eq!(
            "openrouter".parse::<DriverId>().unwrap(),
            DriverId::OpenRouter
        );
        assert_eq!(
            "openai_completions".parse::<DriverId>().unwrap(),
            DriverId::OpenAICompletions
        );
        assert_eq!(
            "azure_openai".parse::<DriverId>().unwrap(),
            DriverId::AzureOpenAI
        );
        assert_eq!(
            "anthropic".parse::<DriverId>().unwrap(),
            DriverId::Anthropic
        );
        assert_eq!("gemini".parse::<DriverId>().unwrap(), DriverId::Gemini);
        // Unknown ids parse to External rather than erroring.
        assert_eq!(
            "ollama".parse::<DriverId>().unwrap(),
            DriverId::external("ollama")
        );
        assert_eq!(
            "custom".parse::<DriverId>().unwrap(),
            DriverId::external("custom")
        );
    }

    #[test]
    fn test_external_provider_id_is_case_insensitive() {
        // Built-in matching and external normalization are both case-folding,
        // so the same id in different casing resolves to one provider.
        assert_eq!("OpenAI".parse::<DriverId>().unwrap(), DriverId::OpenAI);
        assert_eq!(
            "Ollama".parse::<DriverId>().unwrap(),
            "ollama".parse::<DriverId>().unwrap()
        );
        assert_eq!(DriverId::external("OpenAI-Codex").as_str(), "openai-codex");
        // Registration and parsed lookup agree regardless of casing.
        assert_eq!(
            DriverId::external("MyProvider"),
            "myprovider".parse::<DriverId>().unwrap()
        );
    }

    #[test]
    fn test_provider_type_display() {
        assert_eq!(DriverId::OpenAI.to_string(), "openai");
        assert_eq!(DriverId::OpenRouter.to_string(), "openrouter");
        assert_eq!(DriverId::AzureOpenAI.to_string(), "azure_openai");
        assert_eq!(
            DriverId::OpenAICompletions.to_string(),
            "openai_completions"
        );
        assert_eq!(DriverId::Anthropic.to_string(), "anthropic");
        assert_eq!(DriverId::Gemini.to_string(), "gemini");
    }

    #[test]
    fn test_provider_config_builder() {
        let config = ProviderConfig::new(DriverId::Anthropic)
            .with_api_key("test-key")
            .with_base_url("https://custom.api.com");

        assert_eq!(config.provider_type, DriverId::Anthropic);
        assert_eq!(config.api_key, Some("test-key".to_string()));
        assert_eq!(config.base_url, Some("https://custom.api.com".to_string()));
    }

    #[test]
    fn test_driver_registry_requires_api_key() {
        // Register a mock factory
        let mut registry = DriverRegistry::new();
        registry.register(DriverId::OpenAI, |_config| {
            // Return a mock driver - just need something that compiles
            struct MockDriver;
            #[async_trait]
            impl ChatDriver for MockDriver {
                async fn chat_completion_stream(
                    &self,
                    _messages: Vec<LlmMessage>,
                    _config: &LlmCallConfig,
                ) -> Result<LlmResponseStream> {
                    unimplemented!()
                }
            }
            Box::new(MockDriver)
        });

        // Driver without API key should fail
        let config = ProviderConfig::new(DriverId::OpenAI);
        let result = registry.create_chat_driver(&config);
        assert!(result.is_err());

        // Driver with API key should succeed
        let config_with_key = ProviderConfig::new(DriverId::OpenAI).with_api_key("test-key");
        let result = registry.create_chat_driver(&config_with_key);
        assert!(result.is_ok());
    }

    #[test]
    fn test_driver_registry_returns_error_for_unregistered_provider() {
        let registry = DriverRegistry::new();
        let config = ProviderConfig::new(DriverId::Anthropic).with_api_key("test-key");

        let result = registry.create_chat_driver(&config);

        // Should fail with DriverNotRegistered error
        if let Err(AgentLoopError::DriverNotRegistered(provider)) = result {
            assert_eq!(provider, "anthropic");
        } else {
            panic!("Expected DriverNotRegistered error");
        }
    }

    #[test]
    fn test_driver_registry_registration() {
        let mut registry = DriverRegistry::new();

        assert!(!registry.has_driver(&DriverId::OpenAI));
        assert!(!registry.has_driver(&DriverId::Anthropic));

        registry.register(DriverId::OpenAI, |_config| {
            struct MockDriver;
            #[async_trait]
            impl ChatDriver for MockDriver {
                async fn chat_completion_stream(
                    &self,
                    _messages: Vec<LlmMessage>,
                    _config: &LlmCallConfig,
                ) -> Result<LlmResponseStream> {
                    unimplemented!()
                }
            }
            Box::new(MockDriver)
        });

        assert!(registry.has_driver(&DriverId::OpenAI));
        assert!(!registry.has_driver(&DriverId::Anthropic));
    }

    #[test]
    fn test_register_external_and_create_driver_without_api_key() {
        struct MockDriver;
        #[async_trait]
        impl ChatDriver for MockDriver {
            async fn chat_completion_stream(
                &self,
                _messages: Vec<LlmMessage>,
                _config: &LlmCallConfig,
            ) -> Result<LlmResponseStream> {
                unimplemented!()
            }
        }

        let mut registry = DriverRegistry::new();
        registry.register_external("openai-codex", |config| {
            // External providers may authenticate via metadata, not an api_key.
            assert_eq!(config.provider_type, DriverId::external("openai-codex"));
            Box::new(MockDriver)
        });

        assert!(registry.has_driver(&DriverId::external("openai-codex")));

        // No api_key required for external providers.
        let config = ProviderConfig::new(DriverId::external("openai-codex")).with_metadata(
            ProviderMetadata {
                refresh_token: Some("rt".into()),
                ..Default::default()
            },
        );
        assert!(registry.create_chat_driver(&config).is_ok());
    }

    #[test]
    fn test_register_defaults_to_chat_only_descriptor() {
        struct MockDriver;
        #[async_trait]
        impl ChatDriver for MockDriver {
            async fn chat_completion_stream(
                &self,
                _messages: Vec<LlmMessage>,
                _config: &LlmCallConfig,
            ) -> Result<LlmResponseStream> {
                unimplemented!()
            }
        }

        let mut registry = DriverRegistry::new();
        registry.register(DriverId::Anthropic, |_config| Box::new(MockDriver));

        let descriptor = registry.descriptor(&DriverId::Anthropic).unwrap();
        assert_eq!(descriptor.display_name, "Anthropic");
        assert_eq!(descriptor.services, vec![ServiceKind::Chat]);
        assert!(descriptor.chat.is_some());
        // Default credential shape is a single required api_key field.
        assert_eq!(descriptor.credential_schema.fields.len(), 1);
        assert_eq!(descriptor.credential_schema.fields[0].name, "api_key");
        assert!(descriptor.credential_schema.fields[0].required);

        // Keyless drivers default to an empty schema.
        registry.register(DriverId::LlmSim, |_config| Box::new(MockDriver));
        let sim = registry.descriptor(&DriverId::LlmSim).unwrap();
        assert!(sim.credential_schema.fields.is_empty());
    }

    #[test]
    fn test_descriptor_services_and_lookup() {
        struct MockDriver;
        #[async_trait]
        impl ChatDriver for MockDriver {
            async fn chat_completion_stream(
                &self,
                _messages: Vec<LlmMessage>,
                _config: &LlmCallConfig,
            ) -> Result<LlmResponseStream> {
                unimplemented!()
            }
        }

        let mut registry = DriverRegistry::new();
        registry.register_descriptor(DriverDescriptor {
            services: vec![ServiceKind::Chat, ServiceKind::Realtime],
            ..DriverDescriptor::chat_only(DriverId::OpenAI, |_config| Box::new(MockDriver))
        });
        registry.register(DriverId::Anthropic, |_config| Box::new(MockDriver));

        assert!(registry.supports(&DriverId::OpenAI, ServiceKind::Chat));
        assert!(registry.supports(&DriverId::OpenAI, ServiceKind::Realtime));
        assert!(!registry.supports(&DriverId::Anthropic, ServiceKind::Realtime));
        assert!(!registry.supports(&DriverId::Gemini, ServiceKind::Chat));

        let realtime = registry.providers_for(ServiceKind::Realtime);
        assert_eq!(realtime, vec![DriverId::OpenAI]);
        let mut chat = registry.providers_for(ServiceKind::Chat);
        chat.sort_by_key(|p| p.to_string());
        assert_eq!(chat, vec![DriverId::Anthropic, DriverId::OpenAI]);
    }

    #[test]
    fn test_create_chat_driver_fails_without_chat_factory() {
        let mut registry = DriverRegistry::new();
        registry.register_descriptor(DriverDescriptor {
            id: DriverId::external("embeddings-only"),
            display_name: "Embeddings Only".to_string(),
            services: vec![ServiceKind::Embeddings],
            credential_schema: CredentialFormSchema::empty(),
            chat: None,
            embeddings: None,
        });

        let config = ProviderConfig::new(DriverId::external("embeddings-only"));
        let err = match registry.create_chat_driver(&config) {
            Ok(_) => panic!("expected error for missing chat factory"),
            Err(err) => err,
        };
        assert!(
            err.to_string()
                .contains("does not implement the chat service"),
            "unexpected error: {err}"
        );
    }

    #[test]
    #[should_panic(expected = "already registered")]
    fn test_register_duplicate_panics() {
        struct MockDriver;
        #[async_trait]
        impl ChatDriver for MockDriver {
            async fn chat_completion_stream(
                &self,
                _messages: Vec<LlmMessage>,
                _config: &LlmCallConfig,
            ) -> Result<LlmResponseStream> {
                unimplemented!()
            }
        }

        let mut registry = DriverRegistry::new();
        registry.register(DriverId::OpenAI, |_config| Box::new(MockDriver));
        // Second registration for the same provider must panic.
        registry.register(DriverId::OpenAI, |_config| Box::new(MockDriver));
    }

    #[test]
    fn test_register_or_replace_overwrites() {
        struct MockDriver;
        #[async_trait]
        impl ChatDriver for MockDriver {
            async fn chat_completion_stream(
                &self,
                _messages: Vec<LlmMessage>,
                _config: &LlmCallConfig,
            ) -> Result<LlmResponseStream> {
                unimplemented!()
            }
        }

        let mut registry = DriverRegistry::new();
        registry.register(DriverId::LlmSim, |_config| Box::new(MockDriver));
        // Replacing intentionally must not panic.
        registry.register_or_replace(DriverId::LlmSim, |_config| Box::new(MockDriver));
        assert!(registry.has_driver(&DriverId::LlmSim));
    }

    // ========================================================================
    // Image resolution tests
    // ========================================================================

    use crate::{ContentPart, ImageFileContentPart, Message, MessageRole, TextContentPart};

    #[test]
    fn test_message_has_image_files_with_image_file() {
        let message = Message {
            id: uuid::Uuid::new_v4().into(),
            role: MessageRole::User,
            content: vec![
                ContentPart::Text(TextContentPart {
                    text: "Look at this image".to_string(),
                }),
                ContentPart::ImageFile(ImageFileContentPart {
                    image_id: uuid::Uuid::new_v4().into(),
                    filename: Some("test.png".to_string()),
                }),
            ],
            phase: None,
            thinking: None,
            thinking_signature: None,
            controls: None,
            metadata: None,
            external_actor: None,
            created_at: chrono::Utc::now(),
        };

        assert!(LlmMessage::message_has_image_files(&message));
    }

    #[test]
    fn test_message_has_image_files_without_image_file() {
        let message = Message {
            id: uuid::Uuid::new_v4().into(),
            role: MessageRole::User,
            content: vec![ContentPart::Text(TextContentPart {
                text: "Just text".to_string(),
            })],
            phase: None,
            thinking: None,
            thinking_signature: None,
            controls: None,
            metadata: None,
            external_actor: None,
            created_at: chrono::Utc::now(),
        };

        assert!(!LlmMessage::message_has_image_files(&message));
    }

    #[test]
    fn test_extract_image_file_ids() {
        let id1 = uuid::Uuid::new_v4();
        let id2 = uuid::Uuid::new_v4();

        let message = Message {
            id: uuid::Uuid::new_v4().into(),
            role: MessageRole::User,
            content: vec![
                ContentPart::Text(TextContentPart {
                    text: "Look at these images".to_string(),
                }),
                ContentPart::ImageFile(ImageFileContentPart {
                    image_id: id1.into(),
                    filename: Some("test1.png".to_string()),
                }),
                ContentPart::ImageFile(ImageFileContentPart {
                    image_id: id2.into(),
                    filename: Some("test2.png".to_string()),
                }),
            ],
            phase: None,
            thinking: None,
            thinking_signature: None,
            controls: None,
            metadata: None,
            external_actor: None,
            created_at: chrono::Utc::now(),
        };

        let ids = LlmMessage::extract_image_file_ids(&message);
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&id1));
        assert!(ids.contains(&id2));
    }

    #[test]
    fn test_from_message_with_images_text_only() {
        let message = Message {
            id: uuid::Uuid::new_v4().into(),
            role: MessageRole::User,
            content: vec![ContentPart::Text(TextContentPart {
                text: "Hello".to_string(),
            })],
            phase: None,
            thinking: None,
            thinking_signature: None,
            controls: None,
            metadata: None,
            external_actor: None,
            created_at: chrono::Utc::now(),
        };

        let resolved = std::collections::HashMap::new();
        let llm_message = LlmMessage::from_message_with_images(&message, &resolved);

        assert_eq!(llm_message.role, LlmMessageRole::User);
        match llm_message.content {
            LlmMessageContent::Text(text) => assert_eq!(text, "Hello"),
            _ => panic!("Expected text content"),
        }
    }

    #[test]
    fn test_from_message_with_images_resolved_image() {
        let image_id = uuid::Uuid::new_v4();
        let message = Message {
            id: uuid::Uuid::new_v4().into(),
            role: MessageRole::User,
            content: vec![
                ContentPart::Text(TextContentPart {
                    text: "Look at this".to_string(),
                }),
                ContentPart::ImageFile(ImageFileContentPart {
                    image_id: image_id.into(),
                    filename: Some("test.png".to_string()),
                }),
            ],
            phase: None,
            thinking: None,
            thinking_signature: None,
            controls: None,
            metadata: None,
            external_actor: None,
            created_at: chrono::Utc::now(),
        };

        let mut resolved = std::collections::HashMap::new();
        resolved.insert(
            image_id,
            crate::ResolvedImage::new("base64data", "image/png"),
        );

        let llm_message = LlmMessage::from_message_with_images(&message, &resolved);

        match &llm_message.content {
            LlmMessageContent::Parts(parts) => {
                assert_eq!(parts.len(), 2);
                // First part should be text
                assert!(matches!(&parts[0], LlmContentPart::Text { .. }));
                // Second part should be resolved image
                if let LlmContentPart::Image { url } = &parts[1] {
                    assert!(url.starts_with("data:image/png;base64,"));
                } else {
                    panic!("Expected image content part");
                }
            }
            _ => panic!("Expected parts content"),
        }
    }

    #[test]
    fn test_from_message_with_images_unresolved_image() {
        let image_id = uuid::Uuid::new_v4();
        let message = Message {
            id: uuid::Uuid::new_v4().into(),
            role: MessageRole::User,
            content: vec![ContentPart::ImageFile(ImageFileContentPart {
                image_id: image_id.into(),
                filename: Some("missing.png".to_string()),
            })],
            phase: None,
            thinking: None,
            thinking_signature: None,
            controls: None,
            metadata: None,
            external_actor: None,
            created_at: chrono::Utc::now(),
        };

        // Empty resolved map - image not found
        let resolved = std::collections::HashMap::new();
        let llm_message = LlmMessage::from_message_with_images(&message, &resolved);

        // Should have placeholder text for missing image
        // When there's only one part, it may return Text directly instead of Parts
        match &llm_message.content {
            LlmMessageContent::Text(text) => {
                assert!(text.contains("Image not found"));
            }
            LlmMessageContent::Parts(parts) => {
                assert_eq!(parts.len(), 1);
                if let LlmContentPart::Text { text } = &parts[0] {
                    assert!(text.contains("Image not found"));
                } else {
                    panic!("Expected text placeholder for missing image");
                }
            }
        }
    }

    #[test]
    fn test_prepend_text_prefix_simple_text() {
        let mut msg = LlmMessage::text(LlmMessageRole::User, "Hello bot");
        msg.prepend_text_prefix("[Alice] ");
        assert_eq!(msg.content_as_text(), "[Alice] Hello bot");
    }

    #[test]
    fn test_prepend_text_prefix_parts() {
        let mut msg = LlmMessage::parts(
            LlmMessageRole::User,
            vec![
                LlmContentPart::Text {
                    text: "Hello".to_string(),
                },
                LlmContentPart::Image {
                    url: "data:image/png;base64,abc".to_string(),
                },
            ],
        );
        msg.prepend_text_prefix("[Bob] ");
        match &msg.content {
            LlmMessageContent::Parts(parts) => {
                if let LlmContentPart::Text { text } = &parts[0] {
                    assert_eq!(text, "[Bob] Hello");
                } else {
                    panic!("Expected text part");
                }
            }
            _ => panic!("Expected parts content"),
        }
    }

    #[test]
    fn test_prepend_text_prefix_parts_no_text() {
        let mut msg = LlmMessage::parts(
            LlmMessageRole::User,
            vec![LlmContentPart::Image {
                url: "data:image/png;base64,abc".to_string(),
            }],
        );
        msg.prepend_text_prefix("[Eve] ");
        match &msg.content {
            LlmMessageContent::Parts(parts) => {
                assert_eq!(parts.len(), 2);
                if let LlmContentPart::Text { text } = &parts[0] {
                    assert_eq!(text, "[Eve] ");
                } else {
                    panic!("Expected prepended text part");
                }
            }
            _ => panic!("Expected parts content"),
        }
    }

    #[test]
    fn test_openrouter_plugin_config_is_empty() {
        assert!(OpenRouterPluginConfig::default().is_empty());
        assert!(
            !OpenRouterPluginConfig {
                web: Some(OpenRouterWebSearchPlugin::default()),
                file: None,
            }
            .is_empty()
        );
        assert!(
            !OpenRouterPluginConfig {
                web: None,
                file: Some(OpenRouterFilePlugin {}),
            }
            .is_empty()
        );
    }

    #[test]
    fn test_openrouter_routing_is_empty_with_plugins() {
        let with_plugins = OpenRouterRoutingConfig {
            plugins: Some(OpenRouterPluginConfig {
                web: Some(OpenRouterWebSearchPlugin::default()),
                file: None,
            }),
            ..Default::default()
        };
        assert!(!with_plugins.is_empty());

        let empty_plugins = OpenRouterRoutingConfig {
            plugins: Some(OpenRouterPluginConfig::default()),
            ..Default::default()
        };
        assert!(empty_plugins.is_empty());
    }

    #[test]
    fn test_openrouter_web_search_plugin_serialization() {
        let plugin = OpenRouterWebSearchPlugin {
            max_results: Some(10),
            search_prompt: Some("search for Rust crates".to_string()),
        };
        let json = serde_json::to_value(&plugin).unwrap();
        assert_eq!(json["max_results"], 10);
        assert_eq!(json["search_prompt"], "search for Rust crates");
    }

    #[test]
    fn test_openrouter_web_search_plugin_omits_none_fields() {
        let plugin = OpenRouterWebSearchPlugin::default();
        let json = serde_json::to_value(&plugin).unwrap();
        assert!(json.get("max_results").is_none());
        assert!(json.get("search_prompt").is_none());
    }

    #[test]
    fn test_capacity_strategy_shared_capacity_is_noop() {
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            capacity_strategy: Some(OpenRouterCapacityStrategy::SharedCapacity),
            ..Default::default()
        };
        let result = base.apply_capacity_strategy().unwrap();
        assert_eq!(
            result.capacity_strategy,
            Some(OpenRouterCapacityStrategy::SharedCapacity)
        );
        assert!(result.provider.is_none());
    }

    #[test]
    fn test_capacity_strategy_none_is_noop() {
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            capacity_strategy: None,
            ..Default::default()
        };
        let result = base.apply_capacity_strategy().unwrap();
        assert!(result.provider.is_none());
    }

    #[test]
    fn test_capacity_strategy_byok_first_sets_allow_fallbacks() {
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            capacity_strategy: Some(OpenRouterCapacityStrategy::ByokFirst),
            ..Default::default()
        };
        let result = base.apply_capacity_strategy().unwrap();
        let provider = result.provider.as_ref().expect("provider set by ByokFirst");
        assert_eq!(provider.allow_fallbacks, Some(true));
    }

    #[test]
    fn test_capacity_strategy_byok_first_preserves_explicit_allow_fallbacks() {
        // If allow_fallbacks was already set explicitly, ByokFirst must not override it.
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            capacity_strategy: Some(OpenRouterCapacityStrategy::ByokFirst),
            provider: Some(OpenRouterProviderRouting {
                allow_fallbacks: Some(false),
                ..Default::default()
            }),
            ..Default::default()
        };
        let result = base.apply_capacity_strategy().unwrap();
        let provider = result.provider.as_ref().unwrap();
        assert_eq!(provider.allow_fallbacks, Some(false));
    }

    #[test]
    fn test_capacity_strategy_byok_only_requires_provider_only() {
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            capacity_strategy: Some(OpenRouterCapacityStrategy::ByokOnly),
            ..Default::default()
        };
        let err = base.apply_capacity_strategy().unwrap_err();
        assert!(
            err.contains("provider.only"),
            "error should mention provider.only: {err}"
        );
    }

    #[test]
    fn test_capacity_strategy_byok_only_disables_fallbacks() {
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            capacity_strategy: Some(OpenRouterCapacityStrategy::ByokOnly),
            provider: Some(OpenRouterProviderRouting {
                only: vec!["my-byok-provider".to_string()],
                ..Default::default()
            }),
            ..Default::default()
        };
        let result = base.apply_capacity_strategy().unwrap();
        let provider = result.provider.as_ref().unwrap();
        assert_eq!(provider.allow_fallbacks, Some(false));
        assert_eq!(provider.only, vec!["my-byok-provider"]);
    }

    #[test]
    fn test_capacity_strategy_byok_only_not_empty_in_is_empty() {
        let with_strategy = OpenRouterRoutingConfig {
            capacity_strategy: Some(OpenRouterCapacityStrategy::ByokOnly),
            ..Default::default()
        };
        assert!(!with_strategy.is_empty());

        let byok_first = OpenRouterRoutingConfig {
            capacity_strategy: Some(OpenRouterCapacityStrategy::ByokFirst),
            ..Default::default()
        };
        assert!(!byok_first.is_empty());

        let shared = OpenRouterRoutingConfig {
            capacity_strategy: Some(OpenRouterCapacityStrategy::SharedCapacity),
            ..Default::default()
        };
        assert!(shared.is_empty());
    }

    // -------------------------------------------------------------------------
    // OpenRouterRoutingPreset tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_preset_no_presets_is_noop() {
        let base = OpenRouterRoutingConfig {
            models: vec!["openai/gpt-5-mini".to_string()],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        assert_eq!(result, base);
    }

    #[test]
    fn test_preset_cheapest_with_tools_sets_require_parameters_and_sort_price() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::CheapestWithTools],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        assert!(result.presets.is_empty(), "presets cleared after apply");
        let provider = result.provider.expect("provider set by preset");
        assert_eq!(provider.require_parameters, Some(true));
        assert_eq!(
            provider.sort,
            Some(OpenRouterProviderSort::Simple(
                OpenRouterProviderSortBy::Price
            ))
        );
    }

    #[test]
    fn test_preset_lowest_latency_review_sets_sort_throughput() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::LowestLatencyReview],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set by preset");
        assert_eq!(
            provider.sort,
            Some(OpenRouterProviderSort::Simple(
                OpenRouterProviderSortBy::Throughput
            ))
        );
    }

    #[test]
    fn test_preset_zdr_only_sets_zdr() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::ZdrOnly],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        assert_eq!(provider.zdr, Some(true));
    }

    #[test]
    fn test_preset_byok_first_sets_allow_fallbacks() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::ByokFirst],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        assert_eq!(provider.allow_fallbacks, Some(true));
    }

    #[test]
    fn test_preset_no_data_collection_sets_data_collection_deny() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::NoDataCollection],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        assert_eq!(
            provider.data_collection,
            Some(OpenRouterDataCollection::Deny)
        );
    }

    #[test]
    fn test_preset_strict_json_sets_require_parameters() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::StrictJson],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        assert_eq!(provider.require_parameters, Some(true));
    }

    #[test]
    fn test_preset_reasoning_required_sets_require_parameters() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::ReasoningRequired],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        assert_eq!(provider.require_parameters, Some(true));
    }

    #[test]
    fn test_preset_max_price_converts_usd_per_million() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::MaxPrice {
                prompt_usd_per_million: Some(5.0),
                completion_usd_per_million: Some(15.0),
            }],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        let max_price = provider.max_price.expect("max_price set");
        // 5.0 USD/M → 5.0 / 1_000_000 per token
        let prompt = max_price.prompt.expect("prompt set");
        assert!((prompt - 5.0 / 1_000_000.0).abs() < f64::EPSILON);
        let completion = max_price.completion.expect("completion set");
        assert!((completion - 15.0 / 1_000_000.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_preset_max_price_rejects_negative_values() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::MaxPrice {
                prompt_usd_per_million: Some(-1.0),
                completion_usd_per_million: None,
            }],
            ..Default::default()
        };
        let err = base.apply_presets().unwrap_err();
        assert!(
            err.contains("non-negative"),
            "error should mention non-negative: {err}"
        );
    }

    #[test]
    fn test_preset_max_price_both_none_no_provider_field() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::MaxPrice {
                prompt_usd_per_million: None,
                completion_usd_per_million: None,
            }],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        assert!(
            result.provider.is_none(),
            "MaxPrice with no dimensions should not produce a provider field"
        );
    }

    #[test]
    fn test_preset_explicit_provider_overrides_preset() {
        let base = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::CheapestWithTools],
            provider: Some(OpenRouterProviderRouting {
                // Caller explicitly wants throughput sort, overriding Price preset
                sort: Some(OpenRouterProviderSort::Simple(
                    OpenRouterProviderSortBy::Throughput,
                )),
                ..Default::default()
            }),
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        // Explicit sort wins
        assert_eq!(
            provider.sort,
            Some(OpenRouterProviderSort::Simple(
                OpenRouterProviderSortBy::Throughput
            ))
        );
        // But preset-derived require_parameters still set (not overridden by explicit)
        assert_eq!(provider.require_parameters, Some(true));
    }

    #[test]
    fn test_preset_multiple_presets_combined() {
        let base = OpenRouterRoutingConfig {
            presets: vec![
                OpenRouterRoutingPreset::ZdrOnly,
                OpenRouterRoutingPreset::NoDataCollection,
                OpenRouterRoutingPreset::LowestLatencyReview,
            ],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        assert_eq!(provider.zdr, Some(true));
        assert_eq!(
            provider.data_collection,
            Some(OpenRouterDataCollection::Deny)
        );
        assert_eq!(
            provider.sort,
            Some(OpenRouterProviderSort::Simple(
                OpenRouterProviderSortBy::Throughput
            ))
        );
    }

    #[test]
    fn test_preset_later_preset_overrides_sort() {
        let base = OpenRouterRoutingConfig {
            presets: vec![
                OpenRouterRoutingPreset::CheapestWithTools, // sets Price sort
                OpenRouterRoutingPreset::LowestLatencyReview, // overrides to Throughput
            ],
            ..Default::default()
        };
        let result = base.apply_presets().unwrap();
        let provider = result.provider.expect("provider set");
        // Later preset wins for sort
        assert_eq!(
            provider.sort,
            Some(OpenRouterProviderSort::Simple(
                OpenRouterProviderSortBy::Throughput
            ))
        );
        // require_parameters still set by CheapestWithTools
        assert_eq!(provider.require_parameters, Some(true));
    }

    #[test]
    fn test_preset_non_empty_in_is_empty() {
        let with_preset = OpenRouterRoutingConfig {
            presets: vec![OpenRouterRoutingPreset::ZdrOnly],
            ..Default::default()
        };
        assert!(!with_preset.is_empty());

        let without = OpenRouterRoutingConfig::default();
        assert!(without.is_empty());
    }
}