open-agent-sdk 0.6.4

Production-ready Rust SDK for building AI agents with local OpenAI-compatible servers (LMStudio, Ollama, llama.cpp, vLLM). Features streaming, tools, hooks, retry logic, and comprehensive examples.
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
//! Core type definitions for the Open Agent SDK.
//!
//! This module contains the fundamental data structures used throughout the SDK for
//! configuring and interacting with AI agents. The type system is organized into three
//! main categories:
//!
//! # Agent Configuration
//!
//! - [`AgentOptions`]: Main configuration struct for agent behavior, model settings,
//!   and tool management
//! - [`AgentOptionsBuilder`]: Builder pattern implementation for constructing
//!   [`AgentOptions`] with validation
//!
//! # Message System
//!
//! The SDK uses a flexible message system that supports multi-modal content:
//!
//! - [`Message`]: Container for conversation messages with role and content
//! - [`MessageRole`]: Enum defining who sent the message (System, User, Assistant, Tool)
//! - [`ContentBlock`]: Enum for different content types (text, tool use, tool results)
//! - [`TextBlock`]: Simple text content
//! - [`ToolUseBlock`]: Represents an AI request to execute a tool
//! - [`ToolResultBlock`]: Contains the result of a tool execution
//!
//! # OpenAI API Compatibility
//!
//! The SDK communicates with LLM providers using the OpenAI-compatible API format.
//! These types handle serialization/deserialization for streaming responses:
//!
//! - [`OpenAIRequest`]: Request payload sent to the API
//! - [`OpenAIMessage`]: Message format for OpenAI API
//! - [`OpenAIChunk`]: Streaming response chunk from the API
//! - [`OpenAIToolCall`], [`OpenAIFunction`]: Tool calling format
//! - [`OpenAIDelta`], [`OpenAIToolCallDelta`]: Incremental updates in streaming
//!
//! # Architecture Overview
//!
//! The type system is designed to:
//!
//! 1. **Separate concerns**: Internal SDK types (Message, ContentBlock) are distinct
//!    from API wire format (OpenAI types), allowing flexibility in provider support
//! 2. **Enable streaming**: OpenAI types support incremental delta parsing for
//!    real-time responses
//! 3. **Support tool use**: First-class support for function calling with proper
//!    request/response tracking
//! 4. **Provide ergonomics**: Builder pattern and convenience constructors make
//!    common operations simple
//!
//! # Example
//!
//! ```no_run
//! use open_agent::{AgentOptions, Message};
//!
//! // Build agent configuration
//! let options = AgentOptions::builder()
//!     .model("qwen2.5-32b-instruct")
//!     .base_url("http://localhost:1234/v1")
//!     .system_prompt("You are a helpful assistant")
//!     .max_turns(10)
//!     .auto_execute_tools(true)
//!     .build()
//!     .expect("Valid configuration");
//!
//! // Create a user message
//! let msg = Message::user("Hello, how are you?");
//! ```

use crate::Error;
use crate::hooks::Hooks;
use crate::tools::Tool;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

// ============================================================================
// NEWTYPE WRAPPERS FOR COMPILE-TIME TYPE SAFETY
// ============================================================================

/// Validated model name with compile-time type safety.
///
/// This newtype wrapper ensures that model names are validated at construction time
/// rather than at runtime, catching invalid configurations earlier in development.
///
/// # Validation Rules
///
/// - Must not be empty
/// - Must not be only whitespace
///
/// # Example
///
/// ```
/// use open_agent::ModelName;
///
/// // Valid model name
/// let model = ModelName::new("qwen2.5-32b-instruct").unwrap();
/// assert_eq!(model.as_str(), "qwen2.5-32b-instruct");
///
/// // Invalid: empty string
/// assert!(ModelName::new("").is_err());
///
/// // Invalid: whitespace only
/// assert!(ModelName::new("   ").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ModelName(String);

impl ModelName {
    /// Creates a new `ModelName` after validation.
    ///
    /// # Errors
    ///
    /// Returns an error if the model name is empty or contains only whitespace.
    pub fn new(name: impl Into<String>) -> crate::Result<Self> {
        let name = name.into();
        let trimmed = name.trim();

        if trimmed.is_empty() {
            return Err(Error::invalid_input(
                "Model name cannot be empty or whitespace",
            ));
        }

        Ok(ModelName(name))
    }

    /// Returns the model name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `ModelName` and returns the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl std::fmt::Display for ModelName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Validated base URL with compile-time type safety.
///
/// This newtype wrapper ensures that base URLs are validated at construction time
/// rather than at runtime, catching invalid configurations earlier in development.
///
/// # Validation Rules
///
/// - Must not be empty
/// - Must start with `http://` or `https://`
///
/// # Example
///
/// ```
/// use open_agent::BaseUrl;
///
/// // Valid base URLs
/// let url = BaseUrl::new("http://localhost:1234/v1").unwrap();
/// assert_eq!(url.as_str(), "http://localhost:1234/v1");
///
/// let url = BaseUrl::new("https://api.openai.com/v1").unwrap();
/// assert_eq!(url.as_str(), "https://api.openai.com/v1");
///
/// // Invalid: no http/https prefix
/// assert!(BaseUrl::new("localhost:1234").is_err());
///
/// // Invalid: empty string
/// assert!(BaseUrl::new("").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BaseUrl(String);

impl BaseUrl {
    /// Creates a new `BaseUrl` after validation.
    ///
    /// # Errors
    ///
    /// Returns an error if the URL is empty or doesn't start with http:// or https://.
    pub fn new(url: impl Into<String>) -> crate::Result<Self> {
        let url = url.into();
        let trimmed = url.trim();

        if trimmed.is_empty() {
            return Err(Error::invalid_input("base_url cannot be empty"));
        }

        if !trimmed.starts_with("http://") && !trimmed.starts_with("https://") {
            return Err(Error::invalid_input(
                "base_url must start with http:// or https://",
            ));
        }

        Ok(BaseUrl(url))
    }

    /// Returns the base URL as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `BaseUrl` and returns the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl std::fmt::Display for BaseUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Validated temperature value with compile-time type safety.
///
/// This newtype wrapper ensures that temperature values are validated at construction time
/// rather than at runtime, catching invalid configurations earlier in development.
///
/// # Validation Rules
///
/// - Must be between 0.0 and 2.0 (inclusive)
///
/// # Example
///
/// ```
/// use open_agent::Temperature;
///
/// // Valid temperatures
/// let temp = Temperature::new(0.7).unwrap();
/// assert_eq!(temp.value(), 0.7);
///
/// let temp = Temperature::new(0.0).unwrap();
/// assert_eq!(temp.value(), 0.0);
///
/// let temp = Temperature::new(2.0).unwrap();
/// assert_eq!(temp.value(), 2.0);
///
/// // Invalid: below range
/// assert!(Temperature::new(-0.1).is_err());
///
/// // Invalid: above range
/// assert!(Temperature::new(2.1).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Temperature(f32);

impl Temperature {
    /// Creates a new `Temperature` after validation.
    ///
    /// # Errors
    ///
    /// Returns an error if the temperature is not between 0.0 and 2.0 (inclusive).
    pub fn new(temp: f32) -> crate::Result<Self> {
        if !(0.0..=2.0).contains(&temp) {
            return Err(Error::invalid_input(
                "temperature must be between 0.0 and 2.0",
            ));
        }

        Ok(Temperature(temp))
    }

    /// Returns the temperature value.
    pub fn value(&self) -> f32 {
        self.0
    }
}

impl std::fmt::Display for Temperature {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ============================================================================
// AGENT CONFIGURATION
// ============================================================================

/// Configuration options for an AI agent instance.
///
/// `AgentOptions` controls all aspects of agent behavior including model selection,
/// conversation management, tool usage, and lifecycle hooks. This struct should be
/// constructed using [`AgentOptions::builder()`] rather than direct instantiation
/// to ensure required fields are validated.
///
/// # Architecture
///
/// The options are organized into several functional areas:
///
/// - **Model Configuration**: `model`, `base_url`, `api_key`, `temperature`, `max_tokens`
/// - **Conversation Control**: `system_prompt`, `max_turns`, `timeout`
/// - **Tool Management**: `tools`, `auto_execute_tools`, `max_tool_iterations`
/// - **Lifecycle Hooks**: `hooks` for monitoring and interception
///
/// # Thread Safety
///
/// Tools are wrapped in `Arc<Tool>` to allow efficient cloning and sharing across
/// threads, as agents may need to be cloned for parallel processing.
///
/// # Examples
///
/// ```no_run
/// use open_agent::AgentOptions;
///
/// let options = AgentOptions::builder()
///     .model("qwen2.5-32b-instruct")
///     .base_url("http://localhost:1234/v1")
///     .system_prompt("You are a helpful coding assistant")
///     .max_turns(5)
///     .temperature(0.7)
///     .build()
///     .expect("Valid configuration");
/// ```
#[derive(Clone)]
pub struct AgentOptions {
    /// System prompt that defines the agent's behavior and personality.
    ///
    /// This is sent as the first message in the conversation to establish
    /// context and instructions. Can be empty if no system-level guidance
    /// is needed.
    system_prompt: String,

    /// Model identifier for the LLM to use (e.g., "qwen2.5-32b-instruct", "gpt-4").
    ///
    /// This must match a model available at the configured `base_url`.
    /// Different models have varying capabilities for tool use, context
    /// length, and response quality.
    model: String,

    /// OpenAI-compatible API endpoint URL (e.g., "http://localhost:1234/v1").
    ///
    /// The SDK communicates using the OpenAI chat completions API format,
    /// which is widely supported by local inference servers (LM Studio,
    /// llama.cpp, vLLM) and cloud providers.
    base_url: String,

    /// API authentication key for the provider.
    ///
    /// Many local servers don't require authentication, so the default
    /// "not-needed" is often sufficient. For cloud providers like OpenAI,
    /// set this to your actual API key.
    api_key: String,

    /// Maximum number of conversation turns (user message + assistant response = 1 turn).
    ///
    /// This limits how long a conversation can continue. In auto-execution mode
    /// with tools, this prevents infinite loops. Set to 1 for single-shot
    /// interactions or higher for multi-turn conversations.
    max_turns: u32,

    /// Maximum tokens the model should generate in a single response.
    ///
    /// `None` uses the provider's default. Lower values constrain response
    /// length, which can be useful for cost control or ensuring concise answers.
    /// Note this is separate from the model's context window size.
    max_tokens: Option<u32>,

    /// Sampling temperature for response generation (typically 0.0 to 2.0).
    ///
    /// - 0.0: Deterministic, always picks most likely tokens
    /// - 0.7: Balanced creativity and consistency (default)
    /// - 1.0+: More random and creative responses
    ///
    /// Lower temperatures are better for factual tasks, higher for creative ones.
    temperature: f32,

    /// HTTP request timeout in seconds.
    ///
    /// Maximum time to wait for the API to respond. Applies per API call,
    /// not to the entire conversation. Increase for slower models or when
    /// expecting long responses.
    timeout: u64,

    /// Tools available for the agent to use during conversations.
    ///
    /// Tools are wrapped in `Arc` for efficient cloning. When the agent
    /// receives a tool use request, it looks up the tool by name in this
    /// vector. Empty by default.
    tools: Vec<Arc<Tool>>,

    /// Whether to automatically execute tools and continue the conversation.
    ///
    /// - `true`: SDK automatically executes tool calls and sends results back
    ///   to the model, continuing until no more tools are requested
    /// - `false`: Tool calls are returned to the caller, who must manually
    ///   execute them and provide results
    ///
    /// Auto-execution is convenient but gives less control. Manual execution
    /// allows for approval workflows and selective tool access.
    auto_execute_tools: bool,

    /// Maximum iterations of tool execution in automatic mode.
    ///
    /// Prevents infinite loops where the agent continuously requests tools.
    /// Each tool execution attempt counts as one iteration. Only relevant
    /// when `auto_execute_tools` is true.
    max_tool_iterations: u32,

