loopctl 0.3.0

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

use std::future::Future;
use std::pin::Pin;

use futures::stream::Stream;
use serde_json::Value;
use std::time::Duration;

use crate::api::ApiClient;
use crate::api::error::ApiError;
use crate::message::{Message, MessagePart, Role};
use crate::stream::{
    DeltaPart, IndexedDelta, MessageDelta, MessageDeltaPayload, MessageMetadata, MessageStart,
    PartStart, StreamEvent, StreamStopReason, Usage,
};
use crate::structured::ToolConstraint;
use crate::structured::tighten_json_schema;
use crate::tool::ToolSchema;

const DEFAULT_BASE_URL: &str = "https://generativelanguage.googleapis.com/v1beta";
const DEFAULT_MODEL: &str = "gemini-2.0-flash";
const TEXT_PART_INDEX: usize = 0;
const THINKING_PART_INDEX: usize = 1;

/// A Google Gemini API client with streaming support.
///
/// Implements [`ApiClient`] by translating between the framework's
/// [`StreamEvent`] protocol and the Gemini Streaming Generate Content API.
pub struct GeminiClient {
    /// The underlying HTTP client (connection-pooled `reqwest::Client`).
    ///
    /// Created once at build time with the configured timeouts; reused
    /// across all requests for connection pooling.
    http: reqwest::Client,

    /// The Gemini API key used for authentication.
    ///
    /// Sent as the `x-goog-api-key` header on every request. Set via
    /// [`GeminiClientBuilder::api_key`].
    api_key: String,

    /// The base URL for API requests.
    ///
    /// The streaming endpoint is `{base_url}/models/{model}:streamGenerateContent`
    /// and the non-streaming endpoint is `{base_url}/models/{model}:generateContent`.
    /// Defaults to `https://generativelanguage.googleapis.com/v1beta`.
    base_url: String,

    /// The current model identifier, stored behind a mutex for runtime
    /// hot-swapping.
    ///
    /// Changed via [`ApiClient::set_model`] (host-initiated swaps) or
    /// overridden per request via
    /// [`RequestOptions::model`](crate::structured::RequestOptions::model)
    /// — the channel the fallback machinery routes through, leaving the
    /// client itself untouched.
    model: std::sync::Mutex<String>,

    /// Whether to request thought summaries from reasoning-capable models.
    ///
    /// When `true`, every request body gets
    /// `generationConfig.thinkingConfig.includeThoughts = true`. The Gemini
    /// API rejects `thinkingConfig` with `400 INVALID_ARGUMENT` on models
    /// that don't support thinking, so this is opt-in — the caller must know
    /// their model is reasoning-capable (e.g. Gemini 2.5 Pro/Flash, Gemini 3)
    /// before enabling it. Defaults to `false`. Set via
    /// [`GeminiClientBuilder::include_thoughts`].
    include_thoughts: bool,
}

impl GeminiClient {
    /// Create a builder for configuring a [`GeminiClient`].
    ///
    /// Returns a [`GeminiClientBuilder`] with sensible defaults. The only
    /// required field is `api_key`; everything else has a production-ready
    /// default. Call `.with_api_key(...).build()` to finish, or chain additional
    /// setters for custom configuration.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use loopctl::provider::GeminiClient;
    ///
    /// let client = GeminiClient::builder()
    ///     .with_api_key("AI...")
    ///     .with_model("gemini-2.0-flash")
    ///     .build()
    /// .unwrap();
    /// ```
    #[must_use]
    pub fn builder() -> GeminiClientBuilder {
        GeminiClientBuilder::default()
    }

    /// Create a client from environment variables.
    ///
    /// Reads the following variables:
    ///
    /// - `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) — **required**. The API key
    ///   for authentication.
    /// - `GEMINI_BASE_URL` — optional. Defaults to
    ///   `https://generativelanguage.googleapis.com/v1beta`.
    /// - `GEMINI_MODEL` — optional. Defaults to `gemini-2.0-flash`.
    ///
    /// This is a convenience constructor that delegates to
    /// [`builder`](Self::builder) with the env vars as setter arguments.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError`] if no API key is found.
    pub fn from_env() -> Result<Self, ApiError> {
        let api_key = std::env::var("GEMINI_API_KEY")
            .or_else(|_| std::env::var("GOOGLE_API_KEY"))
            .map_err(|_| ApiError::auth_invalid_key("GEMINI_API_KEY not set"))?;
        let base_url = std::env::var("GEMINI_BASE_URL").unwrap_or_else(|_| DEFAULT_BASE_URL.into());
        let model = std::env::var("GEMINI_MODEL").unwrap_or_else(|_| DEFAULT_MODEL.into());

        Self::builder()
            .with_api_key(api_key)
            .with_base_url(base_url)
            .with_model(model)
            .build()
    }

    /// Build the streaming Generate Content URL for one resolved model.
    ///
    /// Gemini puts the model in the URL path — the caller resolves it (the
    /// client's current model, or a per-request override from
    /// [`RequestOptions::model`](crate::structured::RequestOptions::model)).
    /// The API key is sent via the `x-goog-api-key` header, never as a
    /// query parameter.
    fn stream_url_for_model(&self, model: &str) -> String {
        format!(
            "{}/models/{model}:streamGenerateContent?alt=sse",
            self.base_url
        )
    }

    /// Build the non-streaming Generate Content URL for the current model.
    ///
    /// Constructs `{base_url}/models/{model}:generateContent`. The API key
    /// is sent via the `x-goog-api-key` header, not in the URL. Used by
    /// [`ApiClient::create_message`] and its `*_with_options` variant.
    fn generate_url(&self) -> String {
        let model = crate::error::recover_guard(self.model.lock()).clone();
        self.generate_url_for_model(&model)
    }

    /// Build the non-streaming Generate Content URL for one resolved model.
    ///
    /// Shared by the client-model path and the per-request override path
    /// (see [`stream_url_for_model`](Self::stream_url_for_model)).
    fn generate_url_for_model(&self, model: &str) -> String {
        format!("{}/models/{model}:generateContent", self.base_url)
    }

    /// Build a typed [`NonStreamingResponse`] from Gemini's native JSON.
    ///
    /// Reads `candidates[0].content.parts` into [`MessagePart`]s: each `text`
    /// field becomes a [`MessagePart::Text`] part and each `functionCall`
    /// becomes a [`MessagePart::ToolCall`] with its `id` preserved when
    /// present (Gemini 3 assigns a unique id per call; older versions omit
    /// it, in which case the id defaults to an empty string) and its `args`
    /// normalized by [`normalize_function_args`] (absent or `null` becomes
    /// an empty object). Parts flagged
    /// `thought: true` are skipped — reasoning is stream-only in this crate,
    /// so their summaries are dropped rather than surfaced as visible text,
    /// matching what the streaming accumulator's text lane yields. A single
    /// part may hold both `text` and `functionCall`, in which case it yields
    /// two parts. Maps `candidates[0].finishReason` to a [`StreamStopReason`]
    /// using the same mapping the streaming emitter applies: `"MAX_TOKENS"` →
    /// `MaxTokens`, anything else (including the `"STOP"` default) →
    /// `EndTurn`. Reads `usageMetadata.promptTokenCount` and
    /// `candidatesTokenCount` (plus `thoughtsTokenCount`) into [`Usage`],
    /// returning `None` when the object is absent or all-zero.
    fn build_response(raw: &Value) -> crate::api::NonStreamingResponse {
        let mut parts: Vec<MessagePart> = Vec::new();
        if let Some(content_parts) = raw
            .pointer("/candidates/0/content/parts")
            .and_then(|p| p.as_array())
        {
            for part in content_parts {
                let is_thought = part
                    .get("thought")
                    .and_then(Value::as_bool)
                    .unwrap_or(false);
                if !is_thought && let Some(text) = part.get("text").and_then(|t| t.as_str()) {
                    parts.push(MessagePart::text(text));
                }
                if let Some(fc) = part.get("functionCall") {
                    let id = fc.get("id").and_then(|v| v.as_str()).unwrap_or("");
                    let name = fc.get("name").and_then(|v| v.as_str()).unwrap_or("");
                    let input = normalize_function_args(fc);
                    parts.push(MessagePart::tool_call(id, name, input));
                }
            }
        }
        let reason = raw
            .pointer("/candidates/0/finishReason")
            .and_then(|r| r.as_str())
            .unwrap_or("STOP");
        let stop_reason = match reason {
            "MAX_TOKENS" => StreamStopReason::MaxTokens,
            _ => StreamStopReason::EndTurn,
        };
        let usage = extract_usage(raw);
        crate::api::NonStreamingResponse {
            message: Message::new(Role::Assistant, parts),
            stop_reason,
            usage,
        }
    }

    /// Send a POST request and return the raw response.
    ///
    /// Shared by both [`ApiClient::stream_messages`] and
    /// [`ApiClient::create_message`]. Delegates to
    /// [`post_json_checked`](super::post_json_checked), which classifies
    /// non-success responses (auth rejections, rate limits with their
    /// server-advised delay) into structured [`ApiError`] variants.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError`] if the request fails or the server
    /// responds with a non-success status code.
    async fn post_content(
        http: &reqwest::Client,
        url: &str,
        api_key: &str,
        body: &Value,
    ) -> Result<reqwest::Response, ApiError> {
        let mut key_header = reqwest::header::HeaderValue::from_str(api_key)
            .map_err(|e| ApiError::auth_invalid_key(format!("invalid api key header: {e}")))?;
        key_header.set_sensitive(true);
        super::post_json_checked(
            http,
            url,
            &[(
                reqwest::header::HeaderName::from_static("x-goog-api-key"),
                key_header,
            )],
            body,
        )
        .await
    }
}

/// Normalize a function call's `args` field into the tool-call input.
///
/// Gemini omits `args` for parameterless calls, and some Gemini-compatible
/// frontends send an explicit `null`; both mean "no arguments" and become an
/// empty object, so tool executors always receive an object to read. Any
/// other value passes through verbatim — a non-object `args` is malformed
/// wire data, and silently rewriting it would hide it.
fn normalize_function_args(func_call: &Value) -> Value {
    match func_call.get("args") {
        Some(Value::Object(map)) => Value::Object(map.clone()),
        Some(Value::Null) | None => serde_json::json!({}),
        Some(other) => other.clone(),
    }
}

/// Extract token [`Usage`] from Gemini's native `usageMetadata` object.
///
/// Reads `usageMetadata.promptTokenCount` for input tokens and sums
/// `candidatesTokenCount` plus `thoughtsTokenCount` for output. Returns `None`
/// when the `usageMetadata` object is absent or when all counts are zero,
/// matching the convention used by the streaming emitter in
/// `extract_finish_reason`.
fn extract_usage(raw: &Value) -> Option<Usage> {
    let usage = raw.pointer("/usageMetadata")?;
    let input = usage
        .get("promptTokenCount")
        .and_then(Value::as_u64)
        .and_then(|n| u32::try_from(n).ok())
        .unwrap_or(0);
    let output = usage
        .get("candidatesTokenCount")
        .and_then(Value::as_u64)
        .and_then(|n| u32::try_from(n).ok())
        .unwrap_or(0);
    let thoughts = usage
        .get("thoughtsTokenCount")
        .and_then(Value::as_u64)
        .and_then(|n| u32::try_from(n).ok())
        .unwrap_or(0);
    let total_output = output.saturating_add(thoughts);
    (input > 0 || total_output > 0).then(|| Usage::new(input, total_output))
}

impl ApiClient for GeminiClient {
    fn model(&self) -> String {
        crate::error::recover_guard(self.model.lock()).clone()
    }

    fn base_url(&self) -> String {
        self.base_url.clone()
    }

    fn set_model(&self, model: &str) -> bool {
        if model.trim().is_empty() {
            return false;
        }
        *crate::error::recover_guard(self.model.lock()) = model.to_string();
        true
    }

