blazen-cabi 0.5.2

Hand-rolled C ABI over blazen-uniffi for the Ruby gem (via cbindgen + FFI gem) and any other FFI host
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
//! LLM-related record marshalling. Wraps `Media`, `ChatMessage`, `ToolCall`,
//! `Tool`, `TokenUsage`, `CompletionRequest`, `CompletionResponse`, and
//! `EmbeddingResponse` from `blazen_uniffi::llm` as opaque C handles.
//!
//! # Ownership conventions
//!
//! All `blazen_*_new` constructors return `*mut Blazen<T>` whose ownership
//! transfers to the C caller. The caller must release the handle with the
//! matching `blazen_*_free`. Caller-owned strings returned by getters
//! (`*mut c_char`) are released with [`crate::string::blazen_string_free`].
//!
//! `*_push` setters take ownership of the pushed handle: the inner record is
//! moved into the container's `Vec` and the original `*mut` is consumed
//! (calling `blazen_*_free` on it afterwards is a double-free). `*_get(idx)`
//! getters clone the indexed item into a freshly-allocated handle the caller
//! owns. Out-of-range indices return null.
//!
//! Optional input fields use a paired `_set_<field>` / `_clear_<field>` API:
//! `_set_<field>` writes `Some(value)`, `_clear_<field>` writes `None`. For
//! `Option<String>` fields, `_set_<field>` accepts a null pointer as
//! shorthand for clearing.
//!
//! # Nested `Vec<Vec<f64>>` for embeddings
//!
//! [`BlazenEmbeddingResponse`] is unusual: the natural getter shape is
//! "vector i, index j". We expose both an indexed `_embedding_get(i, j)` for
//! sparse access and `_embedding_to_buffer(i, out, out_len)` for bulk copy
//! into a caller-supplied `f64` buffer — the bulk variant matters for hot
//! paths in embedding-heavy workloads (RAG, semantic search).

// Foundation utility consumed by R3+ wrappers; flat extern fns are kept by
// the linker regardless, but `pub(crate)` helpers fire dead-code without
// this. Once R3 wires up the typed `complete_blocking` etc., this allow can
// shrink.
#![allow(dead_code)]

use std::ffi::{CStr, c_char};

use blazen_llm::{
    CompletionResponse as CoreCompletionResponse, EmbeddingResponse as CoreEmbeddingResponse,
};
use blazen_uniffi::errors::BlazenError as InnerError;
use blazen_uniffi::llm::{
    ChatMessage as InnerChatMessage, CompletionRequest as InnerCompletionRequest,
    CompletionResponse as InnerCompletionResponse, EmbeddingResponse as InnerEmbeddingResponse,
    Media as InnerMedia, TokenUsage as InnerTokenUsage, Tool as InnerTool,
    ToolCall as InnerToolCall,
};

use crate::error::BlazenError;
use crate::string::{alloc_cstring, cstr_to_opt_string, cstr_to_str};

// ---------------------------------------------------------------------------
// Wave 3a: JSON-shim constructor helpers
//
// Mirror of the `read_json_input` / `write_internal_err` pattern in
// `compute_results.rs`. Kept module-private and duplicated rather than shared
// so each `*_records.rs` module stays self-contained (matches the cabi
// convention).
// ---------------------------------------------------------------------------

fn write_internal_err(out_err: *mut *mut BlazenError, message: String) {
    if out_err.is_null() {
        return;
    }
    // SAFETY: `out_err` is non-null per the branch above; the caller has
    // guaranteed it points to a writable `*mut BlazenError` slot.
    unsafe {
        *out_err = BlazenError::from(InnerError::Internal { message }).into_ptr();
    }
}

/// Reads `json` as UTF-8 `&str`, writing an `Internal` error through
/// `out_err` on null or non-UTF-8 input.
///
/// # Safety
///
/// `json` must be null OR point to a NUL-terminated buffer that remains valid
/// for the duration of this call.
unsafe fn read_json_input<'a>(
    json: *const c_char,
    fn_name: &str,
    out_err: *mut *mut BlazenError,
) -> Option<&'a str> {
    if json.is_null() {
        write_internal_err(out_err, format!("{fn_name}: json pointer is null"));
        return None;
    }
    // SAFETY: per the contract, `json` is a live NUL-terminated buffer.
    let cstr = unsafe { CStr::from_ptr(json) };
    match cstr.to_str() {
        Ok(s) => Some(s),
        Err(e) => {
            write_internal_err(out_err, format!("{fn_name}: input is not valid UTF-8: {e}"));
            None
        }
    }
}