    /// Lifecycle hooks for observing and intercepting agent operations.
    ///
    /// Hooks allow you to inject custom logic at various points:
    /// - Before/after API requests
    /// - Tool execution interception
    /// - Response streaming callbacks
    ///
    /// Useful for logging, metrics, debugging, and implementing custom
    /// authorization logic.
    hooks: Hooks,
}

/// Custom Debug implementation to prevent sensitive data leakage.
///
/// We override the default Debug implementation because:
/// 1. The `api_key` field may contain sensitive credentials that shouldn't
///    appear in logs or error messages
/// 2. The `tools` vector contains Arc-wrapped closures that don't debug nicely,
///    so we show a count instead
///
/// This ensures that debug output is safe for logging while remaining useful
/// for troubleshooting.
impl std::fmt::Debug for AgentOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AgentOptions")
            .field("system_prompt", &self.system_prompt)
            .field("model", &self.model)
            .field("base_url", &self.base_url)
            // Mask API key to prevent credential leakage in logs
            .field("api_key", &"***")
            .field("max_turns", &self.max_turns)
            .field("max_tokens", &self.max_tokens)
            .field("temperature", &self.temperature)
            .field("timeout", &self.timeout)
            // Show tool count instead of trying to debug Arc<Tool> contents
            .field("tools", &format!("{} tools", self.tools.len()))
            .field("auto_execute_tools", &self.auto_execute_tools)
            .field("max_tool_iterations", &self.max_tool_iterations)
            .field("hooks", &self.hooks)
            .finish()
    }
}

/// Default values optimized for common single-turn use cases.
///
/// These defaults are chosen to:
/// - Require explicit configuration of critical fields (model, base_url)
/// - Provide safe, sensible defaults for optional fields
/// - Work with local inference servers that don't need authentication
impl Default for AgentOptions {
    fn default() -> Self {
        Self {
            // Empty string forces users to explicitly set context
            system_prompt: String::new(),
            // Empty string forces users to explicitly choose a model
            model: String::new(),
            // Empty string forces users to explicitly configure the endpoint
            base_url: String::new(),
            // Most local servers (LM Studio, llama.cpp) don't require auth
            api_key: "not-needed".to_string(),
            // Default to single-shot interaction; users opt into conversations
            max_turns: 1,
            // 4096 is a reasonable default that works with most models
            // while preventing runaway generation costs
            max_tokens: Some(4096),
            // 0.7 balances creativity with consistency for general use
            temperature: 0.7,
            // 60 seconds handles most requests without timing out prematurely
            timeout: 60,
            // No tools by default; users explicitly add capabilities
            tools: Vec::new(),
            // Manual tool execution by default for safety and control
            auto_execute_tools: false,
            // 5 iterations prevent infinite loops while allowing multi-step workflows
            max_tool_iterations: 5,
            // Empty hooks for no-op behavior
            hooks: Hooks::new(),
        }
    }
}

impl AgentOptions {
    /// Creates a new builder for constructing [`AgentOptions`].
    ///
    /// The builder pattern is used because:
    /// 1. Some fields are required (model, base_url) and need validation
    /// 2. Many fields have sensible defaults that can be overridden
    /// 3. The API is more discoverable and readable than struct initialization
    ///
    /// # Example
    ///
    /// ```no_run
    /// use open_agent::AgentOptions;
    ///
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .build()
    ///     .expect("Valid configuration");
    /// ```
    pub fn builder() -> AgentOptionsBuilder {
        AgentOptionsBuilder::default()
    }

    /// Returns the system prompt.
    pub fn system_prompt(&self) -> &str {
        &self.system_prompt
    }

    /// Returns the model identifier.
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Returns the base URL.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Returns the API key.
    pub fn api_key(&self) -> &str {
        &self.api_key
    }

    /// Returns the maximum number of conversation turns.
    pub fn max_turns(&self) -> u32 {
        self.max_turns
    }

    /// Returns the maximum tokens setting.
    pub fn max_tokens(&self) -> Option<u32> {
        self.max_tokens
    }

    /// Returns the sampling temperature.
    pub fn temperature(&self) -> f32 {
        self.temperature
    }

    /// Returns the HTTP timeout in seconds.
    pub fn timeout(&self) -> u64 {
        self.timeout
    }

    /// Returns a reference to the tools vector.
    pub fn tools(&self) -> &[Arc<Tool>] {
        &self.tools
    }

    /// Returns whether automatic tool execution is enabled.
    pub fn auto_execute_tools(&self) -> bool {
        self.auto_execute_tools
    }

    /// Returns the maximum tool execution iterations.
    pub fn max_tool_iterations(&self) -> u32 {
        self.max_tool_iterations
    }

    /// Returns a reference to the hooks configuration.
    pub fn hooks(&self) -> &Hooks {
        &self.hooks
    }
}

/// Builder for constructing [`AgentOptions`] with validation.
///
/// This builder implements the typestate pattern using `Option<T>` to track
/// which required fields have been set. The [`build()`](AgentOptionsBuilder::build)
/// method validates that all required fields are present before creating
/// the final [`AgentOptions`].
///
/// # Required Fields
///
/// - `model`: The LLM model identifier
/// - `base_url`: The API endpoint URL
///
/// All other fields have sensible defaults.
///
/// # Usage Pattern
///
/// 1. Call [`AgentOptions::builder()`]
/// 2. Chain method calls to set configuration
/// 3. Call [`build()`](AgentOptionsBuilder::build) to validate and create the final options
///
/// Methods return `self` for chaining, following the fluent interface pattern.
///
/// # Examples
///
/// ```no_run
/// use open_agent::AgentOptions;
/// use open_agent::Tool;
///
/// let calculator = Tool::new(
///     "calculate",
///     "Perform arithmetic",
///     serde_json::json!({
///         "type": "object",
///         "properties": {
///             "expression": {"type": "string"}
///         }
///     }),
///     |input| Box::pin(async move {
///         Ok(serde_json::json!({"result": 42}))
///     }),
/// );
///
/// let options = AgentOptions::builder()
///     .model("qwen2.5-32b-instruct")
///     .base_url("http://localhost:1234/v1")
///     .system_prompt("You are a helpful assistant")
///     .max_turns(10)
///     .temperature(0.8)
///     .tool(calculator)
///     .auto_execute_tools(true)
///     .build()
///     .expect("Valid configuration");
/// ```
#[derive(Default)]
pub struct AgentOptionsBuilder {
    /// Optional system prompt; defaults to empty if not set
    system_prompt: Option<String>,
    /// Required: model identifier
    model: Option<String>,
    /// Required: API endpoint URL
    base_url: Option<String>,
    /// Optional API key; defaults to "not-needed"
    api_key: Option<String>,
    /// Optional max turns; defaults to 1
    max_turns: Option<u32>,
    /// Optional max tokens; defaults to Some(4096)
    max_tokens: Option<u32>,
    /// Optional temperature; defaults to 0.7
    temperature: Option<f32>,
    /// Optional timeout; defaults to 60 seconds
    timeout: Option<u64>,
    /// Tools to provide; starts empty
    tools: Vec<Arc<Tool>>,
    /// Optional auto-execute flag; defaults to false
    auto_execute_tools: Option<bool>,
    /// Optional max iterations; defaults to 5
    max_tool_iterations: Option<u32>,
    /// Lifecycle hooks; defaults to empty
    hooks: Hooks,
}

/// Custom Debug implementation for builder to show minimal useful information.
///
/// Similar to [`AgentOptions`], we provide a simplified debug output that:
/// - Omits sensitive fields like API keys (not shown at all in builder)
/// - Shows tool count rather than tool details
/// - Focuses on the most important configuration fields
impl std::fmt::Debug for AgentOptionsBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AgentOptionsBuilder")
            .field("system_prompt", &self.system_prompt)
            .field("model", &self.model)
            .field("base_url", &self.base_url)
            .field("tools", &format!("{} tools", self.tools.len()))
            .finish()
    }
}

/// Builder methods for configuring agent options.
///
/// All methods follow the builder pattern: they consume `self`, update a field,
/// and return `self` for method chaining. The generic `impl Into<String>` parameters
/// allow passing `&str`, `String`, or any other type that converts to `String`.
impl AgentOptionsBuilder {
    /// Sets the system prompt that defines agent behavior.
    ///
    /// The system prompt is sent at the beginning of every conversation to
    /// establish context, personality, and instructions for the agent.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .system_prompt("You are a helpful coding assistant. Be concise.")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// Sets the model identifier (required).
    ///
    /// This must match a model available at your configured endpoint.
    /// Common examples: "qwen2.5-32b-instruct", "gpt-4", "claude-3-sonnet".
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("gpt-4")
    ///     .base_url("https://api.openai.com/v1")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Sets the API endpoint URL (required).
    ///
    /// Must be an OpenAI-compatible endpoint. Common values:
    /// - Local: "http://localhost:1234/v1" (LM Studio default)
    /// - OpenAI: <https://api.openai.com/v1>
    /// - Custom: Your inference server URL
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Sets the API key for authentication.
    ///
    /// Required for cloud providers like OpenAI. Most local servers don't
    /// need this - the default "not-needed" works fine.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("gpt-4")
    ///     .base_url("https://api.openai.com/v1")
    ///     .api_key("sk-...")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Sets the maximum number of conversation turns.
    ///
    /// One turn = user message + assistant response. Higher values enable
    /// longer conversations but may increase costs and latency.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .max_turns(10)  // Allow multi-turn conversation
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn max_turns(mut self, turns: u32) -> Self {
        self.max_turns = Some(turns);
        self
    }

    /// Sets the maximum tokens to generate per response.
    ///
    /// Constrains response length. Lower values reduce costs but may truncate
    /// responses. Higher values allow longer, more complete answers.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .max_tokens(1000)  // Limit to shorter responses
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn max_tokens(mut self, tokens: u32) -> Self {
        self.max_tokens = Some(tokens);
        self
    }

    /// Sets the sampling temperature for response generation.
    ///
    /// Controls randomness:
    /// - 0.0: Deterministic, always picks most likely tokens
    /// - 0.7: Balanced (default)
    /// - 1.0+: More creative/random
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .temperature(0.0)  // Deterministic for coding tasks
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn temperature(mut self, temp: f32) -> Self {
        self.temperature = Some(temp);
        self
    }

    /// Sets the HTTP request timeout in seconds.
    ///
    /// How long to wait for the API to respond. Increase for slower models
    /// or when expecting long responses.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .timeout(120)  // 2 minutes for complex tasks
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn timeout(mut self, timeout: u64) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Enables or disables automatic tool execution.
    ///
    /// When true, the SDK automatically executes tool calls and continues
    /// the conversation. When false, tool calls are returned for manual
    /// handling, allowing approval workflows.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .auto_execute_tools(true)  // Automatic execution
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn auto_execute_tools(mut self, auto: bool) -> Self {
        self.auto_execute_tools = Some(auto);
        self
    }

    /// Sets the maximum tool execution iterations in automatic mode.
    ///
    /// Prevents infinite loops where the agent continuously calls tools.
    /// Only relevant when `auto_execute_tools` is true.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .auto_execute_tools(true)
    ///     .max_tool_iterations(10)  // Allow up to 10 tool calls
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn max_tool_iterations(mut self, iterations: u32) -> Self {
        self.max_tool_iterations = Some(iterations);
        self
    }

    /// Adds a single tool to the agent's available tools.
    ///
    /// The tool is wrapped in `Arc` for efficient sharing. Can be called
    /// multiple times to add multiple tools.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// # use open_agent::Tool;
    /// let calculator = Tool::new(
    ///     "calculate",
    ///     "Evaluate a math expression",
    ///     serde_json::json!({"type": "object"}),
    ///     |input| Box::pin(async move { Ok(serde_json::json!({"result": 42})) }),
    /// );
    ///
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .tool(calculator)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn tool(mut self, tool: Tool) -> Self {
        self.tools.push(Arc::new(tool));
        self
    }

    /// Adds multiple tools at once to the agent's available tools.
    ///
    /// Convenience method for bulk tool addition. All tools are wrapped
    /// in `Arc` automatically.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// # use open_agent::Tool;
    /// let tools = vec![
    ///     Tool::new("add", "Add numbers", serde_json::json!({}),
    ///         |input| Box::pin(async move { Ok(serde_json::json!({})) })),
    ///     Tool::new("multiply", "Multiply numbers", serde_json::json!({}),
    ///         |input| Box::pin(async move { Ok(serde_json::json!({})) })),
    /// ];
    ///
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .tools(tools)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn tools(mut self, tools: Vec<Tool>) -> Self {
        self.tools.extend(tools.into_iter().map(Arc::new));
        self
    }

    /// Sets lifecycle hooks for monitoring and intercepting agent operations.
    ///
    /// Hooks allow custom logic at various points: before/after API calls,
    /// tool execution, response streaming, etc. Useful for logging, metrics,
    /// debugging, and custom authorization.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::{AgentOptions, Hooks, HookDecision};
    /// let hooks = Hooks::new()
    ///     .add_user_prompt_submit(|event| async move {
    ///         println!("User prompt: {}", event.prompt);
    ///         Some(HookDecision::continue_())
    ///     });
    ///
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .hooks(hooks)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn hooks(mut self, hooks: Hooks) -> Self {
        self.hooks = hooks;
        self
    }