    fn stream_messages(
        &self,
        request: &crate::api::StreamRequest,
    ) -> Pin<Box<dyn Stream<Item = Result<StreamEvent, ApiError>> + Send + 'static>> {
        self.stream_messages_with_options(request, crate::structured::RequestOptions::default())
    }

    fn create_message(
        &self,
        request: &crate::api::StreamRequest,
    ) -> Pin<Box<dyn Future<Output = Result<crate::api::NonStreamingResponse, ApiError>> + Send + '_>>
    {
        let system = request.system.clone();
        let tools = request.tools.clone();
        let body = build_request_body(
            &request.messages,
            system.as_deref(),
            tools.as_deref(),
            None,
            &ToolConstraint::None,
            self.include_thoughts,
        );
        let url = self.generate_url();

        Box::pin(async move {
            let resp = Self::post_content(&self.http, &url, &self.api_key, &body).await?;
            let resp = super::read_bounded_body(resp).await?;
            let raw = serde_json::from_slice::<Value>(&resp)
                .map_err(|e| ApiError::http(e.to_string()))?;
            Ok(Self::build_response(&raw))
        })
    }

    fn stream_messages_with_options(
        &self,
        request: &crate::api::StreamRequest,
        options: crate::structured::RequestOptions,
    ) -> Pin<Box<dyn Stream<Item = Result<StreamEvent, ApiError>> + Send + 'static>> {
        #[cfg(feature = "grammar")]
        if matches!(&options.tool_constraint, ToolConstraint::Grammar(_)) {
            return Box::pin(futures::stream::once(async move {
                Err(grammar_unsupported_error())
            }));
        }
        if options.response_format.as_ref().is_some_and(|rf| rf.strict) {
            return Box::pin(futures::stream::once(async move {
                Err(strict_unsupported_error("Gemini"))
            }));
        }
        let system = request.system.clone();
        let tools = request.tools.clone();
        let rf = options.response_format.as_ref();
        let body = build_request_body(
            &request.messages,
            system.as_deref(),
            tools.as_deref(),
            rf,
            &options.tool_constraint,
            self.include_thoughts,
        );
        let model = options
            .model
            .clone()
            .unwrap_or_else(|| crate::error::recover_guard(self.model.lock()).clone());
        let url = self.stream_url_for_model(&model);
        let http = self.http.clone();
        let api_key = self.api_key.clone();

        Box::pin(async_stream::try_stream! {
            let resp = Self::post_content(&http, &url, &api_key, &body).await?;
            let mut sse = SseReader::from_response(resp);
            let mut emitter = StreamEmitter::default();

            while let Some(data) = sse.next_gemini_data().await? {
                emitter.process_chunk(&data);
                if emitter.error_recorded() {
                    break;
                }
                for ev in emitter.drain() {
                    yield ev;
                }
            }

            for ev in emitter.finish()? {
                yield ev;
            }
        })
    }

    fn create_message_with_options(
        &self,
        request: &crate::api::StreamRequest,
        options: crate::structured::RequestOptions,
    ) -> Pin<Box<dyn Future<Output = Result<crate::api::NonStreamingResponse, ApiError>> + Send + '_>>
    {
        #[cfg(feature = "grammar")]
        if matches!(&options.tool_constraint, ToolConstraint::Grammar(_)) {
            return Box::pin(async move { Err(grammar_unsupported_error()) });
        }
        if options.response_format.as_ref().is_some_and(|rf| rf.strict) {
            return Box::pin(async move { Err(strict_unsupported_error("Gemini")) });
        }
        let system = request.system.clone();
        let tools = request.tools.clone();
        let response_format = options.response_format.as_ref();
        let body = build_request_body(
            &request.messages,
            system.as_deref(),
            tools.as_deref(),
            response_format,
            &options.tool_constraint,
            self.include_thoughts,
        );
        let model = options
            .model
            .clone()
            .unwrap_or_else(|| crate::error::recover_guard(self.model.lock()).clone());
        let url = self.generate_url_for_model(&model);
        Box::pin(async move {
            let resp = Self::post_content(&self.http, &url, &self.api_key, &body).await?;
            let resp = super::read_bounded_body(resp).await?;
            let raw = serde_json::from_slice::<Value>(&resp)
                .map_err(|e| ApiError::http(e.to_string()))?;
            Ok(Self::build_response(&raw))
        })
    }
}

/// Builder for [`GeminiClient`].
///
/// Created via [`GeminiClientBuilder::default`] or
/// [`GeminiClient::builder`]. All fields have sensible defaults except
/// `api_key`, which must be set before [`build`](Self::build).
pub struct GeminiClientBuilder {
    /// The Gemini API key for authentication (required).
    ///
    /// Must be set before building. Sent as the `x-goog-api-key` header on
    /// every request.
    api_key: Option<String>,

    /// The base URL for API requests.
    ///
    /// Defaults to `https://generativelanguage.googleapis.com/v1beta`.
    base_url: String,

    /// The default model identifier.
    ///
    /// Can be changed at runtime via [`GeminiClient::set_model`].
    model: String,

    /// Whether to opt into thought summaries from reasoning-capable models.
    ///
    /// When `true`, every request gets
    /// `generationConfig.thinkingConfig.includeThoughts = true`. The Gemini
    /// API rejects `thinkingConfig` on non-reasoning models with
    /// `400 INVALID_ARGUMENT`, so this is `false` by default and the caller
    /// must opt in once they know their model supports thinking.
    include_thoughts: bool,

    /// Shared HTTP client configuration (timeouts, pool, TCP).
    ///
    /// Holds the timeout, connection-pool, and TCP knobs that apply to the
    /// internally-built `reqwest::Client`, or an externally-supplied client
    /// injected via [`with_http_client`](Self::with_http_client).
    http: super::HttpClientConfig,
}

impl Default for GeminiClientBuilder {
    fn default() -> Self {
        Self {
            api_key: None,
            base_url: DEFAULT_BASE_URL.into(),
            model: DEFAULT_MODEL.into(),
            include_thoughts: false,
            http: super::HttpClientConfig::default(),
        }
    }
}

impl GeminiClientBuilder {
    /// Set the API key for authentication.
    ///
    /// Required — [`build`](Self::build) returns an error if this is not set.
    /// The key is sent as the `x-goog-api-key` header on every request.
    #[must_use]
    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Set the base URL for API requests.
    ///
    /// Defaults to `https://generativelanguage.googleapis.com/v1beta`.
    /// Trailing `/` separators are trimmed, so joined request paths never
    /// contain `//` — a `…/v1/` base behaves identically to `…/v1`.
    /// Override when targeting a proxy or Google AI-compatible endpoint.
    #[must_use]
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into().trim_end_matches('/').to_string();
        self
    }

    /// Set the default model identifier.
    ///
    /// The model string is embedded in the request URL (e.g.
    /// `/models/{model}:generateContent`), unless a per-request
    /// [`RequestOptions::model`](crate::structured::RequestOptions::model)
    /// override names another. Can also be swapped wholesale at runtime
    /// via [`GeminiClient::set_model`].
    #[must_use]
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    /// Set the HTTP read timeout.
    ///
    /// This bounds *idleness* — how long a gap between bytes on the
    /// connection may last — not the total request lifetime: a stream
    /// that keeps producing bytes runs as long as it keeps producing.
    /// Defaults to 120 seconds. Ignored when a client was supplied via
    /// [`with_http_client`](Self::with_http_client); bound the whole
    /// turn with a [`StreamHandler`](crate::stream::handler::StreamHandler)
    /// total timeout instead.
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.http = self.http.with_timeout(timeout);
        self
    }

    /// Set the TCP connection establishment timeout.
    ///
    /// Defaults to 10 seconds. Ignored when a client was supplied via
    /// [`with_http_client`](Self::with_http_client).
    #[must_use]
    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.http = self.http.with_connect_timeout(timeout);
        self
    }

    /// Opt into thought summaries from reasoning-capable models.
    ///
    /// When enabled, every request body gets
    /// `generationConfig.thinkingConfig.includeThoughts = true`, which asks
    /// Gemini to surface its reasoning alongside the visible answer. Only
    /// reasoning-capable models (e.g. Gemini 2.5 Pro/Flash, Gemini 3) honor
    /// this — non-reasoning models reject `thinkingConfig` with
    /// `400 INVALID_ARGUMENT`, so this defaults to `false`.
    ///
    /// The response-side parser routes `thought: true` parts to
    /// [`DeltaPart::Thinking`] regardless of this flag — it's purely the
    /// request-side opt-in.
    #[must_use]
    pub fn with_include_thoughts(mut self, enabled: bool) -> Self {
        self.include_thoughts = enabled;
        self
    }

    /// Inject a pre-built, shared `reqwest::Client`.
    ///
    /// When set, the client's connection pool is shared with every other
    /// provider built from the same handle, and the pool/TCP knobs are
    /// ignored. Configure timeouts on the injected client, not here.
    #[must_use]
    pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
        self.http = self.http.with_http_client(client);
        self
    }

    /// Set the maximum idle connections kept alive per host.
    ///
    /// Defaults to reqwest's built-in default (unlimited). Ignored when a
    /// client was supplied via [`with_http_client`](Self::with_http_client).
    #[must_use]
    pub fn with_pool_max_idle_per_host(mut self, n: usize) -> Self {
        self.http = self.http.with_pool_max_idle_per_host(n);
        self
    }

    /// Set how long an idle connection stays in the pool before being closed.
    ///
    /// Defaults to reqwest's built-in default (90s). Ignored when a client
    /// was supplied via [`with_http_client`](Self::with_http_client).
    #[must_use]
    pub fn with_pool_idle_timeout(mut self, d: Duration) -> Self {
        self.http = self.http.with_pool_idle_timeout(d);
        self
    }

    /// Set the OS-level TCP keepalive interval.
    ///
    /// Defaults to disabled (reqwest default). Ignored when a client was
    /// supplied via [`with_http_client`](Self::with_http_client).
    #[must_use]
    pub fn with_tcp_keepalive(mut self, d: Duration) -> Self {
        self.http = self.http.with_tcp_keepalive(d);
        self
    }

    /// Control whether `TCP_NODELAY` is set on connections.
    ///
    /// Defaults to `true` — SSE streaming benefits from disabling Nagle's
    /// algorithm. Pass `false` to re-enable it. Ignored when a client was
    /// supplied via [`with_http_client`](Self::with_http_client).
    #[must_use]
    pub fn with_tcp_nodelay(mut self, enabled: bool) -> Self {
        self.http = self.http.with_tcp_nodelay(enabled);
        self
    }

    /// Build the client.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError`] if no API key was set.
    pub fn build(self) -> Result<GeminiClient, ApiError> {
        let api_key = self
            .api_key
            .ok_or_else(|| ApiError::auth_invalid_key("API key not provided"))?;
        let http = self.http.build()?;

        Ok(GeminiClient {
            http,
            api_key,
            base_url: self.base_url,
            model: std::sync::Mutex::new(self.model),
            include_thoughts: self.include_thoughts,
        })
    }
}

/// Build the JSON request body for the Gemini Generate Content API.
///
/// Unlike OpenAI/Anthropic, Gemini puts the model in the URL, not the
/// request body. Each [`Message`] is serialized via [`convert_message`].
///
/// `generationConfig` is injected only when it has something to carry:
/// `thinkingConfig.includeThoughts = true` when `include_thoughts` is set,
/// and/or `responseMimeType` + `responseJsonSchema` when `response_format`
/// is set. When neither applies, `generationConfig` is omitted entirely.
///
/// Tool-call constraint:
/// - When `response_format` is set, suppresses `tools`; `tool_constraint`
///   is ignored in that case.
/// - Otherwise, when `tool_constraint` is `Strict`, each
///   `functionDeclaration`'s `parameters` is tightened
///   (`additionalProperties: false`, full `required`) via [`convert_tools`].
///   No `toolConfig.functionCallingConfig` is injected — Strict constrains
///   the call's shape, not its selection.
fn build_request_body(
    messages: &[Message],
    system: Option<&str>,
    tools: Option<&[ToolSchema]>,
    response_format: Option<&crate::structured::ResponseFormat>,
    tool_constraint: &ToolConstraint,
    include_thoughts: bool,
) -> Value {
    let (non_system, effective_system) = super::fold_system_messages(messages, system);
    let contents: Vec<Value> = non_system.iter().map(|m| convert_message(m)).collect();

    let mut body = serde_json::json!({ "contents": contents });
    if let Some(obj) = body.as_object_mut() {
        if let Some(sys) = effective_system {
            obj.insert(
                "systemInstruction".into(),
                serde_json::json!({"parts": [{"text": sys}]}),
            );
        }

        if response_format.is_none()
            && let Some(tool_list) = tools.filter(|t| !t.is_empty())
        {
            let strict = matches!(tool_constraint, ToolConstraint::Strict);
            obj.insert(
                "tools".into(),
                serde_json::json!([{"functionDeclarations": convert_tools(tool_list, strict)}]),
            );
        }

        let mut generation_config = serde_json::Map::new();
        if include_thoughts {
            generation_config.insert(
                "thinkingConfig".into(),
                serde_json::json!({ "includeThoughts": true }),
            );
        }
        if let Some(rf) = response_format {
            generation_config.insert("responseMimeType".into(), "application/json".into());
            generation_config.insert("responseJsonSchema".into(), rf.schema.clone());
        }
        if !generation_config.is_empty() {
            obj.insert("generationConfig".into(), Value::Object(generation_config));
        }
    }

    body
}

/// The config error for grammar constraints on the Gemini API.
///
/// Gemini has no grammar-constrained tool decoding, so a requested
/// grammar is rejected loudly instead of silently downgraded to an
/// unconstrained request — a caller asking for structural guarantees
/// must not discover their absence from malformed tool calls downstream.
#[cfg(feature = "grammar")]
fn grammar_unsupported_error() -> ApiError {
    ApiError::config_validation(
        "the Gemini API has no grammar-constrained tool decoding; \
         use ToolConstraint::Strict or an OpenAI-compatible endpoint",
    )
}

/// The Gemini API's `responseJsonSchema` has no strict-mode switch — a
/// `strict` response format would be silently served non-strict, so it
/// is rejected loudly instead.
fn strict_unsupported_error(provider: &str) -> ApiError {
    ApiError::config_validation(format!(
        "the {provider} API cannot express response_format.strict; the \
         request would be served non-strict — use an OpenAI-compatible \
         endpoint or drop strict"
    ))
}