// ---------------------------------------------------------------------------
// BlazenMedia
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::Media`].
pub struct BlazenMedia(pub(crate) InnerMedia);

impl BlazenMedia {
    pub(crate) fn into_ptr(self) -> *mut BlazenMedia {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerMedia> for BlazenMedia {
    fn from(inner: InnerMedia) -> Self {
        Self(inner)
    }
}

/// Constructs a new `Media` handle from the three required string fields.
///
/// Returns null if any pointer is null or contains non-UTF-8 bytes. Caller
/// owns the returned handle and must free it with [`blazen_media_free`].
///
/// # Safety
///
/// `kind`, `mime_type`, and `data_base64` must each be null OR point to a
/// NUL-terminated UTF-8 buffer that remains valid for the duration of this
/// call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_media_new(
    kind: *const c_char,
    mime_type: *const c_char,
    data_base64: *const c_char,
) -> *mut BlazenMedia {
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract on each input.
    let kind = match unsafe { cstr_to_str(kind) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let mime_type = match unsafe { cstr_to_str(mime_type) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let data_base64 = match unsafe { cstr_to_str(data_base64) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    BlazenMedia(InnerMedia {
        kind,
        mime_type,
        data_base64,
    })
    .into_ptr()
}

/// Returns the `kind` field as a caller-owned C string. Returns null on a
/// null handle. Caller frees with `blazen_string_free`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenMedia` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_media_kind(handle: *const BlazenMedia) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenMedia`.
    let m = unsafe { &*handle };
    alloc_cstring(&m.0.kind)
}

/// Returns the `mime_type` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenMedia` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_media_mime_type(handle: *const BlazenMedia) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenMedia`.
    let m = unsafe { &*handle };
    alloc_cstring(&m.0.mime_type)
}

/// Returns the `data_base64` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenMedia` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_media_data_base64(handle: *const BlazenMedia) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenMedia`.
    let m = unsafe { &*handle };
    alloc_cstring(&m.0.data_base64)
}

/// Frees a `BlazenMedia` handle. No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by
/// [`blazen_media_new`] (or by a `*_get` that returned a cloned media). Calling
/// this twice on the same non-null pointer is a double-free.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_media_free(handle: *mut BlazenMedia) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenToolCall
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::ToolCall`].
pub struct BlazenToolCall(pub(crate) InnerToolCall);