    /// Validates configuration and builds the final [`AgentOptions`].
    ///
    /// This method performs validation to ensure required fields are set and
    /// applies default values for optional fields. Returns an error if
    /// validation fails.
    ///
    /// # Required Fields
    ///
    /// - `model`: Must be set or build() returns an error
    /// - `base_url`: Must be set or build() returns an error
    ///
    /// # Errors
    ///
    /// Returns a configuration error if any required field is missing.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use open_agent::AgentOptions;
    /// // Success - all required fields set
    /// let options = AgentOptions::builder()
    ///     .model("qwen2.5-32b-instruct")
    ///     .base_url("http://localhost:1234/v1")
    ///     .build()
    ///     .expect("Valid configuration");
    ///
    /// // Error - missing model
    /// let result = AgentOptions::builder()
    ///     .base_url("http://localhost:1234/v1")
    ///     .build();
    /// assert!(result.is_err());
    /// ```
    pub fn build(self) -> crate::Result<AgentOptions> {
        // Validate required fields - these must be explicitly set by the user
        // because they're fundamental to connecting to an LLM provider
        let model = self
            .model
            .ok_or_else(|| crate::Error::config("model is required"))?;

        let base_url = self
            .base_url
            .ok_or_else(|| crate::Error::config("base_url is required"))?;

        // Validate model is not empty or whitespace
        if model.trim().is_empty() {
            return Err(crate::Error::invalid_input(
                "model cannot be empty or whitespace",
            ));
        }

        // Validate base_url is not empty and has valid URL format
        if base_url.trim().is_empty() {
            return Err(crate::Error::invalid_input("base_url cannot be empty"));
        }
        // Check if URL has a valid scheme (http:// or https://)
        if !base_url.starts_with("http://") && !base_url.starts_with("https://") {
            return Err(crate::Error::invalid_input(
                "base_url must start with http:// or https://",
            ));
        }

        // Validate temperature is in valid range (0.0 to 2.0)
        let temperature = self.temperature.unwrap_or(0.7);
        if !(0.0..=2.0).contains(&temperature) {
            return Err(crate::Error::invalid_input(
                "temperature must be between 0.0 and 2.0",
            ));
        }

        // Validate max_tokens if set
        let max_tokens = self.max_tokens.or(Some(4096));
        if let Some(tokens) = max_tokens {
            if tokens == 0 {
                return Err(crate::Error::invalid_input(
                    "max_tokens must be greater than 0",
                ));
            }
        }

        // Construct the final options, applying defaults where values weren't set
        Ok(AgentOptions {
            // Empty system prompt is valid - not all use cases need one
            system_prompt: self.system_prompt.unwrap_or_default(),
            model,
            base_url,
            // Default API key works for most local servers
            api_key: self.api_key.unwrap_or_else(|| "not-needed".to_string()),
            // Default to single-turn for simplicity
            max_turns: self.max_turns.unwrap_or(1),
            max_tokens,
            temperature,
            // Conservative timeout that works for most requests
            timeout: self.timeout.unwrap_or(60),
            // Tools vector was built up during configuration, use as-is
            tools: self.tools,
            // Manual execution by default for safety and control
            auto_execute_tools: self.auto_execute_tools.unwrap_or(false),
            // Reasonable limit to prevent runaway tool loops
            max_tool_iterations: self.max_tool_iterations.unwrap_or(5),
            // Hooks were built up during configuration, use as-is
            hooks: self.hooks,
        })
    }
}

/// Identifies the sender/role of a message in the conversation.
///
/// This enum follows the standard chat completion role system used by most
/// LLM APIs. The role determines how the message is interpreted and processed.
///
/// # Serialization
///
/// Serializes to lowercase strings via serde (`"system"`, `"user"`, etc.)
/// to match OpenAI API format.
///
/// # Role Semantics
///
/// - [`System`](MessageRole::System): Establishes context, instructions, and behavior
/// - [`User`](MessageRole::User): Input from the human or calling application
/// - [`Assistant`](MessageRole::Assistant): Response from the AI model
/// - [`Tool`](MessageRole::Tool): Results from tool/function execution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MessageRole {
    /// System message that establishes agent behavior and context.
    ///
    /// Typically the first message in a conversation. Used for instructions,
    /// personality definition, and constraints that apply throughout the
    /// conversation.
    System,

    /// User message representing human or application input.
    ///
    /// The prompt or query that the agent should respond to. In multi-turn
    /// conversations, user messages alternate with assistant messages.
    User,

    /// Assistant message containing the AI model's response.
    ///
    /// Can include text, tool use requests, or both. When the model wants to
    /// call a tool, it includes ToolUseBlock content.
    Assistant,

    /// Tool result message containing function execution results.
    ///
    /// Sent back to the model after executing a requested tool. Contains the
    /// tool's output that the model can use in its next response.
    Tool,
}

/// Multi-modal content blocks that can appear in messages.
///
/// Messages are composed of one or more content blocks, allowing rich,
/// structured communication between the user, assistant, and tools.
///
/// # Serialization
///
/// Uses serde's "externally tagged" enum format with a `"type"` field:
/// ```json
/// {"type": "text", "text": "Hello"}
/// {"type": "tool_use", "id": "call_123", "name": "search", "input": {...}}
/// {"type": "tool_result", "tool_use_id": "call_123", "content": {...}}
/// ```
///
/// # Block Types
///
/// - [`Text`](ContentBlock::Text): Simple text content
/// - [`Image`](ContentBlock::Image): Image content (URL or base64)
/// - [`ToolUse`](ContentBlock::ToolUse): Request from model to execute a tool
/// - [`ToolResult`](ContentBlock::ToolResult): Result of tool execution
///
/// # Usage
///
/// Messages can contain multiple blocks. For example, a user message might
/// include text and an image, or an assistant message might include text
/// followed by a tool use request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// Text content block containing a string message.
    Text(TextBlock),

    /// Image content block for vision-capable models.
    Image(ImageBlock),

    /// Tool use request from the model to execute a function.
    ToolUse(ToolUseBlock),

    /// Tool execution result sent back to the model.
    ToolResult(ToolResultBlock),
}

/// Simple text content in a message.
///
/// The most common content type, representing plain text communication.
/// Both users and assistants primarily use text blocks for their messages.
///
/// # Example
///
/// ```
/// use open_agent::{TextBlock, ContentBlock};
///
/// let block = TextBlock::new("Hello, world!");
/// let content = ContentBlock::Text(block);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextBlock {
    /// The text content.
    pub text: String,
}

impl TextBlock {
    /// Creates a new text block from any string-like type.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::TextBlock;
    ///
    /// let block = TextBlock::new("Hello");
    /// assert_eq!(block.text, "Hello");
    /// ```
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into() }
    }
}

/// Tool use request from the AI model.
///
/// When the model determines it needs to call a tool/function, it returns
/// a ToolUseBlock specifying which tool to call and with what parameters.
/// The application must then execute the tool and return results via
/// [`ToolResultBlock`].
///
/// # Fields
///
/// - `id`: Unique identifier for this tool call, used to correlate results
/// - `name`: Name of the tool to execute (must match a registered tool)
/// - `input`: JSON parameters to pass to the tool
///
/// # Example
///
/// ```
/// use open_agent::{ToolUseBlock, ContentBlock};
/// use serde_json::json;
///
/// let block = ToolUseBlock::new(
///     "call_123",
///     "calculate",
///     json!({"expression": "2 + 2"})
/// );
/// assert_eq!(block.id(), "call_123");
/// assert_eq!(block.name(), "calculate");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolUseBlock {
    /// Unique identifier for this tool call.
    ///
    /// Generated by the model. Used to correlate the tool result back to
    /// this specific request, especially when multiple tools are called.
    id: String,

    /// Name of the tool to execute.
    ///
    /// Must match the name of a tool that was provided in the agent's
    /// configuration, otherwise execution will fail.
    name: String,

    /// JSON parameters to pass to the tool.
    ///
    /// The structure should match the tool's input schema. The tool's
    /// execution function receives this value as input.
    input: serde_json::Value,
}

impl ToolUseBlock {
    /// Creates a new tool use block.
    ///
    /// # Parameters
    ///
    /// - `id`: Unique identifier for this tool call
    /// - `name`: Name of the tool to execute
    /// - `input`: JSON parameters for the tool
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::ToolUseBlock;
    /// use serde_json::json;
    ///
    /// let block = ToolUseBlock::new(
    ///     "call_abc",
    ///     "search",
    ///     json!({"query": "Rust async programming"})
    /// );
    /// ```
    pub fn new(id: impl Into<String>, name: impl Into<String>, input: serde_json::Value) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            input,
        }
    }

    /// Returns the unique identifier for this tool call.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the name of the tool to execute.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the JSON parameters for the tool.
    pub fn input(&self) -> &serde_json::Value {
        &self.input
    }
}

/// Tool execution result sent back to the model.
///
/// After executing a tool requested via [`ToolUseBlock`], the application
/// creates a ToolResultBlock containing the tool's output and sends it back
/// to the model. The model then uses this information in its next response.
///
/// # Fields
///
/// - `tool_use_id`: Must match the `id` from the corresponding ToolUseBlock
/// - `content`: JSON result from the tool execution
///
/// # Example
///
/// ```
/// use open_agent::{ToolResultBlock, ContentBlock};
/// use serde_json::json;
///
/// let result = ToolResultBlock::new(
///     "call_123",
///     json!({"result": 4})
/// );
/// assert_eq!(result.tool_use_id(), "call_123");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResultBlock {
    /// ID of the tool use request this result corresponds to.
    ///
    /// Must match the `id` field from the ToolUseBlock that requested
    /// this tool execution. This correlation is essential for the model
    /// to understand which tool call produced which result.
    tool_use_id: String,

    /// JSON result from executing the tool.
    ///
    /// Contains the tool's output data. Can be any valid JSON structure -
    /// the model will interpret it based on the tool's description and
    /// output schema.
    content: serde_json::Value,
}

impl ToolResultBlock {
    /// Creates a new tool result block.
    ///
    /// # Parameters
    ///
    /// - `tool_use_id`: ID from the corresponding ToolUseBlock
    /// - `content`: JSON result from tool execution
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::ToolResultBlock;
    /// use serde_json::json;
    ///
    /// let result = ToolResultBlock::new(
    ///     "call_xyz",
    ///     json!({
    ///         "status": "success",
    ///         "data": {"temperature": 72}
    ///     })
    /// );
    /// ```
    pub fn new(tool_use_id: impl Into<String>, content: serde_json::Value) -> Self {
        Self {
            tool_use_id: tool_use_id.into(),
            content,
        }
    }

    /// Returns the ID of the tool use request this result corresponds to.
    pub fn tool_use_id(&self) -> &str {
        &self.tool_use_id
    }

    /// Returns the JSON result from executing the tool.
    pub fn content(&self) -> &serde_json::Value {
        &self.content
    }
}

/// Image detail level for vision API calls.
///
/// Controls the resolution and token cost of image processing.
///
/// # Token Costs Vary by Model ⚠️
///
/// **OpenAI Vision API** (reference values):
/// - `Low`: ~85 tokens (512x512 max resolution)
/// - `High`: Variable tokens based on image dimensions
/// - `Auto`: Model decides (balanced default)
///
/// **Local models** (llama.cpp, Ollama, vLLM):
/// - May have **completely different** token calculations
/// - Some models don't charge tokens for images at all
/// - The `ImageDetail` setting may be ignored entirely
///
/// **Recommendation:** Always benchmark your specific model to understand
/// actual token consumption. Do not rely on OpenAI's values for capacity planning
/// with local models.
///
/// # Examples
///
/// ```
/// use open_agent::ImageDetail;
///
/// let detail = ImageDetail::High;
/// assert_eq!(detail.to_string(), "high");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ImageDetail {
    /// Low resolution (512x512), fixed 85 tokens
    Low,
    /// High resolution, variable tokens based on dimensions
    High,
    /// Automatic selection (default)
    #[default]
    Auto,
}

impl std::fmt::Display for ImageDetail {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImageDetail::Low => write!(f, "low"),
            ImageDetail::High => write!(f, "high"),
            ImageDetail::Auto => write!(f, "auto"),
        }
    }
}