/// Convert a single framework [`Message`] into the Gemini JSON shape.
///
/// Gemini uses `role: "user"` / `role: "model"` (not "assistant") and
/// a `parts` array for content blocks. A tool result's `is_error` flag
/// is not forwarded: the `functionResponse` payload carries the output
/// text either way, and Gemini has no dedicated error channel for it —
/// a failed call's error text itself conveys the failure to the model.
fn convert_message(m: &Message) -> Value {
    // System messages are folded into the top-level `systemInstruction` field
    // by `build_request_body` before this function is reached, so the `System`
    // pattern below is defensive: if one ever reaches here, route it to `user`
    // so the text renders rather than being dropped silently.
    let role = match m.role {
        Role::User | Role::System => "user",
        Role::Assistant => "model",
    };
    let parts: Vec<Value> = m.parts.iter().filter_map(convert_part).collect();
    serde_json::json!({"role": role, "parts": parts})
}

/// Convert a single [`MessagePart`] into a Gemini part JSON object.
///
/// Returns `None` for image parts (not yet supported for Gemini).
fn convert_part(p: &MessagePart) -> Option<Value> {
    match p {
        MessagePart::Text { text } => Some(serde_json::json!({"text": text})),
        MessagePart::ToolCall { id, name, input } => {
            let mut fc = serde_json::Map::new();
            fc.insert("name".to_string(), serde_json::Value::String(name.clone()));
            fc.insert("args".to_string(), input.clone());
            if !id.is_empty() {
                fc.insert("id".to_string(), serde_json::Value::String(id.clone()));
            }
            Some(serde_json::json!({"functionCall": fc}))
        }
        MessagePart::ToolResult {
            call_id,
            name,
            output,
            ..
        } => {
            let mut fr = serde_json::Map::new();
            fr.insert("name".to_string(), serde_json::Value::String(name.clone()));
            if !call_id.is_empty() {
                fr.insert("id".to_string(), serde_json::Value::String(call_id.clone()));
            }
            fr.insert(
                "response".to_string(),
                serde_json::json!({"result": output.to_string()}),
            );
            Some(serde_json::json!({"functionResponse": fr}))
        }
        MessagePart::Image { .. } => None,
    }
}

/// Convert framework tool schemas into the Gemini `functionDeclarations`
/// array shape.
///
/// Each [`ToolSchema`] becomes a JSON object with `name`, `description`, and
/// `parameters` — the fields Gemini's function-calling API expects. When
/// `strict` is `true`, each `parameters` is first tightened (recursive
/// `additionalProperties: false` and full `required`) — Gemini has no native
/// per-function strict flag, so the tightening is the structural constraint
/// behind [`ToolConstraint::Strict`].
///
/// When structured output is active (`response_format` set), this function is not
/// called — [`build_request_body`] injects `generationConfig.responseJsonSchema`
/// instead, and `tools` is suppressed.
fn convert_tools(tools: &[ToolSchema], strict: bool) -> Vec<Value> {
    tools
        .iter()
        .map(|t| {
            let parameters = if strict {
                tighten_json_schema(&t.input_schema)
            } else {
                t.input_schema.clone()
            };
            serde_json::json!({
                "name": t.tool,
                "description": &t.description,
                "parameters": parameters,
            })
        })
        .collect()
}

use super::sse::SseReader;

impl SseReader {
    /// Extract the next SSE `data:` payload as parsed JSON.
    ///
    /// Returns `Ok(None)` at end-of-stream.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError`] if the underlying HTTP stream fails.
    async fn next_gemini_data(&mut self) -> Result<Option<Value>, ApiError> {
        loop {
            while let Some(line) = self.take_line()? {
                if line.is_empty() {
                    continue;
                }
                if let Some(data) = super::sse_data_payload(&line) {
                    match serde_json::from_str::<Value>(data) {
                        Ok(json) => return Ok(Some(json)),
                        Err(e) => {
                            tracing::warn!(
                                error = %e,
                                data_len = data.len(),
                                "failed to parse Gemini SSE data, skipping"
                            );
                        }
                    }
                }
            }
            if self.next_chunk().await?.is_none() {
                return Ok(None);
            }
        }
    }
}

/// Whether a content lane (text or thinking) currently has an open part.
///
/// Gemini interleaves regular text parts and reasoning (`thought: true`)
/// parts within a single chunk's `parts[]` array. [`StreamEmitter`] opens a
/// part for each lane with a [`PartStart`](StreamEvent::PartStart) on its
/// first non-empty fragment and closes it with a
/// [`PartStop`](StreamEvent::PartStop) when the lane switches or the stream
/// finishes. The two lanes are mutually exclusive — switching emits a
/// `PartStop` for the active lane first — so this enum tracks each lane's
/// open/closed state without a bare `bool`.
#[derive(Default)]
enum PartLane {
    /// No part is open for this lane.
    ///
    /// The default state before the stream delivers any content for the
    /// lane, and the state it returns to once a part has been closed.
    #[default]
    Closed,

    /// A part is open and accumulating deltas.
    ///
    /// Set when the first non-empty fragment opens the lane; cleared when
    /// [`extract_finish_reason`](StreamEmitter::extract_finish_reason) or a
    /// lane switch emits the matching
    /// [`PartStop`](StreamEvent::PartStop).
    Open,
}

/// How far the stream has progressed through its terminal sequence.
///
/// A Gemini stream terminates in two steps: a `finishReason` chunk (the
/// provider's terminal signal, processed by
/// [`extract_finish_reason`](StreamEmitter::extract_finish_reason)) and
/// then the [`MessageStop`](StreamEvent::MessageStop) that
/// [`finish`](StreamEmitter::finish) emits for it at stream end. A
/// stream that ends without a `finishReason` gets no `MessageStop` —
/// its absence is the truncation signal the handler acts on. Once both
/// steps are done the stage is [`Terminal`](Self::Terminal) and all
/// later terminal work is a no-op.
#[derive(Default)]
enum TerminalStage {
    /// No `finishReason` has been seen.
    ///
    /// The default state at the start of a stream.
    #[default]
    Pending,

    /// A `finishReason` chunk has been fully processed.
    ///
    /// Subsequent `finishReason` chunks (e.g. from proxies that re-emit)
    /// are no-ops.
    FinishReasonSeen,

    /// The `MessageStop` for a seen `finishReason` has been emitted.
    ///
    /// The only state from which no further terminal work is possible.
    Terminal,
}

/// Stateful translator that converts Gemini SSE chunks into
/// [`StreamEvent`]s.
///
/// Gemini's SSE format is simpler than Anthropic's: each `data:` line
/// is a complete JSON object with `candidates[0].content.parts[]` for
/// text/function-call data and `candidates[0].finishReason` for the
/// stop reason. Reasoning models (Gemini 2.5+) interleave thought parts
/// with regular parts in the same `parts[]` array, flagged by a
/// `thought: true` boolean on each thought part.
#[derive(Default)]
struct StreamEmitter {
    /// Whether [`StreamEvent::MessageStart`] has been emitted for the
    /// current stream.
    ///
    /// Gemini does not send a dedicated message-start event; the emitter
    /// synthesizes one on the first chunk (with empty `id` and `model`,
    /// since Gemini's streaming chunks don't carry them) and treats later
    /// chunks as content only.
    started: bool,

    /// The latest non-empty `usageMetadata` seen on any chunk.
    ///
    /// Gemini reports cumulative usage on every chunk, but the terminal
    /// `finishReason` chunk does not always carry it (proxies and
    /// gateways frequently split them). Latching the latest report lets
    /// the terminal [`MessageDelta`](StreamEvent::MessageDelta) attach
    /// usage even when the two arrive on different chunks.
    pending_usage: Option<Usage>,

    /// Whether the text content part is currently open.
    ///
    /// The emitter opens a text part with [`StreamEvent::PartStart`] on the
    /// first non-empty text fragment and tracks the open state so
    /// [`extract_finish_reason`](Self::extract_finish_reason) emits exactly
    /// one [`StreamEvent::PartStop`] to close it.
    text: PartLane,

    /// Whether the reasoning (thinking) content part is currently open.
    ///
    /// Reasoning models flag thought parts with `thought: true`. The emitter
    /// opens a thinking part on the first non-empty thought fragment and
    /// closes it in [`extract_finish_reason`](Self::extract_finish_reason),
    /// symmetric to the text lane.
    thinking: PartLane,

    /// Next tool-call index for multiple function calls in one response.
    ///
    /// Gemini can emit several `functionCall` parts in a single chunk.
    /// Each gets its own `PartStart` at an incrementing index so the
    /// accumulator can distinguish them.
    next_tool_index: usize,

    /// How far the stream has progressed through its terminal sequence.
    ///
    /// Tracks the terminal sequence — `finishReason` processing (by
    /// [`extract_finish_reason`](Self::extract_finish_reason)), then the
    /// [`StreamEvent::MessageStop`] emission for it (by
    /// [`finish`](Self::finish)) — as a single field.
    terminal: TerminalStage,

    /// A terminal error carried by a top-level `/error` chunk, if any.
    ///
    /// Gemini reports mid-stream failures as SSE chunks whose JSON carries
    /// an `error` object instead of candidates. Recorded here so
    /// [`finish`](Self::finish) terminates the stream with the error
    /// instead of completing it — without it, a consumer could not
    /// distinguish an errored stream from a truncated one. First error
    /// wins; later ones are ignored.
    error: Option<ApiError>,

    /// Buffered [`StreamEvent`]s waiting to be yielded to the consumer.
    ///
    /// All event-producing methods push onto this queue via
    /// [`push`](Self::push); the stream loop reads them back through
    /// [`drain`](Self::drain) after each chunk so events are yielded
    /// promptly rather than buffered until stream end.
    pending: Vec<StreamEvent>,
}

impl StreamEmitter {
    /// Process a single Gemini SSE JSON chunk into stream events.
    ///
    /// On the first call, emits [`MessageStart`](StreamEvent::MessageStart).
    /// Then delegates to the three extractors: [`extract_text`](Self::extract_text)
    /// for text deltas, [`extract_function_call`](Self::extract_function_call)
    /// for tool calls, and [`extract_finish_reason`](Self::extract_finish_reason)
    /// for the terminal stop signal. Events accumulate in the internal queue
    /// until [`drain`](Self::drain) is called. A chunk carrying a top-level
    /// `/error` object produces no events — it records the terminal error
    /// that [`finish`](Self::finish) surfaces.
    fn process_chunk(&mut self, json: &Value) {
        if json.get("error").is_some() {
            self.record_error(json);
            return;
        }
        if !self.started {
            self.started = true;
            self.push(StreamEvent::MessageStart(MessageStart {
                message: MessageMetadata {
                    id: String::new(),
                    role: "assistant".into(),
                    model: String::new(),
                },
            }));
        }

        self.note_usage(json);
        self.extract_parts_with_tools(json);
        self.extract_finish_reason(json);
    }

    /// Latch the chunk's `usageMetadata` when it carries a non-empty one.
    ///
    /// Reports are cumulative, so the latest non-empty report is the most
    /// complete; `extract_finish_reason` consumes the latch when it emits
    /// the terminal `MessageDelta`. Counts above `u32::MAX` saturate
    /// rather than read as zero.
    fn note_usage(&mut self, json: &Value) {
        let input = json
            .pointer("/usageMetadata/promptTokenCount")
            .and_then(Value::as_u64)
            .unwrap_or(0);
        let output = json
            .pointer("/usageMetadata/candidatesTokenCount")
            .and_then(Value::as_u64)
            .unwrap_or(0);
        let thoughts = json
            .pointer("/usageMetadata/thoughtsTokenCount")
            .and_then(Value::as_u64)
            .unwrap_or(0);
        let total_output = output.saturating_add(thoughts);
        if input > 0 || total_output > 0 {
            self.pending_usage = Some(Usage::new(
                u32::try_from(input).unwrap_or(u32::MAX),
                u32::try_from(total_output).unwrap_or(u32::MAX),
            ));
        }
    }

    /// Record the terminal error from a top-level `/error` chunk.
    ///
    /// Reads `/error/status`, `/error/code`, and `/error/message`
    /// (Gemini's error payload, e.g. `"UNAVAILABLE"` / `"The model is
    /// overloaded"`). Rate-limit family failures (HTTP codes 429/503/529
    /// or statuses `RESOURCE_EXHAUSTED`/`UNAVAILABLE`) become
    /// [`ApiError::RateLimit`] so the stream handler's rate-limit ladder
    /// — with its backoff and `Retry-After` handling — owns the
    /// response, mirroring the status-based classification of
    /// non-streaming requests. Everything else stays an
    /// [`ApiError::api`] recording. Missing fields fall back to generic
    /// wording so a malformed payload still terminates with an error
    /// rather than being dropped. The first error wins; later ones are
    /// ignored.
    fn record_error(&mut self, json: &Value) {
        if self.error.is_some() {
            return;
        }
        let status = json
            .pointer("/error/status")
            .and_then(Value::as_str)
            .unwrap_or("error");
        let message = json
            .pointer("/error/message")
            .and_then(Value::as_str)
            .unwrap_or("stream failed");
        let code = json.pointer("/error/code").and_then(Value::as_u64);
        let detail = format!("{status}: {message}");
        let rate_limited = code.is_some_and(|code| code == 429 || code == 503 || code == 529)
            || matches!(status, "RESOURCE_EXHAUSTED" | "UNAVAILABLE");
        self.error = Some(if rate_limited {
            ApiError::RateLimit {
                retry_after: None,
                message: detail,
            }
        } else {
            ApiError::api(detail)
        });
    }