impl BlazenToolCall {
    pub(crate) fn into_ptr(self) -> *mut BlazenToolCall {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerToolCall> for BlazenToolCall {
    fn from(inner: InnerToolCall) -> Self {
        Self(inner)
    }
}

/// Constructs a new `ToolCall` handle. Returns null if any input is null or
/// non-UTF-8.
///
/// # Safety
///
/// `id`, `name`, and `arguments_json` must each be null OR point to a
/// NUL-terminated UTF-8 buffer valid for the duration of this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_call_new(
    id: *const c_char,
    name: *const c_char,
    arguments_json: *const c_char,
) -> *mut BlazenToolCall {
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract on each input.
    let id = match unsafe { cstr_to_str(id) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let name = match unsafe { cstr_to_str(name) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let arguments_json = match unsafe { cstr_to_str(arguments_json) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    BlazenToolCall(InnerToolCall {
        id,
        name,
        arguments_json,
    })
    .into_ptr()
}

/// Returns the `id` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenToolCall` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_call_id(handle: *const BlazenToolCall) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenToolCall`.
    let t = unsafe { &*handle };
    alloc_cstring(&t.0.id)
}

/// Returns the `name` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenToolCall` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_call_name(handle: *const BlazenToolCall) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenToolCall`.
    let t = unsafe { &*handle };
    alloc_cstring(&t.0.name)
}

/// Returns the `arguments_json` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenToolCall` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_call_arguments_json(
    handle: *const BlazenToolCall,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenToolCall`.
    let t = unsafe { &*handle };
    alloc_cstring(&t.0.arguments_json)
}

/// Frees a `BlazenToolCall` handle. No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface. Double-free is undefined behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_call_free(handle: *mut BlazenToolCall) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenTool
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::Tool`].
pub struct BlazenTool(pub(crate) InnerTool);

impl BlazenTool {
    pub(crate) fn into_ptr(self) -> *mut BlazenTool {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerTool> for BlazenTool {
    fn from(inner: InnerTool) -> Self {
        Self(inner)
    }
}

/// Constructs a new `Tool` handle. Returns null if any input is null or
/// non-UTF-8.
///
/// # Safety
///
/// `name`, `description`, and `parameters_json` must each be null OR point to
/// a NUL-terminated UTF-8 buffer valid for the duration of this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_new(
    name: *const c_char,
    description: *const c_char,
    parameters_json: *const c_char,
) -> *mut BlazenTool {
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract on each input.
    let name = match unsafe { cstr_to_str(name) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let description = match unsafe { cstr_to_str(description) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let parameters_json = match unsafe { cstr_to_str(parameters_json) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    BlazenTool(InnerTool {
        name,
        description,
        parameters_json,
    })
    .into_ptr()
}

/// Returns the `name` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTool` produced by the cabi surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_name(handle: *const BlazenTool) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTool`.
    let t = unsafe { &*handle };
    alloc_cstring(&t.0.name)
}

/// Returns the `description` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTool` produced by the cabi surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_description(handle: *const BlazenTool) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTool`.
    let t = unsafe { &*handle };
    alloc_cstring(&t.0.description)
}

/// Returns the `parameters_json` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTool` produced by the cabi surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_parameters_json(handle: *const BlazenTool) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTool`.
    let t = unsafe { &*handle };
    alloc_cstring(&t.0.parameters_json)
}

/// Frees a `BlazenTool` handle. No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface. Double-free is undefined behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_tool_free(handle: *mut BlazenTool) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenTokenUsage
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::TokenUsage`].
pub struct BlazenTokenUsage(pub(crate) InnerTokenUsage);

impl BlazenTokenUsage {
    pub(crate) fn into_ptr(self) -> *mut BlazenTokenUsage {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerTokenUsage> for BlazenTokenUsage {
    fn from(inner: InnerTokenUsage) -> Self {
        Self(inner)
    }
}

/// Constructs a new `TokenUsage` handle from its five `u64` counters.
///
/// Always succeeds (never returns null). Caller owns the returned handle.
#[unsafe(no_mangle)]
pub extern "C" fn blazen_token_usage_new(
    prompt_tokens: u64,
    completion_tokens: u64,
    total_tokens: u64,
    cached_input_tokens: u64,
    reasoning_tokens: u64,
) -> *mut BlazenTokenUsage {
    BlazenTokenUsage(InnerTokenUsage {
        prompt_tokens,
        completion_tokens,
        total_tokens,
        cached_input_tokens,
        reasoning_tokens,
    })
    .into_ptr()
}

/// Returns `prompt_tokens`. Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTokenUsage` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_token_usage_prompt_tokens(handle: *const BlazenTokenUsage) -> u64 {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTokenUsage`.
    let u = unsafe { &*handle };
    u.0.prompt_tokens
}

/// Returns `completion_tokens`. Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTokenUsage` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_token_usage_completion_tokens(
    handle: *const BlazenTokenUsage,
) -> u64 {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTokenUsage`.
    let u = unsafe { &*handle };
    u.0.completion_tokens
}

/// Returns `total_tokens`. Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTokenUsage` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_token_usage_total_tokens(handle: *const BlazenTokenUsage) -> u64 {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTokenUsage`.
    let u = unsafe { &*handle };
    u.0.total_tokens
}

/// Returns `cached_input_tokens`. Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTokenUsage` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_token_usage_cached_input_tokens(
    handle: *const BlazenTokenUsage,
) -> u64 {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTokenUsage`.
    let u = unsafe { &*handle };
    u.0.cached_input_tokens
}

/// Returns `reasoning_tokens`. Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenTokenUsage` produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_token_usage_reasoning_tokens(
    handle: *const BlazenTokenUsage,
) -> u64 {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenTokenUsage`.
    let u = unsafe { &*handle };
    u.0.reasoning_tokens
}

/// Frees a `BlazenTokenUsage` handle. No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface. Double-free is undefined behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_token_usage_free(handle: *mut BlazenTokenUsage) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenChatMessage
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::ChatMessage`].
pub struct BlazenChatMessage(pub(crate) InnerChatMessage);

impl BlazenChatMessage {
    pub(crate) fn into_ptr(self) -> *mut BlazenChatMessage {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerChatMessage> for BlazenChatMessage {
    fn from(inner: InnerChatMessage) -> Self {
        Self(inner)
    }
}

/// Constructs a new `ChatMessage` with empty media-parts / tool-calls vecs
/// and unset `tool_call_id` / `name` optionals.
///
/// Returns null if either input is null or non-UTF-8.
///
/// # Safety
///
/// `role` and `content` must each be null OR point to a NUL-terminated UTF-8
/// buffer valid for the duration of this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_new(
    role: *const c_char,
    content: *const c_char,
) -> *mut BlazenChatMessage {
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract on each input.
    let role = match unsafe { cstr_to_str(role) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    // SAFETY: same as above.
    let content = match unsafe { cstr_to_str(content) } {
        Some(s) => s.to_owned(),
        None => return std::ptr::null_mut(),
    };
    BlazenChatMessage(InnerChatMessage {
        role,
        content,
        media_parts: Vec::new(),
        tool_calls: Vec::new(),
        tool_call_id: None,
        name: None,
    })
    .into_ptr()
}

/// Returns the `role` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_role(handle: *const BlazenChatMessage) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    alloc_cstring(&m.0.role)
}

/// Returns the `content` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_content(
    handle: *const BlazenChatMessage,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    alloc_cstring(&m.0.content)
}

/// Pushes a `BlazenMedia` onto the message's `media_parts` vec. Consumes
/// the `media` handle — the caller must NOT free it afterwards. No-op if
/// either pointer is null (the `media` allocation is still freed in that case
/// to avoid a leak when only the handle is null).
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`. `media` must be null
/// OR a live `BlazenMedia` produced by the cabi surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_media_parts_push(
    handle: *mut BlazenChatMessage,
    media: *mut BlazenMedia,
) {
    if media.is_null() {
        return;
    }
    // SAFETY: per the contract, `media` came from `Box::into_raw`; reclaiming
    // ownership here moves the inner record so we can either push it or drop
    // it.
    let media_box = unsafe { Box::from_raw(media) };
    if handle.is_null() {
        // Drop the reclaimed Box so we don't leak it. `media_box` falls out of
        // scope here.
        drop(media_box);
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &mut *handle };
    m.0.media_parts.push(media_box.0);
}

/// Returns the number of entries in the message's `media_parts` vec.
/// Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_media_parts_count(
    handle: *const BlazenChatMessage,
) -> usize {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    m.0.media_parts.len()
}

/// Clones the `idx`-th entry from `media_parts` into a fresh `BlazenMedia`
/// handle the caller owns. Returns null if `handle` is null or `idx` is out
/// of range.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_media_parts_get(
    handle: *const BlazenChatMessage,
    idx: usize,
) -> *mut BlazenMedia {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    match m.0.media_parts.get(idx) {
        Some(media) => BlazenMedia(media.clone()).into_ptr(),
        None => std::ptr::null_mut(),
    }
}

/// Pushes a `BlazenToolCall` onto the message's `tool_calls` vec. Consumes
/// `tool_call`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`. `tool_call` must be
/// null OR a live `BlazenToolCall`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_tool_calls_push(
    handle: *mut BlazenChatMessage,
    tool_call: *mut BlazenToolCall,
) {
    if tool_call.is_null() {
        return;
    }
    // SAFETY: per the contract, `tool_call` came from `Box::into_raw`.
    let tc_box = unsafe { Box::from_raw(tool_call) };
    if handle.is_null() {
        drop(tc_box);
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &mut *handle };
    m.0.tool_calls.push(tc_box.0);
}

/// Returns the number of entries in `tool_calls`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_tool_calls_count(
    handle: *const BlazenChatMessage,
) -> usize {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    m.0.tool_calls.len()
}

/// Clones the `idx`-th tool-call entry. Returns null on out-of-range / null
/// handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_tool_calls_get(
    handle: *const BlazenChatMessage,
    idx: usize,
) -> *mut BlazenToolCall {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    match m.0.tool_calls.get(idx) {
        Some(tc) => BlazenToolCall(tc.clone()).into_ptr(),
        None => std::ptr::null_mut(),
    }
}

/// Sets the optional `tool_call_id` field. A null `value` clears the field
/// (sets `None`); a non-null pointer sets `Some(<string>)`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`. `value` must be null
/// OR point to a NUL-terminated UTF-8 buffer valid for the duration of this
/// call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_set_tool_call_id(
    handle: *mut BlazenChatMessage,
    value: *const c_char,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &mut *handle };
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract.
    m.0.tool_call_id = unsafe { cstr_to_opt_string(value) };
}

/// Returns the optional `tool_call_id` as a caller-owned C string. Returns
/// null if the field is unset or `handle` is null.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_tool_call_id(
    handle: *const BlazenChatMessage,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    match &m.0.tool_call_id {
        Some(s) => alloc_cstring(s),
        None => std::ptr::null_mut(),
    }
}