/// Image content block for vision-capable models.
///
/// Supports both URL-based images and base64-encoded images.
///
/// # Examples
///
/// ```
/// use open_agent::{ImageBlock, ImageDetail};
///
/// // From URL
/// let image = ImageBlock::from_url("https://example.com/image.jpg")?;
///
/// // From base64 (use properly formatted base64)
/// let image = ImageBlock::from_base64("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "image/png")?;
///
/// // With detail level
/// let image = ImageBlock::from_url("https://example.com/image.jpg")?
///     .with_detail(ImageDetail::High);
/// # Ok::<(), open_agent::Error>(())
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageBlock {
    url: String,
    #[serde(default)]
    detail: ImageDetail,
}

impl ImageBlock {
    /// Creates a new image block from a URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The image URL (must be HTTP, HTTPS, or data URI)
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if:
    /// - URL is empty
    /// - URL contains control characters (newline, tab, null, etc.)
    /// - URL scheme is not `http://`, `https://`, or `data:`
    /// - Data URI is malformed (missing MIME type or base64 encoding)
    /// - Data URI base64 portion has invalid characters, length, or padding
    ///
    /// # Warnings
    ///
    /// - Logs a warning to stderr if URL exceeds 2000 characters
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::ImageBlock;
    ///
    /// let image = ImageBlock::from_url("https://example.com/cat.jpg")?;
    /// assert_eq!(image.url(), "https://example.com/cat.jpg");
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    pub fn from_url(url: impl Into<String>) -> crate::Result<Self> {
        let url = url.into();

        // Validate URL is not empty
        if url.is_empty() {
            return Err(crate::Error::invalid_input("Image URL cannot be empty"));
        }

        // Check for control characters in URL
        if url.contains(char::is_control) {
            return Err(crate::Error::invalid_input(
                "Image URL contains invalid control characters",
            ));
        }

        // Warn about very long URLs (>2000 chars)
        if url.len() > 2000 {
            eprintln!(
                "WARNING: Very long image URL ({} chars). \
                 Some APIs may have URL length limits.",
                url.len()
            );
        }

        // Validate URL scheme
        if url.starts_with("http://") || url.starts_with("https://") {
            // Valid HTTP/HTTPS URL
            Ok(Self {
                url,
                detail: ImageDetail::default(),
            })
        } else if let Some(mime_part) = url.strip_prefix("data:") {
            // Validate data URI format: data:MIME;base64,DATA
            if !url.contains(";base64,") {
                return Err(crate::Error::invalid_input(
                    "Data URI must be in format: data:image/TYPE;base64,DATA",
                ));
            }

            // Extract MIME type from data:MIME;base64,DATA
            let mime_type = if let Some(semicolon_pos) = mime_part.find(';') {
                &mime_part[..semicolon_pos]
            } else {
                return Err(crate::Error::invalid_input(
                    "Malformed data URI: missing MIME type",
                ));
            };

            if mime_type.is_empty() || !mime_type.starts_with("image/") {
                return Err(crate::Error::invalid_input(
                    "Data URI MIME type must start with 'image/'",
                ));
            }

            // Extract and validate base64 data portion
            if let Some(base64_start_pos) = url.find(";base64,") {
                let base64_data = &url[base64_start_pos + 8..]; // Skip ";base64,"

                // Validate base64 data using same rules as from_base64()
                // Check data is not empty
                if base64_data.is_empty() {
                    return Err(crate::Error::invalid_input(
                        "Data URI base64 data cannot be empty",
                    ));
                }

                // Check character set
                if !base64_data
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
                {
                    return Err(crate::Error::invalid_input(
                        "Data URI base64 data contains invalid characters. Valid characters: A-Z, a-z, 0-9, +, /, =",
                    ));
                }

                // Check length (must be multiple of 4)
                if base64_data.len() % 4 != 0 {
                    return Err(crate::Error::invalid_input(
                        "Data URI base64 data has invalid length (must be multiple of 4)",
                    ));
                }

                // Validate padding
                let equals_count = base64_data.chars().filter(|c| *c == '=').count();
                if equals_count > 2 {
                    return Err(crate::Error::invalid_input(
                        "Data URI base64 data has invalid padding (max 2 '=' characters allowed)",
                    ));
                }
                // Padding must be at the end
                if equals_count > 0 {
                    let trimmed = base64_data.trim_end_matches('=');
                    if trimmed.len() + equals_count != base64_data.len() {
                        return Err(crate::Error::invalid_input(
                            "Data URI base64 padding characters must be at the end",
                        ));
                    }
                }
            }

            Ok(Self {
                url,
                detail: ImageDetail::default(),
            })
        } else {
            Err(crate::Error::invalid_input(
                "Image URL must start with http://, https://, or data:",
            ))
        }
    }

    /// Creates a new image block from base64-encoded data.
    ///
    /// # Arguments
    ///
    /// * `base64_data` - The base64-encoded image data
    /// * `mime_type` - The MIME type (e.g., "image/jpeg", "image/png")
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if:
    /// - Base64 data is empty
    /// - Base64 contains invalid characters (only A-Z, a-z, 0-9, +, /, = allowed)
    /// - Base64 length is not a multiple of 4
    /// - Base64 has invalid padding (more than 2 '=' characters or not at end)
    /// - MIME type is empty
    /// - MIME type does not start with "image/"
    /// - MIME type contains injection characters (;, \\n, \\r, ,)
    ///
    /// # Warnings
    ///
    /// - Logs a warning to stderr if base64 data exceeds 10MB (~7.5MB decoded)
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::ImageBlock;
    ///
    /// let base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
    /// let image = ImageBlock::from_base64(base64, "image/png")?;
    /// assert!(image.url().starts_with("data:image/png;base64,"));
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    pub fn from_base64(
        base64_data: impl AsRef<str>,
        mime_type: impl AsRef<str>,
    ) -> crate::Result<Self> {
        let data = base64_data.as_ref();
        let mime = mime_type.as_ref();

        // Validate base64 data is not empty
        if data.is_empty() {
            return Err(crate::Error::invalid_input(
                "Base64 image data cannot be empty",
            ));
        }

        // Validate base64 character set (alphanumeric + +/=)
        // This catches common errors like spaces, special characters, etc.
        if !data
            .chars()
            .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
        {
            return Err(crate::Error::invalid_input(
                "Base64 data contains invalid characters. Valid characters: A-Z, a-z, 0-9, +, /, =",
            ));
        }

        // Validate base64 padding (length must be multiple of 4)
        if data.len() % 4 != 0 {
            return Err(crate::Error::invalid_input(
                "Base64 data has invalid length (must be multiple of 4)",
            ));
        }

        // Validate padding characters only appear at the end (max 2)
        let equals_count = data.chars().filter(|c| *c == '=').count();
        if equals_count > 2 {
            return Err(crate::Error::invalid_input(
                "Base64 data has invalid padding (max 2 '=' characters allowed)",
            ));
        }
        if equals_count > 0 {
            // Padding must be at the end
            let trimmed = data.trim_end_matches('=');
            if trimmed.len() + equals_count != data.len() {
                return Err(crate::Error::invalid_input(
                    "Base64 padding characters must be at the end",
                ));
            }
        }

        // Validate MIME type is not empty
        if mime.is_empty() {
            return Err(crate::Error::invalid_input("MIME type cannot be empty"));
        }

        // Validate MIME type starts with "image/"
        if !mime.starts_with("image/") {
            return Err(crate::Error::invalid_input(
                "MIME type must start with 'image/' (e.g., 'image/png', 'image/jpeg')",
            ));
        }

        // Check for MIME type injection characters
        if mime.contains([';', ',', '\n', '\r']) {
            return Err(crate::Error::invalid_input(
                "MIME type contains invalid characters (;, \\n, \\r not allowed)",
            ));
        }

        // Warn about extremely large base64 data (>10MB)
        if data.len() > 10_000_000 {
            eprintln!(
                "WARNING: Very large base64 image data ({} chars, ~{:.1}MB). \
                 This may exceed API limits or cause performance issues.",
                data.len(),
                (data.len() as f64 * 0.75) / 1_000_000.0
            );
        }

        let url = format!("data:{};base64,{}", mime, data);
        Ok(Self {
            url,
            detail: ImageDetail::default(),
        })
    }

    /// Creates a new image block from a local file path.
    ///
    /// This is a convenience method that reads the file from disk, encodes it as
    /// base64, and creates an ImageBlock with a data URI. The MIME type is inferred
    /// from the file extension.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the image file on the local filesystem
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if:
    /// - File cannot be read
    /// - File extension is missing or unsupported
    /// - File is too large (>10MB warning)
    ///
    /// # Supported Formats
    ///
    /// - `.jpg`, `.jpeg` → `image/jpeg`
    /// - `.png` → `image/png`
    /// - `.gif` → `image/gif`
    /// - `.webp` → `image/webp`
    /// - `.bmp` → `image/bmp`
    /// - `.svg` → `image/svg+xml`
    ///
    /// # Example
    ///
    /// ```no_run
    /// use open_agent::ImageBlock;
    ///
    /// let image = ImageBlock::from_file_path("/path/to/photo.jpg")?;
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    ///
    /// # Security Note
    ///
    /// This method reads files from the local filesystem. Ensure the path comes from
    /// a trusted source to prevent unauthorized file access.
    pub fn from_file_path(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
        use base64::{Engine as _, engine::general_purpose};

        let path = path.as_ref();

        // Read file bytes
        let bytes = std::fs::read(path).map_err(|e| {
            crate::Error::invalid_input(format!(
                "Failed to read image file '{}': {}",
                path.display(),
                e
            ))
        })?;

        // Determine MIME type from file extension
        let mime_type = match path.extension().and_then(|e| e.to_str()) {
            Some("jpg") | Some("jpeg") => "image/jpeg",
            Some("png") => "image/png",
            Some("gif") => "image/gif",
            Some("webp") => "image/webp",
            Some("bmp") => "image/bmp",
            Some("svg") => "image/svg+xml",
            Some(ext) => {
                return Err(crate::Error::invalid_input(format!(
                    "Unsupported image file extension: .{}. Supported: jpg, jpeg, png, gif, webp, bmp, svg",
                    ext
                )));
            }
            None => {
                return Err(crate::Error::invalid_input(
                    "Image file path must have a file extension (e.g., .jpg, .png)",
                ));
            }
        };

        // Encode to base64
        let base64_data = general_purpose::STANDARD.encode(&bytes);

        // Use existing from_base64 method for validation
        Self::from_base64(&base64_data, mime_type)
    }

    /// Sets the image detail level.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{ImageBlock, ImageDetail};
    ///
    /// let image = ImageBlock::from_url("https://example.com/image.jpg")?
    ///     .with_detail(ImageDetail::High);
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    pub fn with_detail(mut self, detail: ImageDetail) -> Self {
        self.detail = detail;
        self
    }

    /// Returns the image URL (or data URI for base64 images).
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Returns the image detail level.
    pub fn detail(&self) -> ImageDetail {
        self.detail
    }
}

/// A complete message in a conversation.
///
/// Messages are the primary unit of communication in the agent system. Each
/// message has a role (who sent it) and content (what it contains). Content
/// is structured as a vector of blocks to support multi-modal communication.
///
/// # Structure
///
/// - `role`: Who sent the message ([`MessageRole`])
/// - `content`: What the message contains (one or more [`ContentBlock`]s)
///
/// # Message Patterns
///
/// ## Simple Text Message
/// ```
/// use open_agent::Message;
///
/// let msg = Message::user("What's the weather?");
/// ```
///
/// ## Assistant Response with Tool Call
/// ```
/// use open_agent::{Message, ContentBlock, TextBlock, ToolUseBlock};
/// use serde_json::json;
///
/// let msg = Message::assistant(vec![
///     ContentBlock::Text(TextBlock::new("Let me check that for you.")),
///     ContentBlock::ToolUse(ToolUseBlock::new(
///         "call_123",
///         "get_weather",
///         json!({"location": "San Francisco"})
///     ))
/// ]);
/// ```
///
/// ## Tool Result
/// ```
/// use open_agent::{Message, ContentBlock, ToolResultBlock};
/// use serde_json::json;
///
/// let msg = Message::user_with_blocks(vec![
///     ContentBlock::ToolResult(ToolResultBlock::new(
///         "call_123",
///         json!({"temp": 72, "conditions": "sunny"})
///     ))
/// ]);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// The role/sender of this message.
    pub role: MessageRole,

    /// The content blocks that make up this message.
    ///
    /// A message can contain multiple blocks of different types. For example,
    /// an assistant message might have both text and tool use blocks.
    pub content: Vec<ContentBlock>,
}