    /// Extract text, thought, and tool-call parts from the chunk, preserving
    /// the original `content.parts` order.
    ///
    /// Gemini can interleave text, thought (`thought: true`), and
    /// `functionCall` parts within a single chunk. This method walks the
    /// parts array in order and routes each to its lane, closing the
    /// previous lane first when switching — at most one content lane is
    /// ever open, so a lane left open behind a switch could share its
    /// part index with a later tool call and make closing ambiguous.
    fn extract_parts_with_tools(&mut self, json: &Value) {
        let Some(parts) = json
            .pointer("/candidates/0/content/parts")
            .and_then(Value::as_array)
        else {
            return;
        };

        for part in parts {
            if part.get("functionCall").is_some() {
                self.handle_function_call(part);
                continue;
            }

            let Some(text) = part.get("text").and_then(Value::as_str) else {
                continue;
            };

            if text.is_empty() {
                continue;
            }

            let is_thought = part
                .get("thought")
                .and_then(Value::as_bool)
                .unwrap_or(false);

            if is_thought {
                if matches!(self.text, PartLane::Open) {
                    self.text = PartLane::Closed;
                    self.push(StreamEvent::PartStop {
                        index: Some(TEXT_PART_INDEX),
                    });
                }
                if matches!(self.thinking, PartLane::Closed) {
                    self.thinking = PartLane::Open;
                    self.push(StreamEvent::PartStart(PartStart {
                        index: THINKING_PART_INDEX,
                        part: None,
                    }));
                }
                self.push(StreamEvent::IndexedDelta(IndexedDelta {
                    index: THINKING_PART_INDEX,
                    delta: DeltaPart::Thinking {
                        text: text.to_string(),
                    },
                }));
            } else {
                if matches!(self.thinking, PartLane::Open) {
                    self.thinking = PartLane::Closed;
                    self.push(StreamEvent::PartStop {
                        index: Some(THINKING_PART_INDEX),
                    });
                }
                if matches!(self.text, PartLane::Closed) {
                    self.text = PartLane::Open;
                    self.push(StreamEvent::PartStart(PartStart {
                        index: TEXT_PART_INDEX,
                        part: Some(MessagePart::text("")),
                    }));
                }
                self.push(StreamEvent::IndexedDelta(IndexedDelta {
                    index: TEXT_PART_INDEX,
                    delta: DeltaPart::Text {
                        text: text.to_string(),
                    },
                }));
            }
        }
    }

    /// Handle a single `functionCall` part, emitting `PartStart`,
    /// `InputJson`, and `PartStop`.
    ///
    /// Called inline from [`extract_parts_with_tools`] so tool calls appear
    /// at their original position relative to text/thought parts. Each call
    /// gets its own incrementing index, and its `args` are normalized by
    /// [`normalize_function_args`] — the `PartStart` input and the emitted
    /// `InputJson` delta both carry the normalized object.
    fn handle_function_call(&mut self, part: &Value) {
        let Some(func_call) = part.get("functionCall") else {
            return;
        };
        let id = func_call
            .pointer("/id")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let name = func_call
            .pointer("/name")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let args = normalize_function_args(func_call);
        let args_str = serde_json::to_string(&args).unwrap_or_default();

        if matches!(self.thinking, PartLane::Open) {
            self.thinking = PartLane::Closed;
            self.push(StreamEvent::PartStop {
                index: Some(THINKING_PART_INDEX),
            });
        }
        if matches!(self.text, PartLane::Open) {
            self.text = PartLane::Closed;
            self.push(StreamEvent::PartStop {
                index: Some(TEXT_PART_INDEX),
            });
        }

        let idx = self.next_tool_index;
        self.next_tool_index = self.next_tool_index.saturating_add(1);

        self.push(StreamEvent::PartStart(PartStart {
            index: idx,
            part: Some(MessagePart::ToolCall {
                id,
                name,
                input: args,
            }),
        }));
        self.push(StreamEvent::IndexedDelta(IndexedDelta {
            index: idx,
            delta: DeltaPart::InputJson {
                partial_json: args_str,
            },
        }));
        self.push(StreamEvent::PartStop { index: Some(idx) });
    }

    /// Extract the finish reason from the chunk and emit stop events.
    ///
    /// Reads `candidates[0].finishReason` (e.g. `"STOP"`, `"MAX_TOKENS"`).
    /// When present, closes any open thinking part and text part with
    /// [`PartStop`](StreamEvent::PartStop), then emits a
    /// [`MessageDelta`](StreamEvent::MessageDelta) carrying the mapped
    /// [`StreamStopReason`]. No-op on a second `finishReason` chunk (the
    /// `terminal` stage guards against proxies/gateways that re-emit).
    fn extract_finish_reason(&mut self, json: &Value) {
        if matches!(
            self.terminal,
            TerminalStage::FinishReasonSeen | TerminalStage::Terminal
        ) {
            return;
        }
        let Some(reason) = json
            .pointer("/candidates/0/finishReason")
            .and_then(Value::as_str)
        else {
            return;
        };
        self.terminal = TerminalStage::FinishReasonSeen;
        let stop = match reason {
            "MAX_TOKENS" => StreamStopReason::MaxTokens,
            _ => StreamStopReason::EndTurn,
        };

        if matches!(self.thinking, PartLane::Open) {
            self.thinking = PartLane::Closed;
            self.push(StreamEvent::PartStop {
                index: Some(THINKING_PART_INDEX),
            });
        }

        if matches!(self.text, PartLane::Open) {
            self.text = PartLane::Closed;
            self.push(StreamEvent::PartStop {
                index: Some(TEXT_PART_INDEX),
            });
        }

        let usage = self.pending_usage.take();

        self.push(StreamEvent::MessageDelta(MessageDelta {
            delta: MessageDeltaPayload {
                stop_reason: Some(stop.to_api_str().into()),
            },
            usage,
        }));
    }

    /// Drain all pending events from the internal queue.
    ///
    /// Returns the accumulated [`StreamEvent`]s and clears the queue.
    /// Called by the stream loop after each chunk is processed, so events
    /// are yielded to the consumer promptly rather than buffered until the
    /// end of the stream.
    fn drain(&mut self) -> Vec<StreamEvent> {
        std::mem::take(&mut self.pending)
    }

    /// Finalize the stream, emitting the terminal
    /// [`MessageStop`](StreamEvent::MessageStop) if one was started.
    ///
    /// When an error chunk was recorded, terminates with that error and
    /// emits nothing further — no synthetic `MessageStop`, so the failure
    /// cannot masquerade as a clean stop. Otherwise drains any remaining
    /// pending events and appends the stop **only when a `finishReason`
    /// was seen**: Gemini's terminal signal is the `finishReason` chunk,
    /// and a stream that ends without one is truncated — the absence of
    /// the stop is what tells the handler so. Safe to call exactly once
    /// at the end of the stream; subsequent calls return an empty vec
    /// (the `terminal` stage guards against double-stop).
    ///
    /// # Errors
    ///
    /// Returns the recorded terminal error, if a top-level error chunk
    /// arrived during the stream.
    fn finish(&mut self) -> Result<Vec<StreamEvent>, ApiError> {
        if let Some(err) = self.error.take() {
            return Err(err);
        }
        let mut out = self.drain();
        let stop_pending = matches!(self.terminal, TerminalStage::FinishReasonSeen);
        if self.started && stop_pending {
            self.terminal = TerminalStage::Terminal;
            out.push(StreamEvent::MessageStop);
        }
        Ok(out)
    }

    /// Whether a terminal error chunk has been recorded.
    ///
    /// The stream loop checks this after each chunk to stop reading —
    /// Gemini may hold the errored connection open, and waiting for its
    /// EOF would delay the error the emitter already knows about.
    fn error_recorded(&self) -> bool {
        self.error.is_some()
    }

    /// Push an event onto the internal pending queue.
    ///
    /// Events are held until [`drain`](Self::drain) is called. This is the
    /// single write point — all extractors (`extract_text`,
    /// `extract_function_call`, `extract_finish_reason`) and the lifecycle
    /// methods (`process_chunk`, `finish`) funnel through here.
    fn push(&mut self, ev: StreamEvent) {
        self.pending.push(ev);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{Message, MessagePart, Role, ToolContent};

    #[tokio::test]
    async fn strict_response_format_is_rejected_loudly() {
        use crate::structured::{RequestOptions, ResponseFormat};
        let client = GeminiClient::builder()
            .with_api_key("k")
            .with_base_url("http://localhost:1".to_string())
            .build()
            .unwrap();
        let rf = ResponseFormat {
            name: "out".to_string(),
            schema: serde_json::json!({"type": "object"}),
            strict: true,
        };
        let err = client
            .create_message_with_options(
                &crate::api::StreamRequest::new(vec![]),
                RequestOptions::default().with_response_format(rf),
            )
            .await
            .expect_err("strict must fail fast, not be silently dropped");
        assert!(
            err.to_string().contains("strict"),
            "the error names the dropped field: {err}"
        );
        assert_eq!(
            err.code(),
            crate::api::error::ErrorCode::ConfigValidationError,
            "a semantic capability rejection classifies as a validation \
             failure, not a parse error"
        );
    }

    #[test]
    fn gemini_terminal_stage_starts_pending() {
        let em = StreamEmitter::default();
        assert!(
            matches!(em.terminal, TerminalStage::Pending),
            "terminal stage must start pending"
        );
        assert!(
            matches!(em.text, PartLane::Closed) && matches!(em.thinking, PartLane::Closed),
            "both content lanes must start closed"
        );
    }

    #[test]
    fn request_body_user_text() {
        let msgs = vec![Message::user("hello")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let contents = body["contents"].as_array().unwrap();
        assert_eq!(contents.len(), 1);
        assert_eq!(contents[0]["role"], "user");
        let parts = contents[0]["parts"].as_array().unwrap();
        assert_eq!(parts[0]["text"], "hello");
    }

    #[test]
    fn request_body_includes_system_instruction() {
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(
            &msgs,
            Some("be brief"),
            None,
            None,
            &ToolConstraint::None,
            false,
        );

        let sys = &body["systemInstruction"];
        assert!(sys.is_object());
        assert_eq!(sys["parts"][0]["text"], "be brief");
    }

    #[test]
    fn request_body_no_system_instruction_when_none() {
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);
        assert!(body.get("systemInstruction").is_none());
    }

    #[test]
    fn request_body_assistant_maps_to_model_role() {
        let msgs = vec![Message::new(
            Role::Assistant,
            vec![MessagePart::text("hello")],
        )];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);
        assert_eq!(body["contents"][0]["role"], "model");
    }