/// Sets the optional `name` field. Null `value` clears it.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`. `value` must be null
/// OR point to a NUL-terminated UTF-8 buffer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_set_name(
    handle: *mut BlazenChatMessage,
    value: *const c_char,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &mut *handle };
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract.
    m.0.name = unsafe { cstr_to_opt_string(value) };
}

/// Returns the optional `name` field as a caller-owned C string. Returns null
/// if unset.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_name(handle: *const BlazenChatMessage) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenChatMessage`.
    let m = unsafe { &*handle };
    match &m.0.name {
        Some(s) => alloc_cstring(s),
        None => std::ptr::null_mut(),
    }
}

/// Frees a `BlazenChatMessage` handle (and all owned vec / option contents).
/// No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_chat_message_free(handle: *mut BlazenChatMessage) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenCompletionRequest
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::CompletionRequest`].
pub struct BlazenCompletionRequest(pub(crate) InnerCompletionRequest);

impl BlazenCompletionRequest {
    pub(crate) fn into_ptr(self) -> *mut BlazenCompletionRequest {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerCompletionRequest> for BlazenCompletionRequest {
    fn from(inner: InnerCompletionRequest) -> Self {
        Self(inner)
    }
}

/// Constructs a new `CompletionRequest` with empty `messages`/`tools` vecs and
/// every optional field unset. Always succeeds; caller owns the handle.
#[unsafe(no_mangle)]
pub extern "C" fn blazen_completion_request_new() -> *mut BlazenCompletionRequest {
    BlazenCompletionRequest(InnerCompletionRequest {
        messages: Vec::new(),
        tools: Vec::new(),
        temperature: None,
        max_tokens: None,
        top_p: None,
        model: None,
        response_format_json: None,
        system: None,
    })
    .into_ptr()
}

/// Pushes a `BlazenChatMessage` onto the request's `messages` vec. Consumes
/// `message`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`. `message` must
/// be null OR a live `BlazenChatMessage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_messages_push(
    handle: *mut BlazenCompletionRequest,
    message: *mut BlazenChatMessage,
) {
    if message.is_null() {
        return;
    }
    // SAFETY: per the contract, `message` came from `Box::into_raw`.
    let msg_box = unsafe { Box::from_raw(message) };
    if handle.is_null() {
        drop(msg_box);
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.messages.push(msg_box.0);
}

/// Pushes a `BlazenTool` onto the request's `tools` vec. Consumes `tool`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`. `tool` must be
/// null OR a live `BlazenTool`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_tools_push(
    handle: *mut BlazenCompletionRequest,
    tool: *mut BlazenTool,
) {
    if tool.is_null() {
        return;
    }
    // SAFETY: per the contract, `tool` came from `Box::into_raw`.
    let tool_box = unsafe { Box::from_raw(tool) };
    if handle.is_null() {
        drop(tool_box);
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.tools.push(tool_box.0);
}

/// Sets `temperature` to `Some(value)`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_set_temperature(
    handle: *mut BlazenCompletionRequest,
    value: f64,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.temperature = Some(value);
}