impl Message {
    /// Creates a new message with the specified role and content.
    ///
    /// This is the most general constructor. For convenience, use the
    /// role-specific constructors like [`user()`](Message::user),
    /// [`assistant()`](Message::assistant), etc.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{Message, MessageRole, ContentBlock, TextBlock};
    ///
    /// let msg = Message::new(
    ///     MessageRole::User,
    ///     vec![ContentBlock::Text(TextBlock::new("Hello"))]
    /// );
    /// ```
    pub fn new(role: MessageRole, content: Vec<ContentBlock>) -> Self {
        Self { role, content }
    }

    /// Creates a user message with simple text content.
    ///
    /// This is the most common way to create user messages. For more complex
    /// content with multiple blocks, use [`user_with_blocks()`](Message::user_with_blocks).
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::Message;
    ///
    /// let msg = Message::user("What is 2+2?");
    /// ```
    pub fn user(text: impl Into<String>) -> Self {
        Self {
            role: MessageRole::User,
            content: vec![ContentBlock::Text(TextBlock::new(text))],
        }
    }

    /// Creates an assistant message with the specified content blocks.
    ///
    /// Assistant messages often contain multiple content blocks (text + tool use).
    /// This method takes a vector of blocks for maximum flexibility.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{Message, ContentBlock, TextBlock};
    ///
    /// let msg = Message::assistant(vec![
    ///     ContentBlock::Text(TextBlock::new("The answer is 4"))
    /// ]);
    /// ```
    pub fn assistant(content: Vec<ContentBlock>) -> Self {
        Self {
            role: MessageRole::Assistant,
            content,
        }
    }

    /// Creates a system message with simple text content.
    ///
    /// System messages establish the agent's behavior and context. They're
    /// typically sent at the start of a conversation.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::Message;
    ///
    /// let msg = Message::system("You are a helpful assistant. Be concise.");
    /// ```
    pub fn system(text: impl Into<String>) -> Self {
        Self {
            role: MessageRole::System,
            content: vec![ContentBlock::Text(TextBlock::new(text))],
        }
    }

    /// Creates a user message with custom content blocks.
    ///
    /// Use this when you need to send structured content beyond simple text,
    /// such as tool results. For simple text messages, prefer
    /// [`user()`](Message::user).
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{Message, ContentBlock, ToolResultBlock};
    /// use serde_json::json;
    ///
    /// let msg = Message::user_with_blocks(vec![
    ///     ContentBlock::ToolResult(ToolResultBlock::new(
    ///         "call_123",
    ///         json!({"result": "success"})
    ///     ))
    /// ]);
    /// ```
    pub fn user_with_blocks(content: Vec<ContentBlock>) -> Self {
        Self {
            role: MessageRole::User,
            content,
        }
    }

    /// Creates a user message with text and an image from a URL.
    ///
    /// This is a convenience method for the common pattern of sending text with
    /// an image. The image uses `ImageDetail::Auto` by default. For more control
    /// over detail level, use [`user_with_image_detail()`](Message::user_with_image_detail).
    ///
    /// # Arguments
    ///
    /// * `text` - The text prompt
    /// * `image_url` - URL of the image (http/https or data URI)
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if the image URL is invalid (empty, wrong scheme, etc.)
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::Message;
    ///
    /// let msg = Message::user_with_image(
    ///     "What's in this image?",
    ///     "https://example.com/photo.jpg"
    /// )?;
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    pub fn user_with_image(
        text: impl Into<String>,
        image_url: impl Into<String>,
    ) -> crate::Result<Self> {
        Ok(Self {
            role: MessageRole::User,
            content: vec![
                ContentBlock::Text(TextBlock::new(text)),
                ContentBlock::Image(ImageBlock::from_url(image_url)?),
            ],
        })
    }

    /// Creates a user message with text and an image with specified detail level.
    ///
    /// Use this when you need control over the image detail level for token cost
    /// management. On OpenAI's Vision API: `ImageDetail::Low` uses ~85 tokens,
    /// `ImageDetail::High` uses more tokens based on image dimensions, and
    /// `ImageDetail::Auto` lets the model decide. Local models may have very different token costs.
    ///
    /// # Arguments
    ///
    /// * `text` - The text prompt
    /// * `image_url` - URL of the image (http/https or data URI)
    /// * `detail` - Detail level (Low, High, or Auto)
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if the image URL is invalid (empty, wrong scheme, etc.)
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{Message, ImageDetail};
    ///
    /// let msg = Message::user_with_image_detail(
    ///     "Analyze this diagram in detail",
    ///     "https://example.com/diagram.png",
    ///     ImageDetail::High
    /// )?;
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    pub fn user_with_image_detail(
        text: impl Into<String>,
        image_url: impl Into<String>,
        detail: ImageDetail,
    ) -> crate::Result<Self> {
        Ok(Self {
            role: MessageRole::User,
            content: vec![
                ContentBlock::Text(TextBlock::new(text)),
                ContentBlock::Image(ImageBlock::from_url(image_url)?.with_detail(detail)),
            ],
        })
    }

    /// Creates a user message with text and a base64-encoded image.
    ///
    /// This is useful when you have image data in memory and want to send it
    /// without uploading to a URL first. The image will be encoded as a data URI.
    ///
    /// # Arguments
    ///
    /// * `text` - The text prompt
    /// * `base64_data` - Base64-encoded image data
    /// * `mime_type` - MIME type (e.g., "image/png", "image/jpeg")
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if the base64 data or MIME type is invalid
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::Message;
    ///
    /// // Use properly formatted base64 (length divisible by 4, valid chars)
    /// let base64_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
    /// let msg = Message::user_with_base64_image(
    ///     "What's this image?",
    ///     base64_data,
    ///     "image/png"
    /// )?;
    /// # Ok::<(), open_agent::Error>(())
    /// ```
    pub fn user_with_base64_image(
        text: impl Into<String>,
        base64_data: impl AsRef<str>,
        mime_type: impl AsRef<str>,
    ) -> crate::Result<Self> {
        Ok(Self {
            role: MessageRole::User,
            content: vec![
                ContentBlock::Text(TextBlock::new(text)),
                ContentBlock::Image(ImageBlock::from_base64(base64_data, mime_type)?),
            ],
        })
    }
}

/// OpenAI API message format for serialization.
///
/// This struct represents the wire format for messages when communicating
/// with OpenAI-compatible APIs. It differs from the internal [`Message`]
/// type to accommodate the specific serialization requirements of the
/// OpenAI API.
///
/// # Key Differences from Internal Message Type
///
/// - Content is a flat string rather than structured blocks
/// - Tool calls are represented in OpenAI's specific format
/// - Supports both sending tool calls (via `tool_calls`) and tool results
///   (via `tool_call_id`)
///
/// # Serialization
///
/// Optional fields are skipped when `None` to keep payloads minimal.
///
/// # Usage
///
/// This type is typically created by the SDK internally when converting
/// from [`Message`] to API format. Users rarely need to construct these
/// directly.
///
/// # OpenAI Content Format
///
/// OpenAI content format supporting both string and array.
///
/// For backward compatibility, text-only messages use string format.
/// Messages with images use array format with multiple content parts.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OpenAIContent {
    /// Simple text string (backward compatible)
    Text(String),
    /// Array of content parts (text and/or images)
    Parts(Vec<OpenAIContentPart>),
}

/// A single content part in an OpenAI message.
///
/// Can be either text or an image URL. This is a tagged enum that prevents
/// invalid states (e.g., having both text and image_url, or neither).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OpenAIContentPart {
    /// Text content part
    Text {
        /// The text content
        text: String,
    },
    /// Image URL content part
    #[serde(rename = "image_url")]
    ImageUrl {
        /// The image URL details
        image_url: OpenAIImageUrl,
    },
}

impl OpenAIContentPart {
    /// Creates a text content part.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::OpenAIContentPart;
    ///
    /// let part = OpenAIContentPart::text("Hello world");
    /// ```
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Creates an image content part from a validated ImageBlock.
    ///
    /// This is the preferred way to create image content parts as it ensures
    /// the image URL has been validated against security issues (XSS, file disclosure, etc.)
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{OpenAIContentPart, ImageBlock, ImageDetail};
    ///
    /// let image = ImageBlock::from_url("https://example.com/img.jpg")
    ///     .expect("Valid URL");
    /// let part = OpenAIContentPart::from_image(&image);
    /// ```
    pub fn from_image(image: &ImageBlock) -> Self {
        Self::ImageUrl {
            image_url: OpenAIImageUrl {
                url: image.url().to_string(),
                detail: Some(image.detail().to_string()),
            },
        }
    }

    /// Creates an image URL content part directly (DEPRECATED).
    ///
    /// # Security Warning
    ///
    /// This method bypasses validation checks performed by `ImageBlock::from_url()`
    /// and `ImageBlock::from_base64()`. Prefer using `from_image()` instead.
    ///
    /// # Deprecation
    ///
    /// This method is deprecated and will be removed in v1.0. Use `from_image()` instead.
    ///
    /// # Example
    ///
    /// ```
    /// use open_agent::{OpenAIContentPart, ImageDetail};
    ///
    /// // Deprecated approach:
    /// let part = OpenAIContentPart::image_url("https://example.com/img.jpg", ImageDetail::High);
    ///
    /// // Preferred approach:
    /// use open_agent::ImageBlock;
    /// let image = ImageBlock::from_url("https://example.com/img.jpg").expect("Valid URL");
    /// let part = OpenAIContentPart::from_image(&image);
    /// ```
    #[deprecated(
        since = "0.6.0",
        note = "Use `from_image()` instead to ensure proper validation"
    )]
    pub fn image_url(url: impl Into<String>, detail: ImageDetail) -> Self {
        Self::ImageUrl {
            image_url: OpenAIImageUrl {
                url: url.into(),
                detail: Some(detail.to_string()),
            },
        }
    }
}

/// OpenAI image URL structure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIImageUrl {
    /// Image URL or data URI
    pub url: String,
    /// Detail level: "low", "high", or "auto"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIMessage {
    /// Message role as a string ("system", "user", "assistant", "tool").
    pub role: String,

    /// Message content (string for text-only, array for text+images).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<OpenAIContent>,

    /// Tool calls requested by the assistant (assistant messages only).
    ///
    /// When the model wants to call tools, this field contains the list
    /// of tool invocations with their parameters. Only present in assistant
    /// messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<OpenAIToolCall>>,

    /// ID of the tool call this message is responding to (tool messages only).
    ///
    /// When sending tool results back to the model, this field links the
    /// result to the original tool call request. Only present in tool
    /// messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
}

/// OpenAI tool call representation in API messages.
///
/// Represents a request from the model to execute a specific function/tool.
/// This is the wire format used in the OpenAI API, distinct from the internal
/// [`ToolUseBlock`] representation.
///
/// # Structure
///
/// Each tool call has:
/// - A unique ID for correlation with results
/// - A type (always "function" in current OpenAI API)
/// - Function details (name and arguments)
///
/// # Example JSON
///
/// ```json
/// {
///   "id": "call_abc123",
///   "type": "function",
///   "function": {
///     "name": "get_weather",
///     "arguments": "{\"location\":\"San Francisco\"}"
///   }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIToolCall {
    /// Unique identifier for this tool call.
    ///
    /// Generated by the model. Used to correlate tool results back to
    /// this specific call.
    pub id: String,

    /// Type of the call (always "function" in current API).
    ///
    /// The `rename` attribute ensures this serializes as `"type"` in JSON
    /// since `type` is a Rust keyword.
    #[serde(rename = "type")]
    pub call_type: String,

    /// Function/tool details (name and arguments).
    pub function: OpenAIFunction,
}

/// OpenAI function call details.
///
/// Contains the function name and its arguments in the OpenAI API format.
/// Note that arguments are serialized as a JSON string, not a JSON object,
/// which is an OpenAI API quirk.
///
/// # Arguments Format
///
/// The `arguments` field is a **JSON string**, not a parsed JSON object.
/// For example: `"{\"x\": 1, \"y\": 2}"` not `{"x": 1, "y": 2}`.
/// This must be parsed before use.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIFunction {
    /// Name of the function/tool to call.
    pub name: String,

    /// Function arguments as a **JSON string** (OpenAI API quirk).
    ///
    /// Must be parsed as JSON before use. For example, this might contain
    /// the string `"{\"location\":\"NYC\",\"units\":\"fahrenheit\"}"` which
    /// needs to be parsed into an actual JSON value.
    pub arguments: String,
}