    #[test]
    fn request_body_user_role() {
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);
        assert_eq!(body["contents"][0]["role"], "user");
    }

    #[test]
    fn request_body_assistant_tool_call() {
        let msgs = vec![Message::new(
            Role::Assistant,
            vec![MessagePart::ToolCall {
                id: "call_1".into(),
                name: "echo".into(),
                input: serde_json::json!({"msg": "hi"}),
            }],
        )];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let parts = body["contents"][0]["parts"].as_array().unwrap();
        assert_eq!(parts[0]["functionCall"]["name"], "echo");
        assert_eq!(parts[0]["functionCall"]["id"], "call_1");
        assert_eq!(parts[0]["functionCall"]["args"]["msg"], "hi");
    }

    #[test]
    fn request_body_tool_result() {
        let msgs = vec![Message::new(
            Role::User,
            vec![MessagePart::ToolResult {
                call_id: "call_1".into(),
                name: "echo".into(),
                output: ToolContent::from_string("result text"),
                is_error: None,
            }],
        )];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let parts = body["contents"][0]["parts"].as_array().unwrap();
        assert_eq!(parts[0]["functionResponse"]["name"], "echo");
        assert_eq!(parts[0]["functionResponse"]["id"], "call_1");
        assert_eq!(
            parts[0]["functionResponse"]["response"]["result"],
            "result text"
        );
    }

    #[test]
    fn request_body_function_response_includes_name_and_id() {
        let msgs = vec![Message::new(
            Role::User,
            vec![MessagePart::ToolResult {
                call_id: "fc_99".into(),
                name: "search".into(),
                output: ToolContent::from_string("results here"),
                is_error: None,
            }],
        )];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let fr = &body["contents"][0]["parts"][0]["functionResponse"];
        assert_eq!(fr["name"], "search");
        assert_eq!(fr["id"], "fc_99");
        assert_eq!(fr["response"]["result"], "results here");
    }

    #[test]
    fn request_body_function_response_omits_id_when_empty() {
        let msgs = vec![Message::new(
            Role::User,
            vec![MessagePart::ToolResult {
                call_id: String::new(),
                name: "search".into(),
                output: ToolContent::from_string("ok"),
                is_error: None,
            }],
        )];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let fr = &body["contents"][0]["parts"][0]["functionResponse"];
        assert_eq!(fr["name"], "search");
        assert!(
            fr.get("id").is_none(),
            "id should be omitted when call_id is empty"
        );
    }

    #[test]
    fn request_body_function_call_omits_id_when_empty() {
        let msgs = vec![Message::new(
            Role::Assistant,
            vec![MessagePart::tool_call("", "search", serde_json::json!({}))],
        )];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let fc = &body["contents"][0]["parts"][0]["functionCall"];
        assert_eq!(fc["name"], "search");
        assert!(
            fc.get("id").is_none(),
            "id should be omitted when tool-call id is empty"
        );
    }

    #[test]
    fn request_body_includes_tools() {
        let msgs = vec![Message::user("hi")];
        let tools = vec![ToolSchema {
            tool: "search".into(),
            description: "Search the web".into(),
            input_schema: serde_json::json!({"type": "object"}),
        }];
        let body = build_request_body(
            &msgs,
            None,
            Some(&tools),
            None,
            &ToolConstraint::None,
            false,
        );

        let tools_arr = body["tools"].as_array().unwrap();
        assert_eq!(tools_arr.len(), 1);
        let decls = tools_arr[0]["functionDeclarations"].as_array().unwrap();
        assert_eq!(decls[0]["name"], "search");
        assert_eq!(decls[0]["description"], "Search the web");
        assert_eq!(decls[0]["parameters"]["type"], "object");
    }

    #[test]
    fn request_body_no_tools_when_none() {
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);
        assert!(body.get("tools").is_none());
    }

    #[test]
    fn request_body_multiple_messages() {
        let msgs = vec![
            Message::user("hello"),
            Message::new(Role::Assistant, vec![MessagePart::text("hi")]),
            Message::user("bye"),
        ];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let contents = body["contents"].as_array().unwrap();
        assert_eq!(contents.len(), 3);
        assert_eq!(contents[0]["role"], "user");
        assert_eq!(contents[1]["role"], "model");
        assert_eq!(contents[2]["role"], "user");
    }

    #[test]
    fn convert_tools_shape() {
        let tools = vec![ToolSchema {
            tool: "calc".into(),
            description: "Calculate".into(),
            input_schema: serde_json::json!({"type": "object"}),
        }];
        let out = convert_tools(&tools, false);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0]["name"], "calc");
        assert_eq!(out[0]["description"], "Calculate");
    }

    #[test]
    fn convert_message_text_only() {
        let m = Message::user("hello");
        let v = convert_message(&m);
        assert_eq!(v["role"], "user");
        assert_eq!(v["parts"][0]["text"], "hello");
    }

    #[test]
    fn convert_message_assistant_role() {
        let m = Message::new(Role::Assistant, vec![MessagePart::text("hi")]);
        let v = convert_message(&m);
        assert_eq!(v["role"], "model");
    }

    #[test]
    fn convert_message_skips_images() {
        let m = Message::new(
            Role::User,
            vec![
                MessagePart::text("look"),
                MessagePart::Image {
                    source: crate::message::ImageSource {
                        encoding: "base64".into(),
                        media_type: "image/png".into(),
                        data: String::new(),
                    },
                },
            ],
        );
        let v = convert_message(&m);
        let parts = v["parts"].as_array().unwrap();
        assert_eq!(parts.len(), 1); // only text, image filtered out
    }

    #[test]
    fn builder_requires_api_key() {
        let result = GeminiClient::builder().build();
        assert!(result.is_err());
    }

    #[test]
    fn builder_succeeds_with_key() {
        let client = GeminiClient::builder()
            .with_api_key("test-key")
            .build()
            .unwrap();
        assert_eq!(client.model(), DEFAULT_MODEL);
    }

    #[test]
    fn builder_custom_model() {
        let client = GeminiClient::builder()
            .with_api_key("test-key")
            .with_model("gemini-1.5-pro")
            .build()
            .unwrap();
        assert_eq!(client.model(), "gemini-1.5-pro");
    }

    #[test]
    fn builder_custom_base_url() {
        let client = GeminiClient::builder()
            .with_api_key("test-key")
            .with_base_url("https://custom.example.com")
            .with_model("gemini-pro")
            .build()
            .unwrap();
        assert_eq!(client.model(), "gemini-pro");
    }

    #[test]
    fn stream_url_does_not_expose_api_key() {
        let client = GeminiClient::builder()
            .with_api_key("secret-key-123")
            .build()
            .unwrap();
        let url = client.stream_url_for_model("gemini-2.0-flash");
        assert!(
            !url.contains("secret-key-123"),
            "API key must not appear in stream URL: {url}"
        );
        assert!(
            !url.contains("key="),
            "URL must not have key= query param: {url}"
        );
    }

    #[test]
    fn generate_url_does_not_expose_api_key() {
        let client = GeminiClient::builder()
            .with_api_key("secret-key-456")
            .build()
            .unwrap();
        let url = client.generate_url();
        assert!(
            !url.contains("secret-key-456"),
            "API key must not appear in generate URL: {url}"
        );
        assert!(
            !url.contains("key="),
            "URL must not have key= query param: {url}"
        );
    }

    #[test]
    fn emitter_first_chunk_emits_message_start() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "hi"}]}}]
        }));
        let events = em.drain();
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StreamEvent::MessageStart(_)))
        );
    }

    #[test]
    fn emitter_text_delta() {
        let mut em = StreamEmitter::default();
        em.started = true; // skip MessageStart
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "world"}]}}]
        }));
        let events = em.drain();
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StreamEvent::IndexedDelta(_)))
        );
    }

    #[test]
    fn emitter_empty_text_ignored() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": ""}]}}]
        }));
        let events = em.drain();
        // Only MessageStart would be here, but we set started=true so
        // no events at all for empty text.
        assert!(
            events
                .iter()
                .all(|e| !matches!(e, StreamEvent::IndexedDelta(_)))
        );
    }

    #[test]
    fn emitter_function_call() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"functionCall": {"name": "search", "args": {"q": "rust"}}}]}}]
        }));
        let events = em.drain();
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StreamEvent::PartStart(_)))
        );
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StreamEvent::IndexedDelta(_)))
        );
    }

    #[test]
    fn emitter_function_call_includes_id() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"functionCall": {"id": "fc_7", "name": "search", "args": {"q": "rust"}}}]}}]
        }));
        let events = em.drain();
        let start = events
            .iter()
            .find_map(|e| match e {
                StreamEvent::PartStart(ps) => Some(ps),
                _ => None,
            })
            .expect("PartStart");
        match &start.part {
            Some(MessagePart::ToolCall { id, name, .. }) => {
                assert_eq!(id, "fc_7");
                assert_eq!(name, "search");
            }
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn emitter_function_call_without_id_defaults_to_empty() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"functionCall": {"name": "search", "args": {}}}]}}]
        }));
        let events = em.drain();
        let start = events
            .iter()
            .find_map(|e| match e {
                StreamEvent::PartStart(ps) => Some(ps),
                _ => None,
            })
            .expect("PartStart");
        match &start.part {
            Some(MessagePart::ToolCall { id, .. }) => assert_eq!(id, ""),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn emitter_thought_part_routes_to_thinking_variant() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{
                        "text": "reasoning here",
                        "thought": true
                    }]
                }
            }]
        }));
        let events = em.drain();
        let delta = events
            .iter()
            .find_map(|e| match e {
                StreamEvent::IndexedDelta(d) => Some(d.clone()),
                _ => None,
            })
            .expect("expected at least one IndexedDelta");
        assert!(
            matches!(delta.delta, DeltaPart::Thinking { .. }),
            "thought:true part must route to Thinking, got {:?}",
            delta.delta
        );
        if let DeltaPart::Thinking { text } = delta.delta {
            assert_eq!(text, "reasoning here");
        }
    }

    #[test]
    fn emitter_thought_part_emits_part_start_at_thinking_index() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{
                        "text": "hmm",
                        "thought": true
                    }]
                }
            }]
        }));
        let events = em.drain();
        let start = events
            .iter()
            .find_map(|e| match e {
                StreamEvent::PartStart(p) => Some(p.clone()),
                _ => None,
            })
            .expect("expected a PartStart for the thinking lane");
        assert_eq!(
            start.index, THINKING_PART_INDEX,
            "thought part must open at the thinking index"
        );
    }

    #[test]
    fn emitter_thought_part_does_not_open_text_lane() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{
                        "text": "private reasoning",
                        "thought": true
                    }]
                }
            }]
        }));
        let events = em.drain();
        // No DeltaPart::Text event must appear for a thought:true part.
        assert!(
            !events.iter().any(|e| matches!(
                e,
                StreamEvent::IndexedDelta(IndexedDelta {
                    delta: DeltaPart::Text { .. },
                    ..
                })
            )),
            "thought:true part must not produce a Text delta"
        );
    }

    #[test]
    fn emitter_text_part_does_not_open_thinking_lane() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{
                        "text": "visible answer"
                    }]
                }
            }]
        }));
        let events = em.drain();
        assert!(
            !events.iter().any(|e| matches!(
                e,
                StreamEvent::IndexedDelta(IndexedDelta {
                    delta: DeltaPart::Thinking { .. },
                    ..
                })
            )),
            "thought field absent must not produce a Thinking delta"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                StreamEvent::IndexedDelta(IndexedDelta {
                    delta: DeltaPart::Text { .. },
                    ..
                })
            )),
            "plain text part must produce a Text delta"
        );
    }

    #[test]
    fn emitter_thought_and_text_parts_interleave() {
        // Gemini interleaves thought and text parts in the same parts[] array.
        // When the lane changes the emitter closes the previous lane with an
        // addressed PartStop before opening the next, keeping at most one
        // content lane open at any time.
        let mut em = StreamEmitter::default();
        em.started = true;

        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [
                        {"text": "step 1", "thought": true},
                        {"text": "answer", "thought": false}
                    ]
                }
            }]
        }));
        let events = em.drain();
        let deltas: Vec<&IndexedDelta> = events
            .iter()
            .filter_map(|e| match e {
                StreamEvent::IndexedDelta(d) => Some(d),
                _ => None,
            })
            .collect();
        assert_eq!(deltas.len(), 2);
        assert!(
            matches!(deltas[0].delta, DeltaPart::Thinking { ref text } if text == "step 1"),
            "first delta must be the thinking fragment, got {:?}",
            deltas[0].delta
        );
        assert_eq!(deltas[0].index, THINKING_PART_INDEX);
        assert!(
            matches!(deltas[1].delta, DeltaPart::Text { ref text } if text == "answer"),
            "second delta must be the text fragment, got {:?}",
            deltas[1].delta
        );
        assert_eq!(deltas[1].index, TEXT_PART_INDEX);
        // The lane switch between the two deltas must emit exactly one
        // PartStop for the thinking lane before the text PartStart.
        assert_eq!(
            events
                .iter()
                .filter(|e| matches!(e, StreamEvent::PartStop { .. }))
                .count(),
            1,
            "lane switch must close the thinking lane"
        );
    }

    #[test]
    fn emitter_text_to_thought_lane_switch_emits_part_stop() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "visible", "thought": false}]}
            }]
        }));
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "thinking…", "thought": true}]}
            }]
        }));
        let events = em.drain();
        assert_eq!(
            events
                .iter()
                .filter(|e| matches!(e, StreamEvent::PartStop { .. }))
                .count(),
            1,
            "lane switch must close the text lane"
        );
    }

    #[test]
    fn emitter_finish_closes_thinking_lane() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{"text": "thinking…", "thought": true}]
                }
            }]
        }));
        em.drain();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let events = em.drain();
        // The thinking lane was open; finish must close it with a PartStop.
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StreamEvent::PartStop { .. })),
            "finish must emit PartStop for the open thinking lane"
        );
    }

    #[test]
    fn request_body_includes_thinking_config_when_opted_in() {
        // Opt-in: includeThoughts injected only when the caller asked for it.
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, true);

        assert_eq!(
            body["generationConfig"]["thinkingConfig"]["includeThoughts"], true,
            "includeThoughts must be injected when include_thoughts=true"
        );
    }

    #[test]
    fn request_body_omits_thinking_config_by_default() {
        // Default: includeThoughts NOT injected (non-reasoning models reject
        // it with 400 INVALID_ARGUMENT). generationConfig should be absent
        // entirely when there's nothing else to put in it either.
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        assert!(
            body.get("generationConfig").is_none(),
            "generationConfig must be omitted when include_thoughts=false and no response_format"
        );
    }

    #[test]
    fn request_body_thinking_config_composes_with_response_format() {
        // Both thinkingConfig and responseJsonSchema land under generationConfig.
        let msgs = vec![Message::user("hi")];
        let rf = crate::structured::ResponseFormat::new(
            "result",
            serde_json::json!({"type": "object", "properties": {"x": {"type": "string"}}}),
        );
        let body = build_request_body(&msgs, None, None, Some(&rf), &ToolConstraint::None, true);

        assert_eq!(
            body["generationConfig"]["thinkingConfig"]["includeThoughts"],
            true
        );
        assert_eq!(
            body["generationConfig"]["responseMimeType"],
            "application/json"
        );
        assert_eq!(
            body["generationConfig"]["responseJsonSchema"],
            serde_json::json!({"type": "object", "properties": {"x": {"type": "string"}}})
        );
    }

    #[test]
    fn emitter_finish_reason_end_turn() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "hi"}]}}]
        }));
        em.drain();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let events = em.drain();
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StreamEvent::PartStop { .. }))
        );
        assert!(
            matches!(em.text, PartLane::Closed),
            "extract_finish_reason must close the text lane in state, not just emit PartStop"
        );
        let md = events
            .iter()
            .find(|e| matches!(e, StreamEvent::MessageDelta(_)));
        if let Some(StreamEvent::MessageDelta(d)) = md {
            assert_eq!(d.delta.stop_reason.as_deref(), Some("end_turn"));
        } else {
            panic!("expected MessageDelta");
        }
    }

    #[test]
    fn emitter_finish_reason_max_tokens() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "hi"}]}}]
        }));
        em.drain();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "MAX_TOKENS"}]
        }));
        let events = em.drain();
        let md = events
            .iter()
            .find(|e| matches!(e, StreamEvent::MessageDelta(_)));
        if let Some(StreamEvent::MessageDelta(d)) = md {
            assert_eq!(d.delta.stop_reason.as_deref(), Some("max_tokens"));
        } else {
            panic!("expected MessageDelta");
        }
    }

    #[test]
    fn emitter_duplicate_finish_reason_is_noop() {
        // A second finishReason chunk (e.g. from a proxy/gateway that re-emits)
        // must not produce duplicate PartStop / MessageDelta events.
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "hi"}]}}]
        }));
        em.drain();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let first = em.drain();
        let first_deltas = first
            .iter()
            .filter(|e| matches!(e, StreamEvent::MessageDelta(_)))
            .count();
        let first_stops = first
            .iter()
            .filter(|e| matches!(e, StreamEvent::PartStop { .. }))
            .count();

        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let second = em.drain();

        assert_eq!(first_deltas, 1, "first finishReason emits one MessageDelta");
        assert_eq!(first_stops, 1, "first finishReason emits one PartStop");
        assert!(
            second.is_empty(),
            "second finishReason must produce no events, got {second:?}"
        );
    }

    #[test]
    fn emitter_function_call_after_text_closes_text_lane() {
        // When a functionCall arrives after the text lane has been streaming,
        // the emitter must close the text lane with a PartStop before opening
        // the tool part. Both reuse TEXT_PART_INDEX; without the close the
        // accumulator would clobber the text buffer with tool state.
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "calling tool", "thought": false}]}
            }]
        }));
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{"functionCall": {"name": "search", "args": {"q": "rust"}}}]
                }
            }]
        }));
        let events = em.drain();

        // Exactly one PartStop for the text lane (between the text delta and
        // the tool PartStart).
        let stops = events
            .iter()
            .filter(|e| matches!(e, StreamEvent::PartStop { .. }))
            .count();
        assert_eq!(stops, 2, "text lane closed + tool part closed");

        // Ordering: TextDelta → PartStop → tool PartStart.
        let text_delta_idx = events
            .iter()
            .position(|e| {
                matches!(
                    e,
                    StreamEvent::IndexedDelta(IndexedDelta {
                        delta: DeltaPart::Text { .. },
                        ..
                    })
                )
            })
            .expect("Text delta present");
        let stop_idx = events
            .iter()
            .position(|e| matches!(e, StreamEvent::PartStop { .. }))
            .expect("PartStop present");
        let tool_start_idx = events
            .iter()
            .position(|e| {
                matches!(
                    e,
                    StreamEvent::PartStart(PartStart {
                        part: Some(MessagePart::ToolCall { .. }),
                        ..
                    })
                )
            })
            .expect("Tool PartStart present");
        assert!(text_delta_idx < stop_idx, "text delta before PartStop");
        assert!(stop_idx < tool_start_idx, "PartStop before tool PartStart");
    }

    #[test]
    fn emitter_function_call_at_nonzero_part_index() {
        // A functionCall may appear at parts[1] (or later) when Gemini
        // interleaves a thought part with a tool call in the same chunk.
        // The emitter must scan all parts, not just parts[0].
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [
                        {"text": "reasoning about the call", "thought": true},
                        {"functionCall": {"name": "search", "args": {"q": "rust"}}}
                    ]
                }
            }]
        }));
        let events = em.drain();
        assert!(
            events.iter().any(|e| matches!(
                e,
                StreamEvent::PartStart(PartStart {
                    part: Some(MessagePart::ToolCall { name, .. }),
                    ..
                }) if name == "search"
            )),
            "functionCall at parts[1] must be found and emitted"
        );
    }

    #[test]
    fn emitter_no_function_call_does_nothing() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [
                        {"text": "just text"},
                        {"text": "more text"}
                    ]
                }
            }]
        }));
        let events = em.drain();
        assert!(
            !events.iter().any(|e| matches!(
                e,
                StreamEvent::PartStart(PartStart {
                    part: Some(MessagePart::ToolCall { .. }),
                    ..
                })
            )),
            "no functionCall in any part must not emit a tool PartStart"
        );
    }

    #[test]
    fn emitter_finish_emits_no_stop_without_a_finish_reason() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.terminal = TerminalStage::Pending;

        let events = em.finish().expect("no recorded error");
        assert!(
            events
                .iter()
                .all(|e| !matches!(e, StreamEvent::MessageStop)),
            "a stream that ends without finishReason is truncated — no synthetic stop may dress it up"
        );
    }

    #[test]
    fn emitter_finish_noop_if_already_stopped() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.terminal = TerminalStage::Terminal;

        let events = em.finish().expect("no recorded error");
        assert!(events.is_empty());
    }

    #[test]
    fn gemini_error_chunk_terminates_with_error() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "partial"}]}}]
        }));
        em.process_chunk(&serde_json::json!({
            "error": {"code": 503, "message": "The model is overloaded", "status": "UNAVAILABLE"}
        }));
        assert!(
            em.error_recorded(),
            "a top-level error chunk must be recorded"
        );
        let drained = em.drain();
        assert!(
            drained
                .iter()
                .all(|e| !matches!(e, StreamEvent::MessageStop)),
            "no clean MessageStop may be emitted alongside the failure: {drained:?}"
        );
        let err = em
            .finish()
            .expect_err("finish must surface the recorded error");
        assert!(
            err.to_string().contains("UNAVAILABLE"),
            "the terminal error must name the provider's status: {err}"
        );
        assert!(
            err.to_string().contains("The model is overloaded"),
            "the terminal error must carry the provider's message: {err}"
        );
        assert!(
            matches!(err, ApiError::RateLimit { .. }),
            "a 503/UNAVAILABLE chunk is the SSE form of an overloaded status \
             and must classify as RateLimit"
        );
    }

    #[cfg(feature = "grammar")]
    #[tokio::test]
    async fn grammar_constraint_errors_loudly() {
        let client = GeminiClient::builder()
            .with_api_key("test")
            .build()
            .unwrap();
        let opts = crate::structured::RequestOptions::default().with_tool_constraint(
            crate::structured::ToolConstraint::Grammar(std::sync::Arc::new(
                crate::provider::grammar::JsonSchemaGrammar::from_schemas(&[]),
            )),
        );
        let mut stream =
            client.stream_messages_with_options(&crate::api::StreamRequest::new(vec![]), opts);
        let first = futures::StreamExt::next(&mut stream).await;
        assert!(
            matches!(&first, Some(Err(err)) if err.to_string().contains("grammar")),
            "a grammar constraint must be rejected, not silently downgraded: {first:?}"
        );
    }

    #[test]
    fn usage_from_an_earlier_chunk_survives_a_usageless_finish_chunk() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"text": "partial"}]}}],
            "usageMetadata": {
                "promptTokenCount": 25,
                "candidatesTokenCount": 7,
                "thoughtsTokenCount": 3
            }
        }));
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let events = em.drain();
        let usage = events.iter().find_map(|e| match e {
            StreamEvent::MessageDelta(MessageDelta { usage, .. }) => *usage,
            _ => None,
        });
        let usage = usage.expect("the terminal delta must carry usage");
        assert_eq!(usage.input_tokens, 25);
        assert_eq!(
            usage.output_tokens, 10,
            "candidatesTokenCount + thoughtsTokenCount, latched from the earlier chunk"
        );
    }

    #[test]
    fn gemini_rate_limit_error_chunk_classifies_as_rate_limit() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "error": {"code": 429, "message": "Resource exhausted", "status": "RESOURCE_EXHAUSTED"}
        }));
        let err = em
            .finish()
            .expect_err("finish must surface the recorded error");
        assert!(
            matches!(err, ApiError::RateLimit { .. }),
            "a 429/RESOURCE_EXHAUSTED chunk must classify as RateLimit"
        );
    }

    #[test]
    fn gemini_non_rate_limit_error_chunk_stays_a_provider_error() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "error": {"code": 400, "message": "API key not valid", "status": "INVALID_ARGUMENT"}
        }));
        let err = em
            .finish()
            .expect_err("finish must surface the recorded error");
        assert!(
            !matches!(err, ApiError::RateLimit { .. }),
            "non-rate-limit errors stay provider errors: {err}"
        );
    }

    #[test]
    fn emitter_finish_reason_does_not_suppress_message_stop() {
        // Regression: extract_finish_reason advances the terminal stage,
        // but finish() must still emit MessageStop. Previously both used the
        // same `finished` flag, causing finish() to skip MessageStop after
        // a finishReason chunk.
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        em.drain();
        assert!(matches!(em.terminal, TerminalStage::FinishReasonSeen));
        let events = em.finish().expect("no recorded error");
        assert!(
            events.iter().any(|e| matches!(e, StreamEvent::MessageStop)),
            "MessageStop must be emitted even after finishReason was processed"
        );
    }

    #[test]
    fn emitter_finish_reason_after_finish_advances_to_terminal() {
        // A finishReason arriving after a truncated finish() (no stop was
        // emitted) still emits its own MessageDelta and completes the
        // stream; a *second* such chunk must be a no-op once Terminal is
        // reached.
        let mut em = StreamEmitter::default();
        em.started = true;
        let empty = em.finish().expect("no recorded error");
        assert!(
            empty.is_empty(),
            "a truncated finish emits nothing — the missing stop is the truncation signal"
        );
        assert!(matches!(em.terminal, TerminalStage::Pending));

        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        assert!(
            matches!(em.terminal, TerminalStage::FinishReasonSeen),
            "a late finishReason after a truncated finish is still processed"
        );
        let late_events = em.drain();
        assert!(
            late_events
                .iter()
                .any(|e| matches!(e, StreamEvent::MessageDelta(_))),
            "the late finishReason still emits its MessageDelta"
        );

        let stop_events = em.finish().expect("no recorded error");
        assert!(
            stop_events
                .iter()
                .any(|e| matches!(e, StreamEvent::MessageStop)),
            "finish after the late finishReason must emit MessageStop"
        );
        assert!(matches!(em.terminal, TerminalStage::Terminal));

        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let duplicate_events = em.drain();
        assert!(
            duplicate_events.is_empty(),
            "a second late finishReason must be a no-op once Terminal is reached"
        );
    }

    #[test]
    fn sse_reader_take_line_extracts_newline() {
        let mut reader = SseReader {
            bytes: Box::pin(futures::stream::empty()),
            buf: "data: hello\n".into(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        assert_eq!(reader.take_line().unwrap().unwrap(), "data: hello");
        assert!(reader.buf.is_empty());
    }

    #[test]
    fn sse_reader_take_line_none_without_newline() {
        let mut reader = SseReader {
            bytes: Box::pin(futures::stream::empty()),
            buf: "partial".into(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        assert!(reader.take_line().unwrap().is_none());
    }

    #[test]
    fn sse_reader_take_line_multiple() {
        let mut reader = SseReader {
            bytes: Box::pin(futures::stream::empty()),
            buf: "line1\nline2\n".into(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        assert_eq!(reader.take_line().unwrap().unwrap(), "line1");
        assert_eq!(reader.take_line().unwrap().unwrap(), "line2");
    }

    #[test]
    fn sse_reader_take_line_trims_cr() {
        let mut reader = SseReader {
            bytes: Box::pin(futures::stream::empty()),
            buf: "data: hi\r\n".into(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        assert_eq!(reader.take_line().unwrap().unwrap(), "data: hi");
    }

    #[test]
    fn builder_timeouts_applied_on_build() {
        let client = GeminiClient::builder()
            .with_api_key("test-key")
            .with_timeout(Duration::from_mins(3))
            .with_connect_timeout(Duration::from_secs(15))
            .build();
        assert!(client.is_ok(), "build should succeed with valid timeouts");
    }

    #[test]
    fn builder_include_thoughts_defaults_false() {
        let client = GeminiClient::builder()
            .with_api_key("test-key")
            .build()
            .unwrap();
        assert!(
            !client.include_thoughts,
            "include_thoughts must default to false (non-reasoning models reject thinkingConfig)"
        );
    }

    #[test]
    fn builder_include_thoughts_true_propagates_to_client() {
        let client = GeminiClient::builder()
            .with_api_key("test-key")
            .with_include_thoughts(true)
            .build()
            .unwrap();
        assert!(
            client.include_thoughts,
            "include_thoughts(true) must propagate to the built client"
        );
    }

    #[tokio::test]
    async fn sse_reader_take_line_splits_on_newline() {
        let mut reader = SseReader {
            bytes: Box::pin(futures::stream::empty()),
            buf: "data: {\"candidates\":[]}\n\n".to_string().into_bytes(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        assert_eq!(
            reader.take_line().unwrap(),
            Some("data: {\"candidates\":[]}".to_string())
        );
        assert_eq!(reader.take_line().unwrap(), Some(String::new()));
        assert_eq!(reader.take_line().unwrap(), None);
    }

    #[tokio::test]
    async fn sse_reader_next_data_extracts_payload() {
        let chunk = "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hi\"}]}}]}\n\n";
        let stream =
            futures::stream::iter(vec![Ok::<bytes::Bytes, ApiError>(chunk.to_string().into())]);
        let mut reader = SseReader {
            bytes: Box::pin(stream),
            buf: Vec::new(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        let result = reader.next_gemini_data().await.unwrap();
        assert!(result.is_some());
        let json = result.unwrap();
        assert!(json["candidates"].is_array());
    }

    #[tokio::test]
    async fn sse_reader_next_data_malformed_returns_none() {
        let chunk = "data: not valid json\n\ndata: {\"ok\":true}\n\n";
        let stream =
            futures::stream::iter(vec![Ok::<bytes::Bytes, ApiError>(chunk.to_string().into())]);
        let mut reader = SseReader {
            bytes: Box::pin(stream),
            buf: Vec::new(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        // First call should skip malformed and return the valid one.
        let result = reader.next_gemini_data().await.unwrap();
        assert!(result.is_some());
        let json = result.unwrap();
        assert_eq!(json["ok"], true);
    }

    #[tokio::test]
    async fn sse_reader_buffer_overflow_returns_error() {
        let huge = "x".repeat(2 * 1024 * 1024);
        let stream = futures::stream::iter(vec![Ok::<bytes::Bytes, ApiError>(huge.into())]);
        let mut reader = super::SseReader {
            bytes: Box::pin(stream),
            buf: Vec::new(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        let result = reader.next_gemini_data().await;
        assert!(result.is_err(), "should error on buffer overflow");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("SSE buffer"),
            "error should mention SSE buffer: {err_msg}"
        );
    }

    #[test]
    fn max_response_body_is_ten_mb() {
        assert_eq!(super::super::MAX_RESPONSE_BODY, 10 * 1024 * 1024);
    }

    #[test]
    fn request_body_response_format_injects_generation_config() {
        let msgs = vec![Message::user("hi")];
        let rf = crate::structured::ResponseFormat::new(
            "result",
            serde_json::json!({"type": "object", "properties": {"x": {"type": "string"}}}),
        );
        let body = build_request_body(&msgs, None, None, Some(&rf), &ToolConstraint::None, false);

        assert_eq!(
            body["generationConfig"]["responseMimeType"],
            "application/json"
        );
        assert_eq!(
            body["generationConfig"]["responseJsonSchema"],
            serde_json::json!({"type": "object", "properties": {"x": {"type": "string"}}})
        );
    }

    #[test]
    fn request_body_generation_config_omitted_when_nothing_applies() {
        // Without response_format AND include_thoughts=false, generationConfig
        // has nothing to carry, so it must be absent entirely.
        let msgs = vec![Message::user("hi")];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        assert!(
            body.get("generationConfig").is_none(),
            "generationConfig must be omitted when there's nothing to put in it"
        );
    }

    #[test]
    fn request_body_response_format_suppresses_tools() {
        let msgs = vec![Message::user("hi")];
        let caller_tool = ToolSchema {
            tool: "read".into(),
            description: "Read".into(),
            input_schema: serde_json::json!({"type": "object"}),
        };
        let rf =
            crate::structured::ResponseFormat::new("result", serde_json::json!({"type": "object"}));
        let body = build_request_body(
            &msgs,
            None,
            Some(&[caller_tool]),
            Some(&rf),
            &ToolConstraint::None,
            false,
        );

        assert!(
            body.get("tools").is_none(),
            "tools should be suppressed when response_format is set"
        );
        assert!(body.get("generationConfig").is_some());
    }

    #[test]
    fn extract_structured_from_text_part() {
        let client = GeminiClient::builder()
            .with_api_key("test")
            .build()
            .unwrap();
        let message = Message::assistant(r#"{"tool": "write", "args": {}}"#);
        let value = client.extract_structured(&message);
        assert_eq!(value["tool"], "write");
    }

    #[test]
    fn extract_structured_prose_falls_back_to_string() {
        let client = GeminiClient::builder()
            .with_api_key("test")
            .build()
            .unwrap();
        let message = Message::assistant("I cannot produce that.");
        let value = client.extract_structured(&message);
        assert_eq!(value, serde_json::json!("I cannot produce that."));
    }

    #[test]
    fn build_response_maps_text_part_and_stop() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hello gemini"}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.message.role, Role::Assistant);
        assert_eq!(response.message.text_content(), "hello gemini");
        assert_eq!(response.stop_reason, StreamStopReason::EndTurn);
    }

    #[test]
    fn build_response_maps_function_call_part() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{
                        "functionCall": {"name": "search", "args": {"q": "rust"}}
                    }]
                },
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.message.parts.len(), 1);
        match &response.message.parts[0] {
            MessagePart::ToolCall { id, name, input } => {
                assert_eq!(id, "");
                assert_eq!(name, "search");
                assert_eq!(input, &serde_json::json!({"q": "rust"}));
            }
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_parses_function_call_id() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"functionCall": {"id": "fc_42", "name": "search", "args": {}}}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        match &response.message.parts[0] {
            MessagePart::ToolCall { id, name, .. } => {
                assert_eq!(id, "fc_42");
                assert_eq!(name, "search");
            }
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_function_call_without_id_defaults_to_empty() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"functionCall": {"name": "search", "args": {}}}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        match &response.message.parts[0] {
            MessagePart::ToolCall { id, .. } => assert_eq!(id, ""),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_handles_text_and_function_call_in_one_part() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{
                        "text": "Let me search",
                        "functionCall": {"name": "search", "args": {}}
                    }]
                },
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(
            response.message.parts.len(),
            2,
            "text + functionCall in one part should yield two MessageParts"
        );
        assert!(response.message.parts[0].is_text());
        assert!(response.message.parts[1].is_tool_call());
    }

    #[test]
    fn build_response_maps_max_tokens_finish_reason() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "truncated"}]},
                "finishReason": "MAX_TOKENS"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.stop_reason, StreamStopReason::MaxTokens);
    }

    #[test]
    fn build_response_safety_finish_reason_maps_to_end_turn() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "blocked"}]},
                "finishReason": "SAFETY"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.stop_reason, StreamStopReason::EndTurn);
    }

    #[test]
    fn build_response_missing_finish_reason_defaults_to_end_turn() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hi"}]}
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.stop_reason, StreamStopReason::EndTurn);
    }

    #[test]
    fn build_response_missing_candidates_yields_empty_message() {
        let raw = serde_json::json!({});
        let response = GeminiClient::build_response(&raw);
        assert!(response.message.parts.is_empty());
        assert_eq!(response.stop_reason, StreamStopReason::EndTurn);
    }

    #[test]
    fn build_response_extracts_usage() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hi"}]},
                "finishReason": "STOP"
            }],
            "usageMetadata": {
                "promptTokenCount": 25,
                "candidatesTokenCount": 10,
                "thoughtsTokenCount": 5
            }
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.usage.expect("usage").input_tokens, 25);
        assert_eq!(response.usage.expect("usage").output_tokens, 15);
    }

    #[test]
    fn build_response_usage_without_thoughts() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hi"}]},
                "finishReason": "STOP"
            }],
            "usageMetadata": {
                "promptTokenCount": 8,
                "candidatesTokenCount": 4
            }
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.usage.expect("usage").input_tokens, 8);
        assert_eq!(response.usage.expect("usage").output_tokens, 4);
    }

    #[test]
    fn build_response_missing_usage_is_none() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hi"}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert!(response.usage.is_none());
    }

    #[test]
    fn build_response_multiple_function_calls_across_parts() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [
                    {"functionCall": {"name": "first", "args": {}}},
                    {"functionCall": {"name": "second", "args": {"n": 2}}}
                ]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.message.parts.len(), 2);
        match &response.message.parts[0] {
            MessagePart::ToolCall { name, .. } => assert_eq!(name, "first"),
            other => panic!("expected ToolCall, got {other:?}"),
        }
        match &response.message.parts[1] {
            MessagePart::ToolCall { name, .. } => assert_eq!(name, "second"),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_function_call_missing_args_defaults_to_empty_object() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"functionCall": {"name": "search"}}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        match &response.message.parts[0] {
            MessagePart::ToolCall { input, .. } => {
                assert_eq!(input, &serde_json::json!({}));
            }
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_multiple_text_parts_preserve_order() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [
                    {"text": "hello"},
                    {"text": " world"}
                ]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.message.parts.len(), 2);
        assert_eq!(response.message.text_content(), "hello world");
    }

    #[test]
    fn build_response_partial_usage_with_only_input() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hi"}]},
                "finishReason": "STOP"
            }],
            "usageMetadata": {"promptTokenCount": 99}
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(response.usage.expect("usage").input_tokens, 99);
        assert_eq!(response.usage.expect("usage").output_tokens, 0);
    }

    #[test]
    fn gemini_strict_tightens_parameters() {
        let msgs = vec![Message::user("hi")];
        let tools = vec![ToolSchema {
            tool: "echo".into(),
            description: "Echo".into(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {"msg": {"type": "string"}}
            }),
        }];
        let body = build_request_body(
            &msgs,
            None,
            Some(&tools),
            None,
            &ToolConstraint::Strict,
            false,
        );

        let decls = body["tools"][0]["functionDeclarations"].as_array().unwrap();
        assert_eq!(decls.len(), 1);
        let params = &decls[0]["parameters"];
        assert_eq!(params["additionalProperties"], false);
        let required = params["required"].as_array().unwrap();
        assert_eq!(required.len(), 1);
        assert_eq!(required[0], "msg");
    }

    #[test]
    fn gemini_none_constraint_unchanged_shape() {
        // Default None: tools emitted as before (no tightening).
        let msgs = vec![Message::user("hi")];
        let tools = vec![ToolSchema {
            tool: "echo".into(),
            description: "Echo".into(),
            input_schema: serde_json::json!({"type": "object"}),
        }];
        let body = build_request_body(
            &msgs,
            None,
            Some(&tools),
            None,
            &ToolConstraint::None,
            false,
        );

        let decls = body["tools"][0]["functionDeclarations"].as_array().unwrap();
        assert_eq!(
            decls[0]["parameters"],
            serde_json::json!({"type": "object"})
        );
        assert!(decls[0]["parameters"].get("additionalProperties").is_none());
    }

    #[test]
    fn gemini_strict_suppressed_when_response_format_set() {
        // With response_format set, the generationConfig path runs, tools
        // are absent, no tightening.
        let msgs = vec![Message::user("hi")];
        let caller_tool = ToolSchema {
            tool: "read".into(),
            description: "Read".into(),
            input_schema: serde_json::json!({"type": "object"}),
        };
        let rf =
            crate::structured::ResponseFormat::new("result", serde_json::json!({"type": "object"}));
        let body = build_request_body(
            &msgs,
            None,
            Some(&[caller_tool]),
            Some(&rf),
            &ToolConstraint::Strict,
            false,
        );

        assert!(
            body.get("tools").is_none(),
            "tools must be suppressed when response_format is set"
        );
        assert!(body.get("generationConfig").is_some());
    }

    #[test]
    fn gemini_strict_does_not_emit_tool_config() {
        let msgs = vec![Message::user("hi")];
        let tools = vec![ToolSchema {
            tool: "echo".into(),
            description: "Echo".into(),
            input_schema: serde_json::json!({"type": "object"}),
        }];
        let body = build_request_body(
            &msgs,
            None,
            Some(&tools),
            None,
            &ToolConstraint::Strict,
            false,
        );

        assert!(
            body.get("toolConfig").is_none(),
            "toolConfig must not appear under Strict"
        );
    }

    fn system_role_msg(text: &str) -> Message {
        Message::new(Role::System, vec![MessagePart::text(text)])
    }

    #[test]
    fn request_body_system_role_folded_into_system_instruction() {
        // An inline Role::System message must NOT appear in `contents`; its
        // text must be folded into the top-level `systemInstruction` field.
        let msgs = vec![
            Message::user("hello"),
            system_role_msg("stay on task"),
            Message::assistant("working"),
        ];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);

        let contents = body["contents"].as_array().expect("contents is an array");
        assert_eq!(contents.len(), 2, "system-role message is filtered out");
        for c in contents {
            assert_ne!(
                c["role"].as_str().unwrap_or(""),
                "system",
                "no inline system-role entry should be emitted"
            );
        }
        let sys_text = body["systemInstruction"]["parts"][0]["text"]
            .as_str()
            .expect("systemInstruction.parts[0].text is a string");
        assert_eq!(sys_text, "stay on task");
    }

    #[test]
    fn request_body_system_role_merges_with_caller_system() {
        let msgs = vec![Message::user("hi"), system_role_msg("reminder")];
        let body = build_request_body(
            &msgs,
            Some("be brief"),
            None,
            None,
            &ToolConstraint::None,
            false,
        );

        let sys_text = body["systemInstruction"]["parts"][0]["text"]
            .as_str()
            .expect("systemInstruction.parts[0].text is a string");
        assert!(
            sys_text.starts_with("be brief"),
            "caller system prompt comes first: got {sys_text:?}"
        );
        assert!(
            sys_text.contains("reminder"),
            "folded text is appended: got {sys_text:?}"
        );
        assert!(
            sys_text.contains('\n'),
            "caller prompt and folded text are newline-separated: got {sys_text:?}"
        );
    }

    #[test]
    fn request_body_system_role_preserves_message_order() {
        let msgs = vec![
            Message::user("first"),
            system_role_msg("mid reminder"),
            Message::assistant("second"),
            Message::user("third"),
        ];
        let body = build_request_body(&msgs, None, None, None, &ToolConstraint::None, false);
        let contents = body["contents"].as_array().expect("contents is an array");
        let roles: Vec<&str> = contents
            .iter()
            .map(|c| c["role"].as_str().unwrap_or(""))
            .collect();
        assert_eq!(roles, vec!["user", "model", "user"]);
        assert_eq!(contents[0]["parts"][0]["text"], "first");
        assert_eq!(contents[2]["parts"][0]["text"], "third");
    }

    #[test]
    fn emitter_multiple_function_calls_per_chunk() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [
                        {"functionCall": {"name": "search", "args": {"q": "rust"}}},
                        {"functionCall": {"name": "write", "args": {"path": "/tmp"}}}
                    ]
                }
            }]
        }));
        let events = em.drain();

        let tool_starts: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                StreamEvent::PartStart(PartStart {
                    index,
                    part: Some(MessagePart::ToolCall { name, .. }),
                }) => Some((*index, name.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(
            tool_starts.len(),
            2,
            "both function calls must emit PartStart"
        );
        assert_eq!(tool_starts[0].1, "search");
        assert_eq!(tool_starts[1].1, "write");
        assert_ne!(
            tool_starts[0].0, tool_starts[1].0,
            "each tool call must get a distinct index"
        );

        let stops = events
            .iter()
            .filter(|e| matches!(e, StreamEvent::PartStop { .. }))
            .count();
        assert_eq!(stops, 2, "each tool call must emit its own PartStop");
    }

    #[test]
    fn emitter_mixed_text_tool_text_preserves_order() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [
                        {"text": "before"},
                        {"functionCall": {"name": "search", "args": {"q": "rust"}}},
                        {"text": "after"}
                    ]
                }
            }]
        }));
        let events = em.drain();

        let event_types: Vec<&str> = events
            .iter()
            .map(|e| match e {
                StreamEvent::PartStart(p) => {
                    if p.part
                        .as_ref()
                        .is_some_and(crate::message::MessagePart::is_tool_call)
                    {
                        "tool_start"
                    } else {
                        "text_start"
                    }
                }
                StreamEvent::IndexedDelta(IndexedDelta {
                    delta: DeltaPart::Text { .. },
                    ..
                }) => "text_delta",
                StreamEvent::IndexedDelta(IndexedDelta {
                    delta: DeltaPart::InputJson { .. },
                    ..
                }) => "json_delta",
                StreamEvent::PartStop { .. } => "stop",
                _ => "other",
            })
            .collect();

        let text_delta_pos = event_types
            .iter()
            .position(|t| *t == "text_delta")
            .expect("text delta");
        let tool_start_pos = event_types
            .iter()
            .position(|t| *t == "tool_start")
            .expect("tool start");
        let json_delta_pos = event_types
            .iter()
            .position(|t| *t == "json_delta")
            .expect("json delta");
        let second_text_pos = event_types
            .iter()
            .rposition(|t| *t == "text_delta")
            .expect("second text delta");

        assert!(
            text_delta_pos < tool_start_pos,
            "first text must come before tool call"
        );
        assert!(
            tool_start_pos < json_delta_pos,
            "tool PartStart must come before InputJson"
        );
        assert!(
            json_delta_pos < second_text_pos,
            "tool call must come before second text"
        );
    }

    #[test]
    fn emitter_finish_closes_open_tool_part() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [{"functionCall": {"name": "search", "args": {"q": "rust"}}}]
                }
            }]
        }));
        em.drain();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}]
        }));
        let events = em.drain();

        let has_message_delta = events.iter().any(|e| {
            matches!(
                e,
                StreamEvent::MessageDelta(MessageDelta {
                    delta: MessageDeltaPayload {
                        stop_reason: Some(_),
                    },
                    ..
                })
            )
        });
        assert!(has_message_delta, "finish must emit a MessageDelta");
    }

    #[test]
    fn emitter_finish_extracts_usage_metadata() {
        let mut em = StreamEmitter::default();
        em.process_chunk(&serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "hi"}]}
            }]
        }));
        em.drain();
        em.process_chunk(&serde_json::json!({
            "candidates": [{"finishReason": "STOP"}],
            "usageMetadata": {
                "promptTokenCount": 42,
                "candidatesTokenCount": 7,
                "thoughtsTokenCount": 5
            }
        }));
        let events = em.drain();

        let usage = events.iter().find_map(|e| match e {
            StreamEvent::MessageDelta(MessageDelta { usage: Some(u), .. }) => Some(*u),
            _ => None,
        });
        let usage = usage.expect("finish must include Usage from usageMetadata");
        assert_eq!(usage.input_tokens, 42);
        assert_eq!(usage.output_tokens, 12);
    }

    #[test]
    fn request_body_omits_tools_for_empty_slice() {
        let body = build_request_body(
            &[crate::message::Message::user("hi")],
            None,
            Some(&[]),
            None,
            &ToolConstraint::None,
            false,
        );
        assert!(
            body.get("tools").is_none(),
            "an empty tool list must be omitted, not sent as []; got {}",
            body.get("tools").unwrap_or(&serde_json::Value::Null)
        );
    }

    #[test]
    fn generate_url_has_no_double_slash_for_trailing_slash_base() {
        let bare = GeminiClient::builder()
            .with_api_key("k")
            .with_base_url("https://api.example.com")
            .build()
            .expect("client builds");
        let slashed = GeminiClient::builder()
            .with_api_key("k")
            .with_base_url("https://api.example.com/")
            .build()
            .expect("client builds");
        assert_eq!(
            slashed.generate_url(),
            bare.generate_url(),
            "a trailing-slash base URL must join to the same request URL as the bare one"
        );
    }

    #[test]
    fn build_response_excludes_thought_summaries() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {
                    "parts": [
                        {"text": "internal plan", "thought": true},
                        {"text": "answer"}
                    ]
                },
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(
            response.message.text_content(),
            "answer",
            "thought parts must not surface as visible text on the non-streaming path"
        );
    }

    #[tokio::test]
    async fn request_model_override_replaces_the_url_model_on_stream() {
        use futures::StreamExt;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = vec![0u8; 8192];
            let n = sock.read(&mut buf).await.unwrap();
            let head = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n";
            drop(sock.write_all(head.as_bytes()).await);
            String::from_utf8_lossy(&buf[..n]).into_owned()
        });

        let client = GeminiClient::builder()
            .with_api_key("k")
            .with_base_url(format!("http://{addr}"))
            .build()
            .unwrap();
        let options = crate::structured::RequestOptions::new().with_model("override-model");
        let mut stream =
            client.stream_messages_with_options(&crate::api::StreamRequest::new(vec![]), options);
        let _ = stream.next().await;
        let request = server.await.unwrap();
        let request_line = request.lines().next().unwrap_or_default();
        assert!(
            request_line.contains("/models/override-model:streamGenerateContent"),
            "the streaming URL must honor the per-request model override: {request_line}"
        );
    }

    #[tokio::test]
    async fn request_model_override_replaces_the_url_model() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = vec![0u8; 8192];
            let n = sock.read(&mut buf).await.unwrap();
            let head = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n";
            drop(sock.write_all(head.as_bytes()).await);
            String::from_utf8_lossy(&buf[..n]).into_owned()
        });

        let client = GeminiClient::builder()
            .with_api_key("k")
            .with_base_url(format!("http://{addr}"))
            .build()
            .unwrap();
        let options = crate::structured::RequestOptions::new().with_model("override-model");
        drop(
            client
                .create_message_with_options(&crate::api::StreamRequest::new(vec![]), options)
                .await,
        );
        let request = server.await.unwrap();
        let request_line = request.lines().next().unwrap_or_default();
        assert!(
            request_line.contains("/models/override-model:generateContent"),
            "Gemini carries the model in the URL; the override must replace it: {request_line}"
        );
    }

    #[tokio::test]
    async fn sse_data_line_without_space_is_parsed() {
        let chunk = "data:{\"candidates\":[]}\n\n";
        let stream =
            futures::stream::iter(vec![Ok::<bytes::Bytes, ApiError>(chunk.to_string().into())]);
        let mut reader = SseReader {
            bytes: Box::pin(stream),
            buf: Vec::new(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        let parsed = reader
            .next_gemini_data()
            .await
            .expect("reader must not err");
        assert!(
            parsed.is_some(),
            "spec-legal 'data:' line must yield the payload, not be skipped"
        );
    }

    #[test]
    fn emitter_function_call_without_args_defaults_to_empty_object() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"functionCall": {"name": "ping"}}]}}]
        }));
        let events = em.drain();
        let start = events
            .iter()
            .find_map(|e| match e {
                StreamEvent::PartStart(ps) => Some(ps),
                _ => None,
            })
            .expect("PartStart");
        match &start.part {
            Some(MessagePart::ToolCall { input, .. }) => assert_eq!(
                *input,
                serde_json::json!({}),
                "a parameterless function call must carry an empty object, matching build_response's default"
            ),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn emitter_function_call_without_args_emits_empty_object_json_delta() {
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&serde_json::json!({
            "candidates": [{"content": {"parts": [{"functionCall": {"name": "ping"}}]}}]
        }));
        let events = em.drain();
        let delta = events
            .iter()
            .find_map(|e| match e {
                StreamEvent::IndexedDelta(IndexedDelta {
                    delta: DeltaPart::InputJson { partial_json },
                    ..
                }) => Some(partial_json.clone()),
                _ => None,
            })
            .expect("InputJson delta");
        assert_eq!(
            delta, "{}",
            "tool input is assembled from these deltas; a parameterless call must serialize as an empty object, not null"
        );
    }

    #[test]
    fn function_call_with_explicit_null_args_normalizes_to_empty_object() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"functionCall": {"name": "ping", "args": null}}]},
                "finishReason": "STOP"
            }]
        });
        let non_streamed = GeminiClient::build_response(&raw);
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&raw);
        let streamed = em
            .drain()
            .iter()
            .find_map(|e| match e {
                StreamEvent::PartStart(PartStart {
                    part: Some(MessagePart::ToolCall { input, .. }),
                    ..
                }) => Some(input.clone()),
                _ => None,
            })
            .expect("PartStart");
        assert_eq!(
            streamed,
            serde_json::json!({}),
            "an explicit null means no arguments; the streamed path must hand executors an object"
        );
        match &non_streamed.message.parts[0] {
            MessagePart::ToolCall { input, .. } => assert_eq!(
                input,
                &serde_json::json!({}),
                "an explicit null must normalize to an empty object, matching the streamed path"
            ),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_non_object_args_pass_through_verbatim() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"functionCall": {"name": "ping", "args": [1, 2]}}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        let mut em = StreamEmitter::default();
        em.started = true;
        em.process_chunk(&raw);
        let streamed = em
            .drain()
            .iter()
            .find_map(|e| match e {
                StreamEvent::PartStart(PartStart {
                    part: Some(MessagePart::ToolCall { input, .. }),
                    ..
                }) => Some(input.clone()),
                _ => None,
            })
            .expect("PartStart");
        match &response.message.parts[0] {
            MessagePart::ToolCall { input, .. } => {
                assert_eq!(
                    input,
                    &serde_json::json!([1, 2]),
                    "only absent and null args normalize; a malformed non-object value stays visible"
                );
                assert_eq!(
                    &streamed, input,
                    "a non-object args value must pass through identically on both paths"
                );
            }
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn build_response_all_thought_parts_leave_text_empty() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "internal plan", "thought": true}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(
            response.message.text_content(),
            "",
            "a response made only of thought parts must yield no visible text"
        );
    }

    #[test]
    fn build_response_explicit_false_thought_flag_keeps_text() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "answer", "thought": false}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(
            response.message.text_content(),
            "answer",
            "an explicit thought: false marks visible text and must be kept"
        );
    }

    #[test]
    fn build_response_non_bool_thought_flag_keeps_text() {
        let raw = serde_json::json!({
            "candidates": [{
                "content": {"parts": [{"text": "answer", "thought": "yes"}]},
                "finishReason": "STOP"
            }]
        });
        let response = GeminiClient::build_response(&raw);
        assert_eq!(
            response.message.text_content(),
            "answer",
            "a non-boolean thought value is not a thought marker on the streaming path either"
        );
    }

    #[tokio::test]
    async fn bare_data_line_is_skipped_and_next_chunk_parses() {
        let chunk = "data:\n\ndata:{\"candidates\":[]}\n\n";
        let stream =
            futures::stream::iter(vec![Ok::<bytes::Bytes, ApiError>(chunk.to_string().into())]);
        let mut reader = SseReader {
            bytes: Box::pin(stream),
            buf: Vec::new(),
            #[cfg(feature = "openai")]
            done_marker_seen: false,
        };
        let parsed = reader
            .next_gemini_data()
            .await
            .expect("reader must not err");
        assert_eq!(
            parsed,
            Some(serde_json::json!({"candidates": []})),
            "an empty data payload is skipped inside the reader; the next chunk still parses"
        );
    }
}