/// Clears `temperature` back to `None`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_clear_temperature(
    handle: *mut BlazenCompletionRequest,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.temperature = None;
}

/// Sets `max_tokens` to `Some(value)`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_set_max_tokens(
    handle: *mut BlazenCompletionRequest,
    value: u32,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.max_tokens = Some(value);
}

/// Clears `max_tokens` back to `None`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_clear_max_tokens(
    handle: *mut BlazenCompletionRequest,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.max_tokens = None;
}

/// Sets `top_p` to `Some(value)`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_set_top_p(
    handle: *mut BlazenCompletionRequest,
    value: f64,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.top_p = Some(value);
}

/// Clears `top_p` back to `None`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_clear_top_p(
    handle: *mut BlazenCompletionRequest,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    r.0.top_p = None;
}

/// Sets the optional `model` field. Null `value` clears it.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`. `value` must be
/// null OR point to a NUL-terminated UTF-8 buffer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_set_model(
    handle: *mut BlazenCompletionRequest,
    value: *const c_char,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract.
    r.0.model = unsafe { cstr_to_opt_string(value) };
}

/// Sets the optional `response_format_json` field. Null `value` clears it.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`. `value` must be
/// null OR point to a NUL-terminated UTF-8 buffer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_set_response_format_json(
    handle: *mut BlazenCompletionRequest,
    value: *const c_char,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract.
    r.0.response_format_json = unsafe { cstr_to_opt_string(value) };
}