/// Complete request payload for OpenAI chat completions API.
///
/// This struct is serialized and sent as the request body when making
/// API calls to OpenAI-compatible endpoints. It includes the model,
/// conversation history, and configuration parameters.
///
/// # Streaming
///
/// The SDK always uses streaming mode (`stream: true`) to enable real-time
/// response processing and better user experience.
///
/// # Optional Fields
///
/// Fields marked with `skip_serializing_if` are omitted from the JSON payload
/// when `None`, allowing the API provider to use its defaults.
///
/// # Example
///
/// ```ignore
/// use open_agent_sdk::types::{OpenAIRequest, OpenAIMessage};
///
/// let request = OpenAIRequest {
///     model: "gpt-4".to_string(),
///     messages: vec![
///         OpenAIMessage {
///             role: "user".to_string(),
///             content: "Hello!".to_string(),
///             tool_calls: None,
///             tool_call_id: None,
///         }
///     ],
///     stream: true,
///     max_tokens: Some(1000),
///     temperature: Some(0.7),
///     tools: None,
/// };
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct OpenAIRequest {
    /// Model identifier (e.g., "gpt-4", "qwen2.5-32b-instruct").
    pub model: String,

    /// Conversation history as a sequence of messages.
    ///
    /// Includes system prompt, user messages, assistant responses, and
    /// tool results. Order matters - messages are processed sequentially.
    pub messages: Vec<OpenAIMessage>,

    /// Whether to stream the response.
    ///
    /// The SDK always sets this to `true` for better user experience.
    /// Streaming allows incremental processing of responses rather than
    /// waiting for the entire completion.
    pub stream: bool,

    /// Maximum tokens to generate (optional).
    ///
    /// `None` uses the provider's default. Some providers require this
    /// to be set explicitly.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,

    /// Sampling temperature (optional).
    ///
    /// `None` uses the provider's default. Controls randomness in
    /// generation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// Tools/functions available to the model (optional).
    ///
    /// When present, enables function calling. Each tool is described
    /// with a JSON schema defining its parameters. `None` means no
    /// tools are available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<serde_json::Value>>,
}

/// A single chunk from OpenAI's streaming response.
///
/// When the SDK requests streaming responses (`stream: true`), the API
/// returns the response incrementally as a series of chunks. Each chunk
/// represents a small piece of the complete response, allowing the SDK
/// to process and display content as it's generated.
///
/// # Streaming Architecture
///
/// Instead of waiting for the entire response, streaming sends many small
/// chunks in rapid succession. Each chunk contains:
/// - Metadata (id, model, timestamp)
/// - One or more choices (usually just one for single completions)
/// - Incremental deltas with new content
///
/// # Server-Sent Events Format
///
/// Chunks are transmitted as Server-Sent Events (SSE) over HTTP:
/// ```text
/// data: {"id":"chunk_1","object":"chat.completion.chunk",...}
/// data: {"id":"chunk_2","object":"chat.completion.chunk",...}
/// data: [DONE]
/// ```
///
/// # Example Chunk JSON
///
/// ```json
/// {
///   "id": "chatcmpl-123",
///   "object": "chat.completion.chunk",
///   "created": 1677652288,
///   "model": "gpt-4",
///   "choices": [{
///     "index": 0,
///     "delta": {"content": "Hello"},
///     "finish_reason": null
///   }]
/// }
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct OpenAIChunk {
    /// Unique identifier for this completion.
    ///
    /// All chunks in a single streaming response share the same ID.
    /// Not actively used by the SDK but preserved for debugging.
    #[allow(dead_code)]
    pub id: String,

    /// Object type (always "chat.completion.chunk" for streaming).
    ///
    /// Not actively used by the SDK but preserved for debugging.
    #[allow(dead_code)]
    pub object: String,

    /// Unix timestamp of when this chunk was created.
    ///
    /// Not actively used by the SDK but preserved for debugging.
    #[allow(dead_code)]
    pub created: i64,

    /// Model that generated this chunk.
    ///
    /// Not actively used by the SDK but preserved for debugging.
    #[allow(dead_code)]
    pub model: String,

    /// Array of completion choices (usually contains one element).
    ///
    /// Each choice represents a possible completion. In normal usage,
    /// there's only one choice per chunk. This is the critical field
    /// that the SDK processes to extract content and tool calls.
    pub choices: Vec<OpenAIChoice>,
}

/// A single choice/completion option in a streaming chunk.
///
/// In streaming responses, each chunk can theoretically contain multiple
/// choices (parallel completions), but in practice there's usually just one.
/// Each choice contains a delta with incremental updates and optionally a
/// finish reason when the generation is complete.
///
/// # Delta vs Complete Content
///
/// Unlike non-streaming responses that send complete messages, streaming
/// sends deltas - just the new content added in this chunk. The SDK
/// accumulates these deltas to build the complete response.
///
/// # Finish Reason
///
/// - `None`: More content is coming
/// - `Some("stop")`: Normal completion
/// - `Some("length")`: Hit max token limit
/// - `Some("tool_calls")`: Model wants to call tools
/// - `Some("content_filter")`: Blocked by content policy
#[derive(Debug, Clone, Deserialize)]
pub struct OpenAIChoice {
    /// Index of this choice in the choices array.
    ///
    /// Usually 0 since most requests generate a single completion.
    /// Not actively used by the SDK but preserved for debugging.
    #[allow(dead_code)]
    pub index: u32,

    /// Incremental update/delta for this chunk.
    ///
    /// Contains the new content, tool calls, or other updates added in
    /// this specific chunk. The SDK processes this to update its internal
    /// state and accumulate the full response.
    pub delta: OpenAIDelta,

    /// Reason why generation finished (None if still generating).
    ///
    /// Only present in the final chunk of a stream:
    /// - `None`: Generation is still in progress
    /// - `Some("stop")`: Completed normally
    /// - `Some("length")`: Hit token limit
    /// - `Some("tool_calls")`: Model requested tools
    /// - `Some("content_filter")`: Content was filtered
    ///
    /// The SDK uses this to detect completion and determine next actions.
    pub finish_reason: Option<String>,
}

/// Incremental update in a streaming chunk.
///
/// Represents the new content/changes added in this specific chunk.
/// Unlike complete messages, deltas only contain what's new, not the
/// entire accumulated content. The SDK accumulates these deltas to
/// build the complete response.
///
/// # Incremental Nature
///
/// If the complete response is "Hello, world!", the deltas might be:
/// 1. `content: Some("Hello")`
/// 2. `content: Some(", ")`
/// 3. `content: Some("world")`
/// 4. `content: Some("!")`
///
/// The SDK concatenates these to build the full text.
///
/// # Tool Call Deltas
///
/// Tool calls are also streamed incrementally. The first delta might
/// include the tool ID and name, while subsequent deltas stream the
/// arguments JSON string piece by piece.
#[derive(Debug, Clone, Deserialize)]
pub struct OpenAIDelta {
    /// Role of the message (only in first chunk).
    ///
    /// Typically "assistant". Only appears in the first delta of a response
    /// to establish who's speaking. Subsequent deltas omit this field.
    /// Not actively used by the SDK but preserved for completeness.
    #[allow(dead_code)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,

    /// Incremental text content added in this chunk.
    ///
    /// Contains the new text tokens generated. `None` if this chunk doesn't
    /// add text (e.g., it might only have tool call updates). The SDK
    /// concatenates these across chunks to build the complete response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,

    /// Incremental tool call updates added in this chunk.
    ///
    /// When the model wants to call tools, tool call information is streamed
    /// incrementally. Each delta might add to different parts of the tool
    /// call (ID, name, arguments). The SDK accumulates these to reconstruct
    /// complete tool calls.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<OpenAIToolCallDelta>>,
}

/// Incremental update for a tool call in streaming.
///
/// Tool calls are streamed piece-by-piece, with different chunks potentially
/// updating different parts. The SDK must accumulate these deltas to
/// reconstruct complete tool calls.
///
/// # Streaming Pattern
///
/// A complete tool call is typically streamed as:
/// 1. First chunk: `index: 0, id: Some("call_123"), type: Some("function")`
/// 2. Second chunk: `index: 0, function: Some(FunctionDelta { name: Some("search"), ... })`
/// 3. Multiple chunks: `index: 0, function: Some(FunctionDelta { arguments: Some("part") })`
///
/// The SDK uses the `index` to know which tool call to update, as multiple
/// tool calls can be streamed simultaneously.
///
/// # Index-Based Accumulation
///
/// The `index` field is crucial for tracking which tool call is being updated.
/// When the model calls multiple tools, each has a different index, and deltas
/// specify which one they're updating.
#[derive(Debug, Clone, Deserialize)]
pub struct OpenAIToolCallDelta {
    /// Index identifying which tool call this delta updates.
    ///
    /// When multiple tools are called, each has an index (0, 1, 2, ...).
    /// The SDK uses this to route delta updates to the correct tool call
    /// in its accumulation buffer.
    pub index: u32,

    /// Tool call ID (only in first delta for this tool call).
    ///
    /// Generated by the model. Present in the first chunk for each tool
    /// call, then omitted in subsequent chunks. The SDK stores this to
    /// correlate results later.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// Type of call (always "function" when present).
    ///
    /// Only appears in the first delta for each tool call. Subsequent
    /// deltas omit this field. Not actively used by the SDK but preserved
    /// for completeness.
    #[allow(dead_code)]
    #[serde(skip_serializing_if = "Option::is_none", rename = "type")]
    pub call_type: Option<String>,

    /// Incremental function details (name and/or arguments).
    ///
    /// Contains partial updates to the function name and arguments.
    /// The SDK accumulates these across chunks to build the complete
    /// function call specification.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function: Option<OpenAIFunctionDelta>,
}

/// Incremental update for function details in streaming tool calls.
///
/// As the model streams a tool call, the function name and arguments are
/// sent incrementally. The name usually comes first in one chunk, then
/// arguments are streamed piece-by-piece as a JSON string.
///
/// # Arguments Streaming
///
/// The arguments field is particularly important to understand. It contains
/// **fragments of a JSON string** that must be accumulated and then parsed:
///
/// 1. Chunk 1: `arguments: Some("{")`
/// 2. Chunk 2: `arguments: Some("\"query\":")`
/// 3. Chunk 3: `arguments: Some("\"hello\"")`
/// 4. Chunk 4: `arguments: Some("}")`
///
/// The SDK concatenates these into `"{\"query\":\"hello\"}"` and then
/// parses it as JSON.
#[derive(Debug, Clone, Deserialize)]
pub struct OpenAIFunctionDelta {
    /// Function/tool name (only in first delta for this function).
    ///
    /// Present when the model first starts calling this function, then
    /// omitted in subsequent chunks. The SDK stores this to know which
    /// tool to execute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Incremental fragment of the arguments JSON string.
    ///
    /// Contains a piece of the complete JSON arguments string. The SDK
    /// must concatenate all argument fragments across chunks, then parse
    /// the complete string as JSON to get the actual parameters.
    ///
    /// For example, if the complete arguments should be:
    /// `{"x": 1, "y": 2}`
    ///
    /// This might be streamed as:
    /// - `Some("{\"x\": ")`
    /// - `Some("1, \"y\": ")`
    /// - `Some("2}")`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

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

    #[test]
    fn test_agent_options_builder() {
        let options = AgentOptions::builder()
            .system_prompt("Test prompt")
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .api_key("test-key")
            .max_turns(5)
            .max_tokens(1000)
            .temperature(0.5)
            .timeout(30)
            .auto_execute_tools(true)
            .max_tool_iterations(10)
            .build()
            .unwrap();

        assert_eq!(options.system_prompt, "Test prompt");
        assert_eq!(options.model, "test-model");
        assert_eq!(options.base_url, "http://localhost:1234/v1");
        assert_eq!(options.api_key, "test-key");
        assert_eq!(options.max_turns, 5);
        assert_eq!(options.max_tokens, Some(1000));
        assert_eq!(options.temperature, 0.5);
        assert_eq!(options.timeout, 30);
        assert!(options.auto_execute_tools);
        assert_eq!(options.max_tool_iterations, 10);
    }

    #[test]
    fn test_agent_options_builder_defaults() {
        let options = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .build()
            .unwrap();

        assert_eq!(options.system_prompt, "");
        assert_eq!(options.api_key, "not-needed");
        assert_eq!(options.max_turns, 1);
        assert_eq!(options.max_tokens, Some(4096));
        assert_eq!(options.temperature, 0.7);
        assert_eq!(options.timeout, 60);
        assert!(!options.auto_execute_tools);
        assert_eq!(options.max_tool_iterations, 5);
    }