/// Sets the optional `system` field. Null `value` clears it.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionRequest`. `value` must be
/// null OR point to a NUL-terminated UTF-8 buffer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_set_system(
    handle: *mut BlazenCompletionRequest,
    value: *const c_char,
) {
    if handle.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionRequest`.
    let r = unsafe { &mut *handle };
    // SAFETY: caller upholds the NUL-terminated UTF-8 contract.
    r.0.system = unsafe { cstr_to_opt_string(value) };
}

/// Frees a `BlazenCompletionRequest` handle and all owned contents. No-op on
/// a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_request_free(handle: *mut BlazenCompletionRequest) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenCompletionResponse (output-only)
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::CompletionResponse`]. Produced
/// by `complete` / `complete_blocking` in Phase R3; no public constructor.
pub struct BlazenCompletionResponse(pub(crate) InnerCompletionResponse);

impl BlazenCompletionResponse {
    pub(crate) fn into_ptr(self) -> *mut BlazenCompletionResponse {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerCompletionResponse> for BlazenCompletionResponse {
    fn from(inner: InnerCompletionResponse) -> Self {
        Self(inner)
    }
}

/// Returns the `content` text as a caller-owned C string. Returns null on a
/// null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_content(
    handle: *const BlazenCompletionResponse,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionResponse`.
    let r = unsafe { &*handle };
    alloc_cstring(&r.0.content)
}

/// Returns the `finish_reason` field as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_finish_reason(
    handle: *const BlazenCompletionResponse,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionResponse`.
    let r = unsafe { &*handle };
    alloc_cstring(&r.0.finish_reason)
}

/// Returns the `model` identifier as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_model(
    handle: *const BlazenCompletionResponse,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionResponse`.
    let r = unsafe { &*handle };
    alloc_cstring(&r.0.model)
}

/// Returns the number of tool-call entries.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_tool_calls_count(
    handle: *const BlazenCompletionResponse,
) -> usize {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionResponse`.
    let r = unsafe { &*handle };
    r.0.tool_calls.len()
}

/// Clones the `idx`-th tool-call entry into a fresh handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_tool_calls_get(
    handle: *const BlazenCompletionResponse,
    idx: usize,
) -> *mut BlazenToolCall {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionResponse`.
    let r = unsafe { &*handle };
    match r.0.tool_calls.get(idx) {
        Some(tc) => BlazenToolCall(tc.clone()).into_ptr(),
        None => std::ptr::null_mut(),
    }
}

/// Returns a fresh `BlazenTokenUsage` handle cloned from the response's usage
/// counters. Caller frees with `blazen_token_usage_free`.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenCompletionResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_usage(
    handle: *const BlazenCompletionResponse,
) -> *mut BlazenTokenUsage {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenCompletionResponse`.
    let r = unsafe { &*handle };
    BlazenTokenUsage(r.0.usage.clone()).into_ptr()
}

/// Frees a `BlazenCompletionResponse` handle. No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_free(handle: *mut BlazenCompletionResponse) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ---------------------------------------------------------------------------
// BlazenEmbeddingResponse (output-only)
// ---------------------------------------------------------------------------