    #[test]
    fn test_agent_options_builder_missing_required() {
        // Missing model
        let result = AgentOptions::builder()
            .base_url("http://localhost:1234/v1")
            .build();
        assert!(result.is_err());

        // Missing base_url
        let result = AgentOptions::builder().model("test-model").build();
        assert!(result.is_err());
    }

    #[test]
    fn test_message_user() {
        let msg = Message::user("Hello");
        assert!(matches!(msg.role, MessageRole::User));
        assert_eq!(msg.content.len(), 1);
        match &msg.content[0] {
            ContentBlock::Text(text) => assert_eq!(text.text, "Hello"),
            _ => panic!("Expected TextBlock"),
        }
    }

    #[test]
    fn test_message_system() {
        let msg = Message::system("System prompt");
        assert!(matches!(msg.role, MessageRole::System));
        assert_eq!(msg.content.len(), 1);
        match &msg.content[0] {
            ContentBlock::Text(text) => assert_eq!(text.text, "System prompt"),
            _ => panic!("Expected TextBlock"),
        }
    }

    #[test]
    fn test_message_assistant() {
        let content = vec![ContentBlock::Text(TextBlock::new("Response"))];
        let msg = Message::assistant(content);
        assert!(matches!(msg.role, MessageRole::Assistant));
        assert_eq!(msg.content.len(), 1);
    }

    #[test]
    fn test_message_user_with_image() {
        let msg =
            Message::user_with_image("What's in this image?", "https://example.com/image.jpg")
                .unwrap();
        assert!(matches!(msg.role, MessageRole::User));
        assert_eq!(msg.content.len(), 2);

        // Should have text first, then image
        match &msg.content[0] {
            ContentBlock::Text(text) => assert_eq!(text.text, "What's in this image?"),
            _ => panic!("Expected TextBlock at position 0"),
        }
        match &msg.content[1] {
            ContentBlock::Image(image) => {
                assert_eq!(image.url(), "https://example.com/image.jpg");
                assert_eq!(image.detail(), ImageDetail::Auto);
            }
            _ => panic!("Expected ImageBlock at position 1"),
        }
    }

    #[test]
    fn test_message_user_with_image_and_detail() {
        let msg = Message::user_with_image_detail(
            "Analyze this in detail",
            "https://example.com/diagram.png",
            ImageDetail::High,
        )
        .unwrap();
        assert!(matches!(msg.role, MessageRole::User));
        assert_eq!(msg.content.len(), 2);

        match &msg.content[1] {
            ContentBlock::Image(image) => {
                assert_eq!(image.detail(), ImageDetail::High);
            }
            _ => panic!("Expected ImageBlock"),
        }
    }

    #[test]
    fn test_message_user_with_base64_image() {
        let base64_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ";
        let msg =
            Message::user_with_base64_image("What's this?", base64_data, "image/png").unwrap();
        assert!(matches!(msg.role, MessageRole::User));
        assert_eq!(msg.content.len(), 2);

        match &msg.content[1] {
            ContentBlock::Image(image) => {
                assert!(image.url().starts_with("data:image/png;base64,"));
                assert!(image.url().contains(base64_data));
            }
            _ => panic!("Expected ImageBlock"),
        }
    }

    #[test]
    fn test_text_block() {
        let block = TextBlock::new("Hello");
        assert_eq!(block.text, "Hello");
    }

    #[test]
    fn test_tool_use_block() {
        let input = serde_json::json!({"arg": "value"});
        let block = ToolUseBlock::new("call_123", "tool_name", input.clone());
        assert_eq!(block.id(), "call_123");
        assert_eq!(block.name(), "tool_name");
        assert_eq!(block.input(), &input);
    }

    #[test]
    fn test_tool_result_block() {
        let content = serde_json::json!({"result": "success"});
        let block = ToolResultBlock::new("call_123", content.clone());
        assert_eq!(block.tool_use_id(), "call_123");
        assert_eq!(block.content(), &content);
    }

    // ========================================================================
    // Private Field Getters Tests (Issue #3 - RED Phase)
    // ========================================================================

    #[test]
    fn test_tool_use_block_getters() {
        // RED: Test getter methods for ToolUseBlock (don't exist yet)
        let input = serde_json::json!({"x": 5});
        let block = ToolUseBlock::new("call_123", "calculator", input.clone());

        // These should compile with getters
        assert_eq!(block.id(), "call_123");
        assert_eq!(block.name(), "calculator");
        assert_eq!(block.input(), &input);
    }

    #[test]
    fn test_tool_result_block_getters() {
        // RED: Test getter methods for ToolResultBlock (don't exist yet)
        let content = serde_json::json!({"answer": 42});
        let result = ToolResultBlock::new("call_123", content.clone());

        assert_eq!(result.tool_use_id(), "call_123");
        assert_eq!(result.content(), &content);
    }

    #[test]
    fn test_message_role_serialization() {
        assert_eq!(
            serde_json::to_string(&MessageRole::User).unwrap(),
            "\"user\""
        );
        assert_eq!(
            serde_json::to_string(&MessageRole::System).unwrap(),
            "\"system\""
        );
        assert_eq!(
            serde_json::to_string(&MessageRole::Assistant).unwrap(),
            "\"assistant\""
        );
        assert_eq!(
            serde_json::to_string(&MessageRole::Tool).unwrap(),
            "\"tool\""
        );
    }

    #[test]
    fn test_openai_request_serialization() {
        let request = OpenAIRequest {
            model: "gpt-3.5".to_string(),
            messages: vec![OpenAIMessage {
                role: "user".to_string(),
                content: Some(OpenAIContent::Text("Hello".to_string())),
                tool_calls: None,
                tool_call_id: None,
            }],
            stream: true,
            max_tokens: Some(100),
            temperature: Some(0.7),
            tools: None,
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("gpt-3.5"));
        assert!(json.contains("Hello"));
        assert!(json.contains("\"stream\":true"));
    }

    #[test]
    fn test_openai_chunk_deserialization() {
        let json = r#"{
            "id": "chunk_1",
            "object": "chat.completion.chunk",
            "created": 1234567890,
            "model": "gpt-3.5",
            "choices": [{
                "index": 0,
                "delta": {
                    "content": "Hello"
                },
                "finish_reason": null
            }]
        }"#;