/// Opaque wrapper around [`blazen_uniffi::llm::EmbeddingResponse`]. Produced
/// by `embed` / `embed_blocking` in Phase R3; no public constructor.
pub struct BlazenEmbeddingResponse(pub(crate) InnerEmbeddingResponse);

impl BlazenEmbeddingResponse {
    pub(crate) fn into_ptr(self) -> *mut BlazenEmbeddingResponse {
        Box::into_raw(Box::new(self))
    }
}

impl From<InnerEmbeddingResponse> for BlazenEmbeddingResponse {
    fn from(inner: InnerEmbeddingResponse) -> Self {
        Self(inner)
    }
}

/// Returns the number of embedding vectors. Returns `0` on a null handle.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenEmbeddingResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_embeddings_count(
    handle: *const BlazenEmbeddingResponse,
) -> usize {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenEmbeddingResponse`.
    let r = unsafe { &*handle };
    r.0.embeddings.len()
}

/// Returns the dimensionality of the `vec_idx`-th embedding vector. Returns
/// `0` on a null handle or an out-of-range index.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenEmbeddingResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_embedding_dim(
    handle: *const BlazenEmbeddingResponse,
    vec_idx: usize,
) -> usize {
    if handle.is_null() {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenEmbeddingResponse`.
    let r = unsafe { &*handle };
    r.0.embeddings.get(vec_idx).map_or(0, Vec::len)
}

/// Returns the `dim_idx`-th coordinate of the `vec_idx`-th embedding vector.
/// Returns `0.0` on a null handle or any out-of-range index — callers should
/// gate access with `_embeddings_count` and `_embedding_dim` first.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenEmbeddingResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_embedding_get(
    handle: *const BlazenEmbeddingResponse,
    vec_idx: usize,
    dim_idx: usize,
) -> f64 {
    if handle.is_null() {
        return 0.0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenEmbeddingResponse`.
    let r = unsafe { &*handle };
    r.0.embeddings
        .get(vec_idx)
        .and_then(|v| v.get(dim_idx))
        .copied()
        .unwrap_or(0.0)
}

/// Bulk-copy the `vec_idx`-th embedding vector into the caller-supplied
/// buffer. Writes up to `min(vector_len, out_buf_len)` `f64`s starting at
/// `out_buf` and returns the actual number of `f64`s written.
///
/// Returns `0` if `handle` is null, `vec_idx` is out of range, or
/// `out_buf` is null. Designed for hot paths in embedding-heavy workloads
/// where allocating one C string per coordinate is unacceptable.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenEmbeddingResponse`. `out_buf` must
/// be null OR point to a writable buffer of at least `out_buf_len`
/// `f64`-aligned `sizeof(f64)`-spaced slots, valid for the duration of this
/// call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_embedding_to_buffer(
    handle: *const BlazenEmbeddingResponse,
    vec_idx: usize,
    out_buf: *mut f64,
    out_buf_len: usize,
) -> usize {
    if handle.is_null() || out_buf.is_null() || out_buf_len == 0 {
        return 0;
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenEmbeddingResponse`.
    let r = unsafe { &*handle };
    let Some(vec) = r.0.embeddings.get(vec_idx) else {
        return 0;
    };
    let n = vec.len().min(out_buf_len);
    // SAFETY: `out_buf` is non-null and the caller has guaranteed it is valid
    // for at least `out_buf_len` writable `f64` slots. `n` is bounded above
    // by `out_buf_len`, so the write stays in-bounds. Source and destination
    // are non-overlapping (the embedding vector lives behind `&*handle` on
    // the Rust heap; the destination is the caller-supplied buffer).
    unsafe {
        std::ptr::copy_nonoverlapping(vec.as_ptr(), out_buf, n);
    }
    n
}

/// Returns the embedding model identifier as a caller-owned C string.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenEmbeddingResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_model(
    handle: *const BlazenEmbeddingResponse,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenEmbeddingResponse`.
    let r = unsafe { &*handle };
    alloc_cstring(&r.0.model)
}

/// Returns a fresh `BlazenTokenUsage` handle cloned from the response.
///
/// # Safety
///
/// `handle` must be null OR a live `BlazenEmbeddingResponse`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_usage(
    handle: *const BlazenEmbeddingResponse,
) -> *mut BlazenTokenUsage {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `handle` is a live `BlazenEmbeddingResponse`.
    let r = unsafe { &*handle };
    BlazenTokenUsage(r.0.usage.clone()).into_ptr()
}

/// Frees a `BlazenEmbeddingResponse` handle. No-op on a null pointer.
///
/// # Safety
///
/// `handle` must be null OR a pointer previously produced by the cabi
/// surface.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_free(handle: *mut BlazenEmbeddingResponse) {
    if handle.is_null() {
        return;
    }
    // SAFETY: per the contract, `handle` came from `Box::into_raw`.
    drop(unsafe { Box::from_raw(handle) });
}