        let chunk: OpenAIChunk = serde_json::from_str(json).unwrap();
        assert_eq!(chunk.id, "chunk_1");
        assert_eq!(chunk.choices.len(), 1);
        assert_eq!(chunk.choices[0].delta.content, Some("Hello".to_string()));
    }

    #[test]
    fn test_content_block_serialization() {
        let text_block = ContentBlock::Text(TextBlock::new("Hello"));
        let json = serde_json::to_string(&text_block).unwrap();
        assert!(json.contains("\"type\":\"text\""));
        assert!(json.contains("Hello"));
    }

    #[test]
    fn test_agent_options_clone() {
        let options1 = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .build()
            .unwrap();

        let options2 = options1.clone();
        assert_eq!(options1.model, options2.model);
        assert_eq!(options1.base_url, options2.base_url);
    }

    #[test]
    fn test_temperature_validation() {
        // Temperature too low (< 0.0)
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .temperature(-0.1)
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("temperature"));

        // Temperature too high (> 2.0)
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .temperature(2.1)
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("temperature"));

        // Valid temperatures should work
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .temperature(0.0)
            .build();
        assert!(result.is_ok());

        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .temperature(2.0)
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_url_validation() {
        // Empty URL should fail
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("base_url"));

        // Invalid URL format should fail
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("not-a-url")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("base_url"));

        // Valid URLs should work
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .build();
        assert!(result.is_ok());

        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("https://api.openai.com/v1")
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_model_validation() {
        // Empty model should fail
        let result = AgentOptions::builder()
            .model("")
            .base_url("http://localhost:1234/v1")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("model"));

        // Whitespace-only model should fail
        let result = AgentOptions::builder()
            .model("   ")
            .base_url("http://localhost:1234/v1")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("model"));
    }

    #[test]
    fn test_max_tokens_validation() {
        // max_tokens = 0 should fail
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .max_tokens(0)
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("max_tokens"));

        // Valid max_tokens should work
        let result = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .max_tokens(1)
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_agent_options_getters() {
        // Test that AgentOptions provides getter methods for field access
        let options = AgentOptions::builder()
            .model("test-model")
            .base_url("http://localhost:1234/v1")
            .system_prompt("Test prompt")
            .api_key("test-key")
            .max_turns(5)
            .max_tokens(1000)
            .temperature(0.5)
            .timeout(30)
            .auto_execute_tools(true)
            .max_tool_iterations(10)
            .build()
            .unwrap();

        // All fields should be accessible via getter methods, not direct field access
        assert_eq!(options.system_prompt(), "Test prompt");
        assert_eq!(options.model(), "test-model");
        assert_eq!(options.base_url(), "http://localhost:1234/v1");
        assert_eq!(options.api_key(), "test-key");
        assert_eq!(options.max_turns(), 5);
        assert_eq!(options.max_tokens(), Some(1000));
        assert_eq!(options.temperature(), 0.5);
        assert_eq!(options.timeout(), 30);
        assert!(options.auto_execute_tools());
        assert_eq!(options.max_tool_iterations(), 10);
        assert_eq!(options.tools().len(), 0);
    }

    // ========================================================================
    // Image Support Tests (Phase 1 - TDD RED)
    // ========================================================================

    #[test]
    fn test_image_block_from_url() {
        // Should create ImageBlock from URL
        let block = ImageBlock::from_url("https://example.com/image.jpg").unwrap();
        assert_eq!(block.url(), "https://example.com/image.jpg");
        assert!(matches!(block.detail(), ImageDetail::Auto));
    }

    #[test]
    fn test_image_block_from_base64() {
        // Should create ImageBlock from base64
        let block = ImageBlock::from_base64("iVBORw0KGgoAAAA=", "image/jpeg").unwrap();
        assert!(block.url().starts_with("data:image/jpeg;base64,"));
        assert!(matches!(block.detail(), ImageDetail::Auto));
    }

    #[test]
    fn test_image_block_from_file_path() {
        use base64::{Engine as _, engine::general_purpose};
        use std::io::Write;

        // Create a temporary test file
        let temp_dir = std::env::temp_dir();
        let test_file = temp_dir.join("test_image.png");

        // Write a minimal valid 1x1 PNG (red pixel)
        let png_bytes = general_purpose::STANDARD
            .decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==")
            .unwrap();
        std::fs::File::create(&test_file)
            .unwrap()
            .write_all(&png_bytes)
            .unwrap();

        // Test: Should successfully load the file
        let block = ImageBlock::from_file_path(&test_file).unwrap();
        assert!(block.url().starts_with("data:image/png;base64,"));
        assert!(matches!(block.detail(), ImageDetail::Auto));

        // Test: Missing extension should fail
        let no_ext_file = temp_dir.join("test_image_no_ext");
        std::fs::File::create(&no_ext_file)
            .unwrap()
            .write_all(&png_bytes)
            .unwrap();
        let result = ImageBlock::from_file_path(&no_ext_file);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("extension"));

        // Test: Unsupported extension should fail
        let bad_ext_file = temp_dir.join("test_image.txt");
        std::fs::File::create(&bad_ext_file)
            .unwrap()
            .write_all(&png_bytes)
            .unwrap();
        let result = ImageBlock::from_file_path(&bad_ext_file);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Unsupported"));

        // Cleanup
        let _ = std::fs::remove_file(&test_file);
        let _ = std::fs::remove_file(&no_ext_file);
        let _ = std::fs::remove_file(&bad_ext_file);
    }

    #[test]
    fn test_image_block_with_detail() {
        // Should set detail level
        let block = ImageBlock::from_url("https://example.com/image.jpg")
            .unwrap()
            .with_detail(ImageDetail::High);
        assert!(matches!(block.detail(), ImageDetail::High));
    }

    #[test]
    fn test_image_detail_serialization() {
        // Should serialize ImageDetail to correct strings
        let json = serde_json::to_string(&ImageDetail::Low).unwrap();
        assert_eq!(json, "\"low\"");

        let json = serde_json::to_string(&ImageDetail::High).unwrap();
        assert_eq!(json, "\"high\"");

        let json = serde_json::to_string(&ImageDetail::Auto).unwrap();
        assert_eq!(json, "\"auto\"");
    }

    #[test]
    fn test_content_block_image_variant() {
        // Should add Image variant to ContentBlock
        let image = ImageBlock::from_url("https://example.com/image.jpg").unwrap();
        let block = ContentBlock::Image(image);

        match block {
            ContentBlock::Image(img) => {
                assert_eq!(img.url(), "https://example.com/image.jpg");
            }
            _ => panic!("Expected Image variant"),
        }
    }

    #[test]
    fn test_openai_content_text_format() {
        // Should serialize text-only as string (backward compat)
        let content = OpenAIContent::Text("Hello".to_string());
        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json, serde_json::json!("Hello"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_openai_content_parts_format() {
        // Should serialize mixed content as array
        let parts = vec![
            OpenAIContentPart::text("What's in this image?"),
            OpenAIContentPart::image_url("https://example.com/img.jpg", ImageDetail::High),
        ];
        let content = OpenAIContent::Parts(parts);
        let json = serde_json::to_value(&content).unwrap();

        assert!(json.is_array());
        assert_eq!(json[0]["type"], "text");
        assert_eq!(json[0]["text"], "What's in this image?");
        assert_eq!(json[1]["type"], "image_url");
        assert_eq!(json[1]["image_url"]["url"], "https://example.com/img.jpg");
        assert_eq!(json[1]["image_url"]["detail"], "high");
    }

    // ========================================================================
    // OpenAIContentPart Enum Tests (Phase 4 - PR #3 Fixes)
    // ========================================================================

    #[test]
    fn test_openai_content_part_text_serialization() {
        // RED: Test that text variant serializes correctly with enum
        let part = OpenAIContentPart::text("Hello world");
        let json = serde_json::to_value(&part).unwrap();

        // Should have type field with value "text"
        assert_eq!(json["type"], "text");
        assert_eq!(json["text"], "Hello world");
        // Should not have image_url field
        assert!(json.get("image_url").is_none());
    }

    #[test]
    #[allow(deprecated)]
    fn test_openai_content_part_image_serialization() {
        // RED: Test that image_url variant serializes correctly with enum
        let part = OpenAIContentPart::image_url("https://example.com/img.jpg", ImageDetail::Low);
        let json = serde_json::to_value(&part).unwrap();

        // Should have type field with value "image_url"
        assert_eq!(json["type"], "image_url");
        assert_eq!(json["image_url"]["url"], "https://example.com/img.jpg");
        assert_eq!(json["image_url"]["detail"], "low");
        // Should not have text field
        assert!(json.get("text").is_none());
    }

    #[test]
    #[allow(deprecated)]
    fn test_openai_content_part_enum_exhaustiveness() {
        // RED: Test that enum prevents invalid states
        // With tagged enum, it should be impossible to create a part with both text and image_url
        // or a part with neither. This test documents expected enum behavior.

        let text_part = OpenAIContentPart::text("test");
        let image_part = OpenAIContentPart::image_url("url", ImageDetail::Auto);

        // Pattern matching should be exhaustive
        match text_part {
            OpenAIContentPart::Text { .. } => {
                // Expected for text part
            }
            OpenAIContentPart::ImageUrl { .. } => {
                panic!("Text part should not match ImageUrl variant");
            }
        }

        match image_part {
            OpenAIContentPart::Text { .. } => {
                panic!("Image part should not match Text variant");
            }
            OpenAIContentPart::ImageUrl { .. } => {
                // Expected for image part
            }
        }
    }

    #[test]
    fn test_image_detail_display() {
        // Should convert ImageDetail to string
        assert_eq!(ImageDetail::Low.to_string(), "low");
        assert_eq!(ImageDetail::High.to_string(), "high");
        assert_eq!(ImageDetail::Auto.to_string(), "auto");
    }

    // ========================================================================
    // ImageBlock Validation Tests (Phase 1 - PR #3 Fixes)
    // ========================================================================

    #[test]
    fn test_image_block_from_url_rejects_empty() {
        // Should reject empty URL strings
        let result = ImageBlock::from_url("");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    #[test]
    fn test_image_block_from_url_rejects_invalid_scheme() {
        // Should reject non-HTTP/HTTPS/data schemes
        let result = ImageBlock::from_url("ftp://example.com/image.jpg");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("scheme") || err.to_string().contains("http"));
    }

    #[test]
    fn test_image_block_from_url_rejects_relative_path() {
        // Should reject relative paths
        let result = ImageBlock::from_url("/images/photo.jpg");
        assert!(result.is_err());
        // Error message should mention URL requirements
        assert!(matches!(result.unwrap_err(), crate::Error::InvalidInput(_)));
    }

    #[test]
    fn test_image_block_from_url_accepts_http() {
        // Should accept HTTP URLs
        let result = ImageBlock::from_url("http://example.com/image.jpg");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().url(), "http://example.com/image.jpg");
    }

    #[test]
    fn test_image_block_from_url_accepts_https() {
        // Should accept HTTPS URLs
        let result = ImageBlock::from_url("https://example.com/image.jpg");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().url(), "https://example.com/image.jpg");
    }

    #[test]
    fn test_image_block_from_url_accepts_data_uri() {
        // Should accept data URIs
        let data_uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
        let result = ImageBlock::from_url(data_uri);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().url(), data_uri);
    }

    #[test]
    fn test_image_block_from_url_rejects_malformed_data_uri() {
        // Should reject malformed data URIs
        let result = ImageBlock::from_url("data:notanimage");
        assert!(result.is_err());
        // Should return InvalidInput error for malformed data URI
        assert!(matches!(result.unwrap_err(), crate::Error::InvalidInput(_)));
    }

    // Phase 2: Enhanced URL validation tests (RED)

    #[test]
    fn test_from_url_rejects_control_characters() {
        // Should reject URLs with control characters
        let invalid_urls = [
            "https://example.com\n/image.jpg", // newline
            "https://example.com\t/image.jpg", // tab
            "https://example.com\0/image.jpg", // null
            "https://example.com\r/image.jpg", // carriage return
        ];

        for url in &invalid_urls {
            let result = ImageBlock::from_url(*url);
            assert!(
                result.is_err(),
                "Should reject URL with control characters: {:?}",
                url
            );
            let err = result.unwrap_err();
            assert!(
                err.to_string().contains("control") || err.to_string().contains("character"),
                "Error should mention control characters, got: {}",
                err
            );
        }
    }

    #[test]
    fn test_from_url_warns_very_long_url() {
        // Should warn (but accept) very long URLs (>2000 chars)
        // 3000-char URL
        let long_url = format!("https://example.com/{}", "a".repeat(2980));

        // Should succeed but log a warning
        let result = ImageBlock::from_url(&long_url);
        assert!(result.is_ok(), "Should accept long URL (with warning)");

        // Verify the URL was stored
        let block = result.unwrap();
        assert_eq!(block.url().len(), 3000);
    }

    #[test]
    fn test_from_url_validates_data_uri_base64() {
        // Should validate base64 portion of data URIs
        let invalid_data_uris = [
            "data:image/png;base64,",            // empty base64
            "data:image/png;base64,hello world", // spaces in base64
            "data:image/png;base64,@@@",         // invalid chars
            "data:image/png;base64,ABC",         // invalid length (not divisible by 4)
            "data:image/png;base64,==abc",       // padding in middle (not at end)
            "data:image/png;base64,ab==cd",      // padding in middle
        ];

        for uri in &invalid_data_uris {
            let result = ImageBlock::from_url(*uri);
            assert!(
                result.is_err(),
                "Should reject data URI with invalid base64: {}",
                uri
            );
        }
    }

    #[test]
    fn test_from_url_rejects_javascript_scheme() {
        // Should explicitly reject javascript: scheme (XSS risk)
        let result = ImageBlock::from_url("javascript:alert(1)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("http") || err.to_string().contains("scheme"),
            "Error should mention scheme requirements, got: {}",
            err
        );
    }

    #[test]
    fn test_from_url_rejects_file_scheme() {
        // Should reject file: scheme (security risk)
        let result = ImageBlock::from_url("file:///etc/passwd");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("http") || err.to_string().contains("scheme"),
            "Error should mention scheme requirements, got: {}",
            err
        );
    }

    #[test]
    fn test_image_block_from_base64_rejects_empty() {
        // Should reject empty base64 data
        let result = ImageBlock::from_base64("", "image/png");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    #[test]
    fn test_image_block_from_base64_rejects_invalid_mime() {
        // Should reject non-image MIME types
        let result = ImageBlock::from_base64("somedata", "text/plain");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("MIME") || err.to_string().contains("image"));
    }

    #[test]
    fn test_image_block_from_base64_accepts_valid_input() {
        // Should accept valid base64 data with image MIME type
        let base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
        let result = ImageBlock::from_base64(base64, "image/png");
        assert!(result.is_ok());
        let block = result.unwrap();
        assert!(block.url().starts_with("data:image/png;base64,"));
    }

    #[test]
    fn test_image_block_from_base64_accepts_all_image_types() {
        // Should accept all common image MIME types
        let base64 = "iVBORw0KGgo="; // Valid base64 (length multiple of 4)
        let mime_types = ["image/jpeg", "image/png", "image/gif", "image/webp"];

        for mime in &mime_types {
            let result = ImageBlock::from_base64(base64, *mime);
            assert!(result.is_ok(), "Should accept {}", mime);
            let block = result.unwrap();
            assert!(block.url().starts_with(&format!("data:{};base64,", mime)));
        }
    }

    // Phase 1: Enhanced base64 validation tests (RED)

    #[test]
    fn test_from_base64_rejects_invalid_characters() {
        // Should reject base64 with invalid characters
        let invalid_inputs = [
            "hello world", // spaces
            "test@data",   // @
            "test#data",   // #
            "test$data",   // $
            "test%data",   // %
            "abc\ndef",    // newline
        ];

        for invalid in &invalid_inputs {
            let result = ImageBlock::from_base64(invalid, "image/png");
            assert!(
                result.is_err(),
                "Should reject base64 with invalid characters: {}",
                invalid
            );
            let err = result.unwrap_err();
            assert!(
                err.to_string().contains("base64") || err.to_string().contains("character"),
                "Error should mention base64 or character issue, got: {}",
                err
            );
        }
    }

    #[test]
    fn test_from_base64_rejects_malformed_padding() {
        // Should reject base64 with incorrect padding
        let invalid_padding = [
            "A",       // Length 1 (not divisible by 4)
            "AB",      // Length 2 (not divisible by 4)
            "ABC",     // Length 3 (not divisible by 4)
            "ABCD===", // Too many padding characters
        ];

        for invalid in &invalid_padding {
            let result = ImageBlock::from_base64(invalid, "image/png");
            assert!(
                result.is_err(),
                "Should reject malformed padding: {}",
                invalid
            );
        }
    }

    #[test]
    fn test_from_base64_rejects_mime_with_semicolon() {
        // Should reject MIME types with injection characters (semicolon)
        // Use valid base64 (length divisible by 4)
        let result = ImageBlock::from_base64("AAAA", "image/png;charset=utf-8");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("MIME") || err.to_string().contains("character"),
            "Error should mention MIME or character issue, got: {}",
            err
        );
    }

    #[test]
    fn test_from_base64_rejects_mime_with_newline() {
        // Should reject MIME types with control characters (newline)
        let invalid_mimes = [
            "image/png\n",
            "image/png\r",
            "image/png\r\n",
            "image/png,extra",
        ];

        for mime in &invalid_mimes {
            // Use valid base64 (length divisible by 4)
            let result = ImageBlock::from_base64("AAAA", mime);
            assert!(
                result.is_err(),
                "Should reject MIME with control/injection chars: {:?}",
                mime
            );
        }
    }

    #[test]
    fn test_from_base64_warns_large_data() {
        // Should warn (but accept) very large base64 strings (>10MB)
        // 15MB base64 = 15,000,000 chars
        let large_base64 = "A".repeat(15_000_000);

        // This should succeed but log a warning
        let result = ImageBlock::from_base64(&large_base64, "image/png");
        assert!(result.is_ok(), "Should accept large base64 (with warning)");

        // Verify the data URI was created
        let block = result.unwrap();
        assert!(block.url().len() > 15_000_000);
    }

    #[test]
    fn test_from_base64_accepts_all_image_mime_types() {
        // Should accept all common image MIME types
        let valid_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
        let mime_types = [
            "image/jpeg",
            "image/png",
            "image/gif",
            "image/webp",
            "image/avif",
            "image/bmp",
            "image/tiff",
        ];

        for mime in &mime_types {
            let result = ImageBlock::from_base64(valid_data, *mime);
            assert!(result.is_ok(), "Should accept valid MIME type: {}", mime);
        }
    }

    #[test]
    fn test_image_block_from_base64_rejects_empty_mime() {
        // Should reject empty MIME type
        let result = ImageBlock::from_base64("somedata", "");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("MIME") || err.to_string().contains("empty"));
    }
}