// ===========================================================================
// JSON-shim constructors (Wave 3a)
//
// `BlazenCompletionResponse` and `BlazenEmbeddingResponse` wrap UniFFI
// `Record` types in `blazen_uniffi::llm`, which intentionally do NOT derive
// `serde::Deserialize` (UniFFI's record macro doesn't emit it). To accept
// JSON from FFI hosts, we parse against the underlying `blazen_llm` native
// types (which DO derive `Serialize` / `Deserialize`) and convert via the
// existing `From<CoreCompletionResponse> for CompletionResponse` /
// `From<CoreEmbeddingResponse> for EmbeddingResponse` impls in
// `blazen_uniffi::llm`. Round-trip fidelity matches the existing
// future-take path used by `blazen_future_take_completion_response`.
// ===========================================================================

/// Constructs a [`BlazenCompletionResponse`] handle from a JSON-encoded
/// [`blazen_llm::CompletionResponse`].
///
/// # Ownership
///
/// On success returns a non-null handle owned by the caller — release with
/// [`blazen_completion_response_free`]. On failure returns null and writes a
/// fresh `BlazenError::Internal { message }` into `*out_err` when `out_err`
/// is non-null (caller frees with [`crate::error::blazen_error_free`]).
///
/// # Safety
///
/// `json` must be null OR point to a NUL-terminated UTF-8 buffer valid for
/// the duration of this call. `out_err` must be null OR point to a writable
/// `*mut BlazenError` slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_completion_response_from_json(
    json: *const c_char,
    out_err: *mut *mut BlazenError,
) -> *mut BlazenCompletionResponse {
    // SAFETY: forwarded to `read_json_input`; caller upholds the contract.
    let Some(s) =
        (unsafe { read_json_input(json, "blazen_completion_response_from_json", out_err) })
    else {
        return std::ptr::null_mut();
    };
    match serde_json::from_str::<CoreCompletionResponse>(s) {
        Ok(core) => BlazenCompletionResponse(InnerCompletionResponse::from(core)).into_ptr(),
        Err(e) => {
            write_internal_err(
                out_err,
                format!("blazen_completion_response_from_json: deserialize failed: {e}"),
            );
            std::ptr::null_mut()
        }
    }
}

/// Constructs a [`BlazenEmbeddingResponse`] handle from a JSON-encoded
/// [`blazen_llm::EmbeddingResponse`].
///
/// # Ownership
///
/// On success returns a non-null handle owned by the caller — release with
/// [`blazen_embedding_response_free`]. On failure returns null and writes a
/// fresh `BlazenError::Internal { message }` into `*out_err` when `out_err`
/// is non-null (caller frees with [`crate::error::blazen_error_free`]).
///
/// # Safety
///
/// `json` must be null OR point to a NUL-terminated UTF-8 buffer valid for
/// the duration of this call. `out_err` must be null OR point to a writable
/// `*mut BlazenError` slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_embedding_response_from_json(
    json: *const c_char,
    out_err: *mut *mut BlazenError,
) -> *mut BlazenEmbeddingResponse {
    // SAFETY: forwarded to `read_json_input`; caller upholds the contract.
    let Some(s) =
        (unsafe { read_json_input(json, "blazen_embedding_response_from_json", out_err) })
    else {
        return std::ptr::null_mut();
    };
    match serde_json::from_str::<CoreEmbeddingResponse>(s) {
        Ok(core) => BlazenEmbeddingResponse(InnerEmbeddingResponse::from(core)).into_ptr(),
        Err(e) => {
            write_internal_err(
                out_err,
                format!("blazen_embedding_response_from_json: deserialize failed: {e}"),
            );
            std::ptr::null_mut()
        }
    }
}