matchy 2.0.1

Fast database for IP address and pattern matching with rich data storage
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
//! Clean Matchy C API
//!
//! This module provides a modern, clean C API for building and querying databases
//! containing IP addresses and patterns. This is the primary public API.

use crate::database::{Database, ReloadEvent};
use crate::schema_validation::SchemaValidator;
use crate::schemas::{get_schema_info, is_known_database_type};
use crate::DatabaseBuilder;
use chrono::TimeZone;
use matchy_data_format::DataValue;
use matchy_match_mode::MatchMode;
use std::collections::HashMap;
use std::ffi::{c_void, CStr, CString};
use std::os::raw::c_char;
use std::ptr;
use std::slice;

struct CCallbackAdapter {
    callback: unsafe extern "C" fn(event: *const matchy_reload_event_t, user_data: *mut c_void),
    user_data: *mut c_void,
}

// SAFETY: CCallbackAdapter is Send+Sync because the C callback and user_data
// are provided by the caller who guarantees thread-safety of their usage
unsafe impl Send for CCallbackAdapter {}
// SAFETY: See above
unsafe impl Sync for CCallbackAdapter {}

impl CCallbackAdapter {
    fn invoke(&self, event: &ReloadEvent) {
        let path_cstring =
            std::ffi::CString::new(event.path.to_string_lossy().as_ref()).unwrap_or_default();
        let error_cstring = event
            .error
            .as_ref()
            .and_then(|e| std::ffi::CString::new(e.as_str()).ok());

        let c_event = matchy_reload_event_t {
            path: path_cstring.as_ptr(),
            success: event.success,
            error: error_cstring
                .as_ref()
                .map(|s| s.as_ptr())
                .unwrap_or(ptr::null()),
            generation: event.generation,
        };

        // SAFETY: Callback and user_data validity guaranteed by C caller contract
        unsafe { (self.callback)(&c_event, self.user_data) };
    }
}

// ============================================================================
// ERROR CODES
// ============================================================================

/// Success code
pub const MATCHY_SUCCESS: i32 = 0;
/// File not found error
pub const MATCHY_ERROR_FILE_NOT_FOUND: i32 = -1;
/// Invalid format error
pub const MATCHY_ERROR_INVALID_FORMAT: i32 = -2;
/// Corrupt data error
pub const MATCHY_ERROR_CORRUPT_DATA: i32 = -3;
/// Out of memory error
pub const MATCHY_ERROR_OUT_OF_MEMORY: i32 = -4;
/// Invalid parameter error
pub const MATCHY_ERROR_INVALID_PARAM: i32 = -5;
/// I/O error
pub const MATCHY_ERROR_IO: i32 = -6;
/// Schema validation error
pub const MATCHY_ERROR_SCHEMA_VALIDATION: i32 = -7;
/// Unknown schema error
pub const MATCHY_ERROR_UNKNOWN_SCHEMA: i32 = -8;

// ============================================================================
// OPAQUE HANDLES
// ============================================================================

/// Opaque database builder handle
#[repr(C)]
pub struct matchy_builder_t {
    _private: [u8; 0],
}

/// Opaque database handle
#[repr(C)]
pub struct matchy_t {
    _private: [u8; 0],
}

/// Query result (zero-allocation)
#[repr(C)]
pub struct matchy_result_t {
    /// Whether a match was found
    pub found: bool,
    /// Network prefix length (for IP results)
    pub prefix_len: u8,
    /// Result type: 0=not found, 1=ip, 2=pattern
    pub _result_type: u8,
    /// Data offset into mmap'd data section (use matchy_aget_value to decode)
    pub _data_offset: u32,
    /// Internal database reference (for decoding)
    pub _db_ref: *const matchy_t,
}

// ============================================================================
// INTERNAL STRUCTURES
// ============================================================================

struct MatchyBuilderInternal {
    builder: DatabaseBuilder,
    /// Optional schema validator (set via matchy_builder_set_schema)
    validator: Option<SchemaValidator>,
}

struct MatchyInternal {
    database: Database,
}

// Conversion helpers for opaque types
impl matchy_builder_t {
    fn from_internal(internal: Box<MatchyBuilderInternal>) -> *mut Self {
        Box::into_raw(internal).cast::<Self>()
    }

    unsafe fn into_internal(ptr: *mut Self) -> Box<MatchyBuilderInternal> {
        Box::from_raw(ptr.cast::<MatchyBuilderInternal>())
    }

    unsafe fn as_internal_mut(ptr: *mut Self) -> &'static mut MatchyBuilderInternal {
        &mut *ptr.cast::<MatchyBuilderInternal>()
    }
}

impl matchy_t {
    fn from_internal(internal: Box<MatchyInternal>) -> *mut Self {
        Box::into_raw(internal).cast::<Self>()
    }

    unsafe fn into_internal(ptr: *mut Self) -> Box<MatchyInternal> {
        Box::from_raw(ptr.cast::<MatchyInternal>())
    }

    unsafe fn as_internal(ptr: *const Self) -> &'static MatchyInternal {
        &*ptr.cast::<MatchyInternal>()
    }
}

// ============================================================================
// DATABASE BUILDING API
// ============================================================================

/// Create a new database builder
///
/// # Returns
/// * Non-null pointer on success
/// * NULL on allocation failure
///
/// # Example
/// ```c
/// matchy_builder_t *builder = matchy_builder_new();
/// if (builder == NULL) {
///     fprintf(stderr, "Failed to create builder\n");
///     return 1;
/// }
/// ```
#[no_mangle]
pub extern "C" fn matchy_builder_new() -> *mut matchy_builder_t {
    let builder = DatabaseBuilder::new(MatchMode::CaseSensitive);
    let internal = Box::new(MatchyBuilderInternal {
        builder,
        validator: None,
    });
    matchy_builder_t::from_internal(internal)
}

/// Set case-insensitive matching mode
///
/// When enabled, all pattern/literal lookups will be case-insensitive.
/// IP lookups are always case-insensitive regardless of this setting.
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `case_insensitive` - true for case-insensitive, false for case-sensitive (default)
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * MATCHY_ERROR_INVALID_PARAM if builder is NULL
///
/// # Safety
/// * `builder` must be a valid pointer returned by `matchy_builder_new()` or NULL
/// * `builder` must not have been freed with `matchy_builder_free()`
///
/// # Example
/// ```c
/// matchy_builder_t *builder = matchy_builder_new();
/// matchy_builder_set_case_insensitive(builder, true);
/// // Entries like "Evil.COM" will match queries for "evil.com", "EVIL.COM", etc.
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_set_case_insensitive(
    builder: *mut matchy_builder_t,
    case_insensitive: bool,
) -> i32 {
    if builder.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let internal = matchy_builder_t::as_internal_mut(builder);
    let match_mode = if case_insensitive {
        MatchMode::CaseInsensitive
    } else {
        MatchMode::CaseSensitive
    };
    internal.builder.set_match_mode(match_mode);

    MATCHY_SUCCESS
}

/// Enable schema validation for a known database type
///
/// When a schema is set, all entries added via matchy_builder_add() will be
/// validated against the schema. Invalid entries will cause add to return
/// MATCHY_ERROR_SCHEMA_VALIDATION.
///
/// Known database types:
/// - "threatdb" - Threat intelligence database (ThreatDB-v1 schema)
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `schema_name` - Name of a known schema (e.g., "threatdb")
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * MATCHY_ERROR_UNKNOWN_SCHEMA if the schema name is not recognized
/// * MATCHY_ERROR_INVALID_PARAM if builder or schema_name is NULL
///
/// # Safety
/// * `builder` must be a valid pointer returned by `matchy_builder_new()` or NULL
/// * `builder` must not have been freed with `matchy_builder_free()`
/// * `schema_name` must be a valid null-terminated C string or NULL
///
/// # Example
/// ```c
/// matchy_builder_t *builder = matchy_builder_new();
/// int result = matchy_builder_set_schema(builder, "threatdb");
/// if (result != MATCHY_SUCCESS) {
///     fprintf(stderr, "Unknown schema\n");
///     return 1;
/// }
/// // Now all entries will be validated against ThreatDB schema
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_set_schema(
    builder: *mut matchy_builder_t,
    schema_name: *const c_char,
) -> i32 {
    if builder.is_null() || schema_name.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let name = match CStr::from_ptr(schema_name).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    // Check if this is a known schema
    if !is_known_database_type(name) {
        return MATCHY_ERROR_UNKNOWN_SCHEMA;
    }

    // Create validator
    let validator = match SchemaValidator::new(name) {
        Ok(v) => v,
        Err(_) => return MATCHY_ERROR_INVALID_FORMAT,
    };

    // Get the canonical database type and set it
    let internal = matchy_builder_t::as_internal_mut(builder);
    if let Some(info) = get_schema_info(name) {
        // DatabaseBuilder's with_database_type takes ownership and returns Self
        // We need to use a placeholder to swap it out
        let placeholder = DatabaseBuilder::new(MatchMode::CaseSensitive);
        let old_builder = std::mem::replace(&mut internal.builder, placeholder);
        internal.builder = old_builder.with_database_type(info.database_type);
    }
    internal.validator = Some(validator);

    MATCHY_SUCCESS
}

/// Add an entry with associated data (as JSON)
///
/// Automatically detects whether the key is an IP address, CIDR range, or pattern.
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `key` - IP address, CIDR, or pattern (null-terminated C string, must not be NULL)
/// * `json_data` - Associated data as JSON (null-terminated C string, must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * Error code < 0 on failure
///
/// # Safety
/// * `builder` must be a valid pointer from matchy_builder_new
/// * `key` must be a valid null-terminated C string
/// * `json_data` must be a valid null-terminated C string containing valid JSON
///
/// # Example
/// ```c
/// matchy_builder_add(builder, "1.2.3.4", "{\"threat_level\": \"high\"}");
/// matchy_builder_add(builder, "10.0.0.0/8", "{\"type\": \"internal\"}");
/// matchy_builder_add(builder, "*.evil.com", "{\"category\": \"malware\"}");
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_add(
    builder: *mut matchy_builder_t,
    key: *const c_char,
    json_data: *const c_char,
) -> i32 {
    if builder.is_null() || key.is_null() || json_data.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let key_str = match CStr::from_ptr(key).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    let json_str = match CStr::from_ptr(json_data).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    // Parse JSON to DataValue (supports nested structures)
    let data: DataValue = match serde_json::from_str(json_str) {
        Ok(d) => d,
        Err(_) => return MATCHY_ERROR_INVALID_FORMAT,
    };

    // Wrap in a map if it's not already a map
    let data_map = match data {
        DataValue::Map(m) => m,
        _ => {
            // Single value - wrap it in a map with "value" key
            let mut map = HashMap::new();
            map.insert("value".to_string(), data);
            map
        }
    };

    let internal = matchy_builder_t::as_internal_mut(builder);

    // Validate against schema if one is set
    if let Some(ref validator) = internal.validator {
        if validator.validate(&data_map).is_err() {
            return MATCHY_ERROR_SCHEMA_VALIDATION;
        }
    }

    match internal.builder.add_entry(key_str, data_map) {
        Ok(_) => MATCHY_SUCCESS,
        Err(_) => MATCHY_ERROR_INVALID_FORMAT,
    }
}

/// Set database description
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `description` - Description text (null-terminated C string, must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * Error code < 0 on failure
///
/// # Safety
/// * `builder` must be a valid pointer from matchy_builder_new
/// * `description` must be a valid null-terminated C string
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_set_description(
    builder: *mut matchy_builder_t,
    description: *const c_char,
) -> i32 {
    if builder.is_null() || description.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let desc_str = match CStr::from_ptr(description).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    let internal = matchy_builder_t::as_internal_mut(builder);
    // Create new builder with description
    let old_builder = std::mem::replace(
        &mut internal.builder,
        DatabaseBuilder::new(MatchMode::CaseSensitive),
    );
    internal.builder = old_builder.with_description("en", desc_str);

    MATCHY_SUCCESS
}

/// Set the update URL for the database
///
/// When set, this URL is stored in the database metadata. Applications using
/// auto_update will fetch updates from this URL.
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `url` - Update URL (null-terminated C string, must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * MATCHY_ERROR_INVALID_PARAM if parameters invalid
///
/// # Safety
/// * `builder` must be a valid pointer from matchy_builder_new
/// * `url` must be a valid null-terminated C string
///
/// # Example
/// ```c
/// matchy_builder_set_update_url(builder, "https://example.com/threats.mxy");
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_set_update_url(
    builder: *mut matchy_builder_t,
    url: *const c_char,
) -> i32 {
    if builder.is_null() || url.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let url_str = match CStr::from_ptr(url).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    let internal = matchy_builder_t::as_internal_mut(builder);
    let old_builder = std::mem::replace(
        &mut internal.builder,
        DatabaseBuilder::new(MatchMode::CaseSensitive),
    );
    internal.builder = old_builder.with_update_url(url_str);

    MATCHY_SUCCESS
}

/// Build and save database to file
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `filename` - Path where file should be written (null-terminated C string, must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * Error code < 0 on failure
///
/// # Safety
/// * `builder` must be a valid pointer from matchy_builder_new
/// * `filename` must be a valid null-terminated C string
///
/// # Example
/// ```c
/// if (matchy_builder_save(builder, "threats.db") != MATCHY_SUCCESS) {
///     fprintf(stderr, "Failed to save database\n");
/// }
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_save(
    builder: *mut matchy_builder_t,
    filename: *const c_char,
) -> i32 {
    if builder.is_null() || filename.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let path = match CStr::from_ptr(filename).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    let internal = matchy_builder_t::as_internal_mut(builder);
    // Replace builder with a dummy one to take ownership
    let builder_to_build = std::mem::replace(
        &mut internal.builder,
        DatabaseBuilder::new(MatchMode::CaseSensitive),
    );
    let bytes = match builder_to_build.build() {
        Ok(b) => b,
        Err(_) => return MATCHY_ERROR_INVALID_FORMAT,
    };

    match std::fs::write(path, bytes) {
        Ok(_) => MATCHY_SUCCESS,
        Err(_) => MATCHY_ERROR_IO,
    }
}

/// Build and return database in memory
///
/// # Parameters
/// * `builder` - Builder handle (must not be NULL)
/// * `buffer` - Pointer to receive the buffer pointer (must not be NULL)
/// * `size` - Pointer to receive the buffer size (must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS (0) on success
/// * Error code < 0 on failure
///
/// # Safety
/// * `builder` must be a valid pointer from matchy_builder_new
/// * `buffer` and `size` must be valid pointers
/// * Caller must free the returned buffer with libc::free()
///
/// # Example
/// ```c
/// uint8_t *buffer = NULL;
/// size_t size = 0;
/// if (matchy_builder_build(builder, &buffer, &size) == MATCHY_SUCCESS) {
///     // Use buffer...
///     free(buffer);
/// }
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_build(
    builder: *mut matchy_builder_t,
    buffer: *mut *mut u8,
    size: *mut usize,
) -> i32 {
    if builder.is_null() || buffer.is_null() || size.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let internal = matchy_builder_t::as_internal_mut(builder);
    // Replace builder with a dummy one to take ownership
    let builder_to_build = std::mem::replace(
        &mut internal.builder,
        DatabaseBuilder::new(MatchMode::CaseSensitive),
    );
    let bytes = match builder_to_build.build() {
        Ok(b) => b,
        Err(_) => return MATCHY_ERROR_INVALID_FORMAT,
    };

    // Allocate buffer using libc::malloc so C can free it
    let buf_size = bytes.len();
    let buf_ptr = libc::malloc(buf_size).cast::<u8>();
    if buf_ptr.is_null() {
        return MATCHY_ERROR_OUT_OF_MEMORY;
    }

    // Copy data
    std::ptr::copy_nonoverlapping(bytes.as_ptr(), buf_ptr, buf_size);

    *buffer = buf_ptr;
    *size = buf_size;

    MATCHY_SUCCESS
}

/// Free builder
///
/// # Parameters
/// * `builder` - Builder handle (may be NULL)
///
/// # Safety
/// * `builder` must be NULL or a valid pointer from matchy_builder_new
/// * Must not be used after calling this function
/// * Calling with NULL is safe (no-op)
#[no_mangle]
pub unsafe extern "C" fn matchy_builder_free(builder: *mut matchy_builder_t) {
    if !builder.is_null() {
        let _ = matchy_builder_t::into_internal(builder);
    }
}

// ============================================================================
// DATABASE QUERYING API
// ============================================================================

/// Reload callback event information
///
/// Information passed to reload callbacks when database reloads occur.
#[repr(C)]
pub struct matchy_reload_event_t {
    /// Path to database file (null-terminated C string)
    /// Valid only for duration of callback - copy if needed
    pub path: *const c_char,

    /// Whether reload succeeded
    /// true = successful reload, false = reload failed
    pub success: bool,

    /// Error message if reload failed (null if success)
    /// Valid only for duration of callback - copy if needed
    pub error: *const c_char,

    /// Generation counter (increments on each successful reload)
    /// Can be used to detect if database has changed since last check
    pub generation: u64,
}

/// Reload callback function type
///
/// Called when database reload completes (success or failure).
/// Called from watcher thread - keep processing minimal!
///
/// # Parameters
/// * `event` - Reload event information (valid only during callback)
/// * `user_data` - User-provided context pointer from matchy_open_options_t
///
/// # Safety
/// * Callback must be thread-safe
/// * Do not call matchy_* functions from callback (potential deadlock)
/// * Copy event.path and event.error if you need them after callback returns
/// * user_data must match what was provided in options
///
/// # Example
/// ```c
/// void on_reload(const matchy_reload_event_t *event, void *user_data) {
///     if (event->success) {
///         printf("Database reloaded: %s (generation %lu)\n",
///                event->path, event->generation);
///     } else {
///         fprintf(stderr, "Reload failed: %s - %s\n",
///                 event->path, event->error);
///     }
/// }
/// ```
#[allow(non_camel_case_types)]
pub type matchy_reload_callback_t =
    Option<unsafe extern "C" fn(event: *const matchy_reload_event_t, user_data: *mut c_void)>;

/// Database opening options
///
/// Configure how databases are loaded, including cache settings and validation.
#[repr(C)]
pub struct matchy_open_options_t {
    /// LRU cache capacity
    /// 0 = disable cache, >0 = cache this many entries
    /// Default: 10000
    pub cache_capacity: u32,

    /// Enable automatic reload when database file changes
    /// false = no watching (default), true = auto-reload on file changes
    /// Default: false
    ///
    /// When enabled, the database watches its source file and automatically
    /// reloads when changes are detected. All queries transparently use the
    /// latest version. Adds ~10-20ns overhead per query due to read lock.
    pub auto_reload: bool,

    /// Enable automatic updates from database's embedded URL (requires auto-update feature)
    /// false = no network updates (default), true = check for updates periodically
    /// Default: false
    ///
    /// When enabled, periodically checks the database's embedded update URL for new versions
    /// using HTTP conditional GET (ETag). Database must have an update URL embedded in metadata.
    /// Updates are downloaded to cache_dir (or system default), not the original file.
    pub auto_update: bool,

    /// How often to check for remote updates, in seconds
    /// Only used when auto_update is true
    /// Default: 3600 (1 hour)
    pub update_interval_secs: u32,

    /// Cache directory for downloaded updates (optional)
    /// If NULL, uses system default (~/.cache/matchy/ on Unix)
    /// Default: NULL
    pub cache_dir: *const c_char,

    /// Reload callback function (optional)
    /// Called when database reload completes (success or failure)
    /// Set to NULL to disable callback
    /// Default: NULL
    pub reload_callback: matchy_reload_callback_t,

    /// User data pointer passed to reload callback
    /// Can be any pointer - callback receives it as-is
    /// Default: NULL
    pub reload_callback_user_data: *mut c_void,
}

impl Default for matchy_open_options_t {
    fn default() -> Self {
        Self {
            cache_capacity: 10000,
            auto_reload: false,
            auto_update: false,
            update_interval_secs: 3600,
            cache_dir: ptr::null(),
            reload_callback: None,
            reload_callback_user_data: ptr::null_mut(),
        }
    }
}

/// Initialize database opening options with defaults
///
/// Sets default values:
/// - cache_capacity = 10000
/// - auto_reload = false
///
/// # Parameters
/// * `options` - Pointer to options struct to initialize (must not be NULL)
///
/// # Safety
/// * `options` must be a valid pointer
///
/// # Example
/// ```c
/// matchy_open_options_t opts;
/// matchy_init_open_options(&opts);
/// opts.cache_capacity = 100000;  // Custom size
/// opts.auto_reload = true;        // Enable auto-reload
/// matchy_t *db = matchy_open_with_options("threats.mxy", &opts);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_init_open_options(options: *mut matchy_open_options_t) {
    if options.is_null() {
        return;
    }
    *options = matchy_open_options_t::default();
}

/// Open database with custom options
///
/// Opens a database file with configurable cache size, auto-reload, and validation settings.
///
/// # Parameters
/// * `filename` - Path to database file (null-terminated C string, must not be NULL)
/// * `options` - Opening options (must not be NULL)
///
/// # Returns
/// * Non-null pointer on success
/// * NULL on failure
///
/// # Safety
/// * `filename` must be a valid null-terminated C string
/// * `options` must be a valid pointer
///
/// # Example
/// ```c
/// // High-performance mode with auto-reload
/// matchy_open_options_t opts;
/// matchy_init_open_options(&opts);
/// opts.cache_capacity = 100000; // Large cache
/// opts.auto_reload = true;      // Watch file for changes
///
/// matchy_t *db = matchy_open_with_options("threats.mxy", &opts);
/// if (db == NULL) {
///     fprintf(stderr, "Failed to open database\n");
///     return 1;
/// }
///
/// // Queries automatically use latest database version
/// matchy_result_t result;
/// matchy_lookup(db, "1.2.3.4", &result);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_open_with_options(
    filename: *const c_char,
    options: *const matchy_open_options_t,
) -> *mut matchy_t {
    if filename.is_null() || options.is_null() {
        return ptr::null_mut();
    }

    let path = match CStr::from_ptr(filename).to_str() {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };

    let opts = &*options;

    let mut opener = Database::from(path);

    if opts.cache_capacity == 0 {
        opener = opener.no_cache();
    } else {
        opener = opener.cache_capacity(opts.cache_capacity as usize);
    }

    if opts.auto_reload {
        opener = opener.watch();
    }

    #[cfg(feature = "auto-update")]
    if opts.auto_update {
        opener = opener
            .auto_update()
            .update_interval(std::time::Duration::from_secs(u64::from(
                opts.update_interval_secs,
            )));

        if !opts.cache_dir.is_null() {
            if let Ok(dir) = CStr::from_ptr(opts.cache_dir).to_str() {
                opener = opener.cache_dir(dir);
            }
        }
    }

    if let Some(callback) = opts.reload_callback {
        let adapter = CCallbackAdapter {
            callback,
            user_data: opts.reload_callback_user_data,
        };
        opener = opener.on_reload(move |event: ReloadEvent| {
            adapter.invoke(&event);
        });
    }

    match opener.open() {
        Ok(db) => {
            let internal = Box::new(MatchyInternal { database: db });
            matchy_t::from_internal(internal)
        }
        Err(_) => ptr::null_mut(),
    }
}

/// Open database from file (memory-mapped) - SAFE mode
///
/// Opens a database file using memory mapping for optimal performance.
/// The file is not loaded into memory - it's accessed on-demand.
///
/// This validates UTF-8 on pattern string reads. Use for untrusted databases.
///
/// # Parameters
/// * `filename` - Path to database file (null-terminated C string, must not be NULL)
///
/// # Returns
/// * Non-null pointer on success
/// * NULL on failure
///
/// # Safety
/// * `filename` must be a valid null-terminated C string
///
/// # Example
/// ```c
/// matchy_t *db = matchy_open("threats.db");
/// if (db == NULL) {
///     fprintf(stderr, "Failed to open database\n");
///     return 1;
/// }
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_open(filename: *const c_char) -> *mut matchy_t {
    // Delegate to matchy_open_with_options with default settings
    let opts = matchy_open_options_t::default();
    matchy_open_with_options(filename, &opts)
}

/// Open database from memory buffer (zero-copy)
///
/// Creates a database handle from a memory buffer. No data is copied.
///
/// # Parameters
/// * `buffer` - Pointer to database data (must not be NULL)
/// * `size` - Size of buffer in bytes (must be > 0)
///
/// # Returns
/// * Non-null pointer on success
/// * NULL on failure
///
/// # Safety
/// * `buffer` must be valid for the lifetime of the database handle
/// * Caller must not modify or free buffer while handle exists
#[no_mangle]
pub unsafe extern "C" fn matchy_open_buffer(buffer: *const u8, size: usize) -> *mut matchy_t {
    if buffer.is_null() || size == 0 {
        return ptr::null_mut();
    }

    let slice = slice::from_raw_parts(buffer, size);
    match Database::from_bytes(slice.to_vec()) {
        Ok(db) => {
            let internal = Box::new(MatchyInternal { database: db });
            matchy_t::from_internal(internal)
        }
        Err(_) => ptr::null_mut(),
    }
}

/// Database statistics
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct matchy_stats_t {
    /// Total number of queries executed
    pub total_queries: u64,
    /// Queries that found a match
    pub queries_with_match: u64,
    /// Queries that found no match
    pub queries_without_match: u64,
    /// Cache hits (query served from cache)
    pub cache_hits: u64,
    /// Cache misses (query required lookup)
    pub cache_misses: u64,
    /// Number of IP address queries
    pub ip_queries: u64,
    /// Number of string queries (literal or pattern)
    pub string_queries: u64,
}

/// Get database statistics
///
/// Returns statistics about query performance, cache effectiveness,
/// and query distribution.
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
/// * `stats` - Pointer to stats structure to fill (must not be NULL)
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
/// * `stats` must be a valid pointer to matchy_stats_t
///
/// # Example
/// ```c
/// matchy_stats_t stats;
/// matchy_get_stats(db, &stats);
/// printf("Total queries: %llu\n", stats.total_queries);
///
/// // Calculate hit rate
/// double cache_hit_rate = 0.0;
/// if (stats.cache_hits + stats.cache_misses > 0) {
///     cache_hit_rate = (double)stats.cache_hits /
///                      (stats.cache_hits + stats.cache_misses);
/// }
/// printf("Cache hit rate: %.1f%%\n", cache_hit_rate * 100.0);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_get_stats(db: *const matchy_t, stats: *mut matchy_stats_t) {
    if db.is_null() || stats.is_null() {
        return;
    }

    let internal = matchy_t::as_internal(db);
    let rust_stats = internal.database.stats();

    *stats = matchy_stats_t {
        total_queries: rust_stats.total_queries,
        queries_with_match: rust_stats.queries_with_match,
        queries_without_match: rust_stats.queries_without_match,
        cache_hits: rust_stats.cache_hits,
        cache_misses: rust_stats.cache_misses,
        ip_queries: rust_stats.ip_queries,
        string_queries: rust_stats.string_queries,
    };
}

/// Clear the query cache
///
/// Removes all cached query results. Useful for benchmarking or
/// forcing fresh lookups.
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
///
/// # Example
/// ```c
/// // Do some queries (fills cache)
/// matchy_query(db, "example.com");
///
/// // Clear cache to force fresh lookups
/// matchy_clear_cache(db);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_clear_cache(db: *const matchy_t) {
    if db.is_null() {
        return;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.clear_cache();
}

/// Close database
///
/// Closes the database and frees all associated resources.
///
/// # Parameters
/// * `db` - Database handle (may be NULL)
///
/// # Safety
/// * `db` must be NULL or a valid pointer from matchy_open
/// * Must not be used after calling this function
/// * Calling with NULL is safe (no-op)
///
/// # Example
/// ```c
/// matchy_close(db);
/// db = NULL;  // Good practice
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_close(db: *mut matchy_t) {
    if !db.is_null() {
        let _ = matchy_t::into_internal(db);
    }
}

/// Unified query interface - automatically detects IP vs pattern
///
/// Queries the database with an IP address or pattern. The function automatically
/// detects the query type and uses the appropriate lookup method.
///
/// Returns structured data as DataValue (cached internally).
/// Use matchy_result_get_entry() to access structured data,
/// or matchy_result_to_json() to convert to JSON.
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
/// * `query` - IP address or pattern to search (null-terminated C string, must not be NULL)
///
/// # Returns
/// * matchy_result_t with found=true if match found
/// * matchy_result_t with found=false if no match
/// * Caller must free result with matchy_free_result
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
/// * `query` must be a valid null-terminated C string
///
/// # Example
/// ```c
/// matchy_result_t result = matchy_query(db, "1.2.3.4");
/// if (result.found) {
///     // Option 1: Get as JSON
///     char *json = matchy_result_to_json(&result);
///     printf("Found: %s\n", json);
///     matchy_free_string(json);
///     
///     // Option 2: Access structured data
///     matchy_entry_s entry;
///     matchy_result_get_entry(&result, &entry);
///     // ... use matchy_aget_value()
/// }
/// matchy_free_result(&result);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_query(
    db: *const matchy_t,
    query: *const c_char,
) -> matchy_result_t {
    let empty_result = matchy_result_t {
        found: false,
        prefix_len: 0,
        _result_type: 0,
        _data_offset: 0,
        _db_ref: ptr::null(),
    };

    if db.is_null() || query.is_null() {
        return empty_result;
    }

    let query_str = match CStr::from_ptr(query).to_str() {
        Ok(s) => s,
        Err(_) => return empty_result,
    };

    let internal = matchy_t::as_internal(db);
    match internal.database.lookup_ref(query_str) {
        Ok(lookup_ref) if lookup_ref.found => matchy_result_t {
            found: true,
            prefix_len: lookup_ref.prefix_len,
            _result_type: lookup_ref.result_type,
            _data_offset: lookup_ref.data_offset,
            _db_ref: db,
        },
        _ => empty_result,
    }
}

/// Unified query interface - writes result into provided struct pointer
///
/// Same as matchy_query but writes to a provided pointer instead of returning by value.
/// This is more FFI-friendly for some languages/platforms (like Java JNA on ARM64).
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
/// * `query` - IP address or pattern to search (null-terminated C string, must not be NULL)
/// * `result` - Pointer to result struct to fill (must not be NULL)
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
/// * `query` must be a valid null-terminated C string
/// * `result` must be a valid pointer to a matchy_result_t
///
/// # Example
/// ```c
/// matchy_result_t result;
/// matchy_query_into(db, "1.2.3.4", &result);
/// if (result.found) {
///     // Use result...
/// }
/// matchy_free_result(&result);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_query_into(
    db: *const matchy_t,
    query: *const c_char,
    result: *mut matchy_result_t,
) {
    if result.is_null() {
        return;
    }
    *result = matchy_query(db, query);
}

/// Free query result (no-op in zero-allocation API)
///
/// This function exists for ABI compatibility but does nothing since
/// matchy_result_t now uses offsets instead of heap-allocated data.
///
/// # Parameters
/// * `result` - Pointer to result from matchy_query (may be NULL)
///
/// # Safety
/// * Safe to call with any pointer including NULL
#[no_mangle]
pub unsafe extern "C" fn matchy_free_result(_result: *mut matchy_result_t) {
    // No-op: matchy_result_t now stores offsets, not heap pointers
}

/// Free a string returned by matchy
///
/// # Parameters
/// * `string` - String pointer returned by matchy (may be NULL)
///
/// # Safety
/// * `string` must be NULL or a pointer returned by matchy
/// * Must not be called twice on the same pointer
#[no_mangle]
pub unsafe extern "C" fn matchy_free_string(string: *mut c_char) {
    if !string.is_null() {
        let _ = CString::from_raw(string);
    }
}

/// Get library version string
///
/// # Returns
/// * Version string (e.g., "0.4.0")
/// * Pointer is valid for program lifetime, do not free
#[no_mangle]
pub extern "C" fn matchy_version() -> *const c_char {
    // Use the version from Cargo.toml, automatically updated at compile time
    concat!(env!("CARGO_PKG_VERSION"), "\0")
        .as_ptr()
        .cast::<c_char>()
}

/// Get database format description
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * Format string ("IP database", "Pattern database", or "Combined IP+Pattern database")
/// * Pointer is valid for database lifetime, do not free
/// * NULL if db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_format(db: *const matchy_t) -> *const c_char {
    if db.is_null() {
        return ptr::null();
    }

    let internal = matchy_t::as_internal(db);
    let format_str = internal.database.format();
    format_str.as_ptr().cast::<c_char>()
}

/// Check if database supports IP address lookups
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * true if database contains IP data
/// * false if not or if db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_has_ip_data(db: *const matchy_t) -> bool {
    if db.is_null() {
        return false;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.has_ip_data()
}

/// Check if database supports string lookups (literals or globs)
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * true if database contains literal or glob data
/// * false if not or if db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_has_string_data(db: *const matchy_t) -> bool {
    if db.is_null() {
        return false;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.has_string_data()
}

/// Check if database supports literal (exact string) lookups
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * true if database contains literal hash data
/// * false if not or if db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_has_literal_data(db: *const matchy_t) -> bool {
    if db.is_null() {
        return false;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.has_literal_data()
}

/// Check if database supports glob pattern lookups
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * true if database contains glob pattern data
/// * false if not or if db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_has_glob_data(db: *const matchy_t) -> bool {
    if db.is_null() {
        return false;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.has_glob_data()
}

/// Check if database supports pattern matching (deprecated)
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * true if database contains pattern data
/// * false if not or if db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
///
/// # Deprecated
/// Use matchy_has_literal_data or matchy_has_glob_data instead
#[no_mangle]
#[deprecated(
    since = "0.5.0",
    note = "Use matchy_has_literal_data or matchy_has_glob_data instead"
)]
pub unsafe extern "C" fn matchy_has_pattern_data(db: *const matchy_t) -> bool {
    if db.is_null() {
        return false;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.has_string_data()
}

/// Get database metadata as JSON string
///
/// Returns MMDB metadata if available (for IP or combined databases).
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * JSON string containing metadata (caller must free with matchy_free_string)
/// * NULL if no metadata available or db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_metadata(db: *const matchy_t) -> *mut c_char {
    if db.is_null() {
        return ptr::null_mut();
    }

    let internal = matchy_t::as_internal(db);
    match internal.database.metadata() {
        Some(metadata) => {
            // Convert metadata to JSON string
            match serde_json::to_string(&metadata) {
                Ok(json_str) => match CString::new(json_str) {
                    Ok(c_str) => c_str.into_raw(),
                    Err(_) => ptr::null_mut(),
                },
                Err(_) => ptr::null_mut(),
            }
        }
        None => ptr::null_mut(),
    }
}

/// Get pattern string by ID
///
/// Returns the pattern string for a given pattern ID.
/// Only works for pattern or combined databases.
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
/// * `pattern_id` - Pattern ID
///
/// # Returns
/// * Pattern string (caller must free with matchy_free_string)
/// * NULL if pattern ID not found or db has no patterns
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_get_pattern_string(
    db: *const matchy_t,
    pattern_id: u32,
) -> *mut c_char {
    if db.is_null() {
        return ptr::null_mut();
    }

    let internal = matchy_t::as_internal(db);

    // Get pattern string from database
    if let Some(pattern_str) = internal.database.get_pattern_string(pattern_id) {
        match CString::new(pattern_str) {
            Ok(c_str) => return c_str.into_raw(),
            Err(_) => return ptr::null_mut(),
        }
    }

    ptr::null_mut()
}

/// Get total number of patterns in database
///
/// Returns the number of patterns in the database.
/// Only works for pattern or combined databases.
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * Number of patterns (0 if no patterns or db is NULL)
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
#[no_mangle]
pub unsafe extern "C" fn matchy_pattern_count(db: *const matchy_t) -> usize {
    if db.is_null() {
        return 0;
    }

    let internal = matchy_t::as_internal(db);
    internal.database.pattern_count()
}

// ============================================================================
// ENHANCED API - STRUCTURED DATA ACCESS
// ============================================================================

/// MMDB data type constants (matching libmaxminddb)
/// Extended type marker (internal use)
pub const MATCHY_DATA_TYPE_EXTENDED: u32 = 0;
/// Pointer type for data section references
pub const MATCHY_DATA_TYPE_POINTER: u32 = 1;
/// UTF-8 encoded string
pub const MATCHY_DATA_TYPE_UTF8_STRING: u32 = 2;
/// Double precision float (64-bit)
pub const MATCHY_DATA_TYPE_DOUBLE: u32 = 3;
/// Byte array / binary data
pub const MATCHY_DATA_TYPE_BYTES: u32 = 4;
/// Unsigned 16-bit integer
pub const MATCHY_DATA_TYPE_UINT16: u32 = 5;
/// Unsigned 32-bit integer
pub const MATCHY_DATA_TYPE_UINT32: u32 = 6;
/// Map/dictionary type
pub const MATCHY_DATA_TYPE_MAP: u32 = 7;
/// Signed 32-bit integer
pub const MATCHY_DATA_TYPE_INT32: u32 = 8;
/// Unsigned 64-bit integer
pub const MATCHY_DATA_TYPE_UINT64: u32 = 9;
/// Unsigned 128-bit integer
pub const MATCHY_DATA_TYPE_UINT128: u32 = 10;
/// Array type
pub const MATCHY_DATA_TYPE_ARRAY: u32 = 11;
/// Boolean type
pub const MATCHY_DATA_TYPE_BOOLEAN: u32 = 14;
/// Single precision float (32-bit)
pub const MATCHY_DATA_TYPE_FLOAT: u32 = 15;

/// Additional error codes for structured data API
/// Invalid lookup path specified
pub const MATCHY_ERROR_LOOKUP_PATH_INVALID: i32 = -7;
/// No data available at the specified path
pub const MATCHY_ERROR_NO_DATA: i32 = -8;
/// Failed to parse data value
pub const MATCHY_ERROR_DATA_PARSE: i32 = -9;

/// Entry data union (matches MMDB layout for compatibility)
#[repr(C)]
#[derive(Copy, Clone)]
pub union matchy_entry_data_value_u {
    /// Pointer to data section offset
    pub pointer: u32,
    /// Null-terminated UTF-8 string pointer
    pub utf8_string: *const c_char,
    /// 64-bit floating point value
    pub double_value: f64,
    /// Pointer to byte array
    pub bytes: *const u8,
    /// 16-bit unsigned integer value
    pub uint16: u16,
    /// 32-bit unsigned integer value
    pub uint32: u32,
    /// 32-bit signed integer value
    pub int32: i32,
    /// 64-bit unsigned integer value
    pub uint64: u64,
    /// 128-bit unsigned integer value (as byte array)
    pub uint128: [u8; 16],
    /// Boolean value
    pub boolean: bool,
    /// 32-bit floating point value
    pub float_value: f32,
}

/// Entry data structure (like MMDB_entry_data_s)
#[repr(C)]
pub struct matchy_entry_data_t {
    /// Whether data was found
    pub has_data: bool,
    /// Data type (one of MATCHY_DATA_TYPE_* constants)
    pub type_: u32,
    /// Actual data value
    pub value: matchy_entry_data_value_u,
    /// Size in bytes (for strings, bytes, maps, arrays)
    pub data_size: u32,
    /// Internal offset (for debugging)
    pub offset: u32,
}

/// Entry handle (like MMDB_entry_s)
#[repr(C)]
pub struct matchy_entry_s {
    /// Database handle
    pub db: *const matchy_t,
    /// Data offset into MMDB data section
    pub _data_offset: u32,
}

/// Entry data list node (like MMDB_entry_data_list_s)
#[repr(C)]
pub struct matchy_entry_data_list_t {
    /// The entry data for this node
    pub entry_data: matchy_entry_data_t,
    /// Pointer to the next node in the list (NULL if last)
    pub next: *mut Self,
}

impl matchy_entry_data_t {
    /// Create empty entry data
    fn empty() -> Self {
        Self {
            has_data: false,
            type_: 0,
            value: matchy_entry_data_value_u { uint32: 0 },
            data_size: 0,
            offset: 0,
        }
    }

    /// Convert DataValue to entry_data_t
    /// Strings are stored in the cache to keep them alive
    unsafe fn from_data_value(value: &DataValue, string_cache: &mut Vec<CString>) -> Option<Self> {
        let (type_, data_value, data_size) = match value {
            DataValue::Pointer(offset) => (
                MATCHY_DATA_TYPE_POINTER,
                matchy_entry_data_value_u { pointer: *offset },
                0,
            ),
            DataValue::String(s) => {
                let c_str = CString::new(s.as_str()).ok()?;
                let ptr = c_str.as_ptr();
                string_cache.push(c_str);
                (
                    MATCHY_DATA_TYPE_UTF8_STRING,
                    matchy_entry_data_value_u { utf8_string: ptr },
                    u32::try_from(s.len()).unwrap_or(u32::MAX),
                )
            }
            DataValue::Double(d) => (
                MATCHY_DATA_TYPE_DOUBLE,
                matchy_entry_data_value_u { double_value: *d },
                8,
            ),
            DataValue::Bytes(b) => {
                let ptr = b.as_ptr();
                (
                    MATCHY_DATA_TYPE_BYTES,
                    matchy_entry_data_value_u { bytes: ptr },
                    u32::try_from(b.len()).unwrap_or(u32::MAX),
                )
            }
            DataValue::Uint16(n) => (
                MATCHY_DATA_TYPE_UINT16,
                matchy_entry_data_value_u { uint16: *n },
                2,
            ),
            DataValue::Uint32(n) => (
                MATCHY_DATA_TYPE_UINT32,
                matchy_entry_data_value_u { uint32: *n },
                4,
            ),
            DataValue::Map(m) => (
                MATCHY_DATA_TYPE_MAP,
                matchy_entry_data_value_u { uint32: 0 },
                u32::try_from(m.len()).unwrap_or(u32::MAX),
            ),
            DataValue::Int32(n) => (
                MATCHY_DATA_TYPE_INT32,
                matchy_entry_data_value_u { int32: *n },
                4,
            ),
            DataValue::Uint64(n) => (
                MATCHY_DATA_TYPE_UINT64,
                matchy_entry_data_value_u { uint64: *n },
                8,
            ),
            DataValue::Uint128(n) => {
                let bytes = n.to_be_bytes();
                (
                    MATCHY_DATA_TYPE_UINT128,
                    matchy_entry_data_value_u { uint128: bytes },
                    16,
                )
            }
            DataValue::Array(a) => (
                MATCHY_DATA_TYPE_ARRAY,
                matchy_entry_data_value_u { uint32: 0 },
                u32::try_from(a.len()).unwrap_or(u32::MAX),
            ),
            DataValue::Bool(b) => (
                MATCHY_DATA_TYPE_BOOLEAN,
                matchy_entry_data_value_u { boolean: *b },
                1,
            ),
            DataValue::Float(f) => (
                MATCHY_DATA_TYPE_FLOAT,
                matchy_entry_data_value_u { float_value: *f },
                4,
            ),
            DataValue::Timestamp(epoch) => {
                let iso = chrono::Utc
                    .timestamp_opt(*epoch, 0)
                    .single()
                    .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
                    .unwrap_or_else(|| format!("{epoch}"));
                let c_str = CString::new(iso.as_str()).ok()?;
                let ptr = c_str.as_ptr();
                let len = iso.len();
                string_cache.push(c_str);
                (
                    MATCHY_DATA_TYPE_UTF8_STRING,
                    matchy_entry_data_value_u { utf8_string: ptr },
                    u32::try_from(len).unwrap_or(u32::MAX),
                )
            }
        };

        Some(Self {
            has_data: true,
            type_,
            value: data_value,
            data_size,
            offset: 0,
        })
    }
}

/// Navigate into DataValue using a path of string keys
fn navigate_path<'a>(mut value: &'a DataValue, path: &[&str]) -> Option<&'a DataValue> {
    for key in path {
        match value {
            DataValue::Map(m) => {
                value = m.get(*key)?;
            }
            DataValue::Array(a) => {
                // Try to parse key as array index
                let idx: usize = key.parse().ok()?;
                value = a.get(idx)?;
            }
            _ => return None,
        }
    }
    Some(value)
}

/// Get entry handle from query result
///
/// This extracts the entry handle which can be used for data navigation.
///
/// # Parameters
/// * `result` - Query result (must not be NULL, must have found=true)
/// * `entry` - Output entry handle (must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS on success
/// * MATCHY_ERROR_NO_DATA if result not found
/// * MATCHY_ERROR_INVALID_PARAM if parameters invalid
///
/// # Safety
/// * `result` must be valid result from matchy_query
/// * `entry` must be valid pointer to output struct
/// * Result must not have been freed
///
/// # Example
/// ```c
/// matchy_result_t result = matchy_query(db, "8.8.8.8");
/// if (result.found) {
///     matchy_entry_s entry;
///     matchy_result_get_entry(&result, &entry);
/// }
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_result_get_entry(
    result: *const matchy_result_t,
    entry: *mut matchy_entry_s,
) -> i32 {
    if result.is_null() || entry.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let res = &*result;
    if !res.found {
        return MATCHY_ERROR_NO_DATA;
    }

    (*entry).db = res._db_ref;
    (*entry)._data_offset = res._data_offset;

    MATCHY_SUCCESS
}

// Note: Full varargs support (matchy_get_value) should be provided as a C macro
// or wrapper function that calls matchy_aget_value. For now, we provide the
// array-based version which is more portable.

/// Get value using array of strings for path
///
/// Like matchy_get_value but takes an array of strings instead of varargs.
///
/// # Parameters
/// * `entry` - Entry handle
/// * `entry_data` - Output data
/// * `path` - NULL-terminated array of string pointers
///
/// # Returns
/// * Same as matchy_get_value
///
/// # Safety
/// * Same as matchy_get_value
/// * `path` must be NULL-terminated array
///
/// # Example
/// ```c
/// const char *path[] = {"country", "iso_code", NULL};
/// matchy_aget_value(&entry, &data, path);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_aget_value(
    entry: *const matchy_entry_s,
    entry_data: *mut matchy_entry_data_t,
    path: *const *const c_char,
) -> i32 {
    if entry.is_null() || entry_data.is_null() || path.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let mut path_vec = Vec::new();
    let mut i = 0;
    loop {
        let ptr = *path.offset(i);
        if ptr.is_null() {
            break;
        }
        match CStr::from_ptr(ptr).to_str() {
            Ok(s) => path_vec.push(s),
            Err(_) => return MATCHY_ERROR_INVALID_PARAM,
        }
        i += 1;
    }

    let db = (*entry).db;
    if db.is_null() {
        (*entry_data) = matchy_entry_data_t::empty();
        return MATCHY_ERROR_NO_DATA;
    }

    let internal = matchy_t::as_internal(db);
    let data = match internal.database.decode_at_offset((*entry)._data_offset) {
        Ok(d) => d,
        Err(_) => {
            (*entry_data) = matchy_entry_data_t::empty();
            return MATCHY_ERROR_DATA_PARSE;
        }
    };

    let target = match navigate_path(&data, &path_vec) {
        Some(v) => v,
        None => {
            (*entry_data) = matchy_entry_data_t::empty();
            return MATCHY_ERROR_LOOKUP_PATH_INVALID;
        }
    };

    let mut string_cache = Vec::new();
    match matchy_entry_data_t::from_data_value(target, &mut string_cache) {
        Some(d) => {
            (*entry_data) = d;
            std::mem::forget(string_cache);
            MATCHY_SUCCESS
        }
        None => {
            (*entry_data) = matchy_entry_data_t::empty();
            MATCHY_ERROR_DATA_PARSE
        }
    }
}

/// Get full entry data as linked list (tree traversal)
///
/// This function traverses the entire data structure and returns it as
/// a flattened linked list. Maps and arrays are expanded recursively.
///
/// # Parameters
/// * `entry` - Entry handle
/// * `entry_data_list` - Output list pointer
///
/// # Returns
/// * MATCHY_SUCCESS on success
/// * Error code on failure
///
/// # Safety
/// * `entry` must be valid
/// * `entry_data_list` must be valid pointer
/// * Caller must free result with matchy_free_entry_data_list
///
/// # Example
/// ```c
/// matchy_entry_data_list_t *list = NULL;
/// if (matchy_get_entry_data_list(&entry, &list) == MATCHY_SUCCESS) {
///     for (matchy_entry_data_list_t *p = list; p != NULL; p = p->next) {
///         // Process p->entry_data
///     }
///     matchy_free_entry_data_list(list);
/// }
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_get_entry_data_list(
    entry: *const matchy_entry_s,
    entry_data_list: *mut *mut matchy_entry_data_list_t,
) -> i32 {
    if entry.is_null() || entry_data_list.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let db = (*entry).db;
    if db.is_null() {
        return MATCHY_ERROR_NO_DATA;
    }

    let internal = matchy_t::as_internal(db);
    let data = match internal.database.decode_at_offset((*entry)._data_offset) {
        Ok(d) => d,
        Err(_) => return MATCHY_ERROR_DATA_PARSE,
    };
    let mut string_cache = Vec::new();
    let mut list_head: *mut matchy_entry_data_list_t = ptr::null_mut();
    let mut list_tail: *mut matchy_entry_data_list_t = ptr::null_mut();

    // Helper to add a node to the list
    let mut add_node = |entry_data: matchy_entry_data_t| {
        let node = Box::new(matchy_entry_data_list_t {
            entry_data,
            next: ptr::null_mut(),
        });
        let node_ptr = Box::into_raw(node);

        if list_head.is_null() {
            list_head = node_ptr;
            list_tail = node_ptr;
        } else {
            (*list_tail).next = node_ptr;
            list_tail = node_ptr;
        }
    };

    // Flatten the data structure recursively
    fn flatten_data(
        value: &DataValue,
        string_cache: &mut Vec<CString>,
        add_node: &mut impl FnMut(matchy_entry_data_t),
    ) {
        // Add the current node
        if let Some(entry_data) =
            // SAFETY: from_data_value only reads from value and appends to string_cache
            unsafe { matchy_entry_data_t::from_data_value(value, string_cache) }
        {
            add_node(entry_data);
        }

        // Recursively add children
        match value {
            DataValue::Map(m) => {
                for (_key, val) in m.iter() {
                    flatten_data(val, string_cache, add_node);
                }
            }
            DataValue::Array(a) => {
                for val in a.iter() {
                    flatten_data(val, string_cache, add_node);
                }
            }
            _ => {}
        }
    }

    flatten_data(&data, &mut string_cache, &mut add_node);

    // Leak the string cache so pointers remain valid
    std::mem::forget(string_cache);

    *entry_data_list = list_head;
    MATCHY_SUCCESS
}

/// Free entry data list
///
/// Frees the linked list returned by matchy_get_entry_data_list.
///
/// # Parameters
/// * `list` - List to free (may be NULL)
///
/// # Safety
/// * `list` must be from matchy_get_entry_data_list or NULL
/// * Must not be freed twice
#[no_mangle]
pub unsafe extern "C" fn matchy_free_entry_data_list(list: *mut matchy_entry_data_list_t) {
    if list.is_null() {
        return;
    }

    let mut current = list;
    while !current.is_null() {
        let next = (*current).next;
        let _ = Box::from_raw(current);
        current = next;
    }
}

// ============================================================================
// CONVENIENCE FUNCTIONS
// ============================================================================

/// Get the update URL from database metadata
///
/// Returns the update URL stored in the database metadata (if any).
/// This is set during database build with matchy_builder_set_update_url().
///
/// # Parameters
/// * `db` - Database handle (must not be NULL)
///
/// # Returns
/// * URL string (caller must free with matchy_free_string)
/// * NULL if no update URL is set or db is NULL
///
/// # Safety
/// * `db` must be a valid pointer from matchy_open
///
/// # Example
/// ```c
/// char *url = matchy_get_update_url(db);
/// if (url) {
///     printf("Update URL: %s\n", url);
///     matchy_free_string(url);
/// }
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_get_update_url(db: *const matchy_t) -> *mut c_char {
    if db.is_null() {
        return ptr::null_mut();
    }

    let internal = matchy_t::as_internal(db);
    match internal.database.update_url() {
        Some(url) => match CString::new(url) {
            Ok(c_str) => c_str.into_raw(),
            Err(_) => ptr::null_mut(),
        },
        None => ptr::null_mut(),
    }
}

/// Check if auto-update feature is available
///
/// Returns whether the library was compiled with auto-update support.
/// When auto-update is available, you can set auto_update=true in
/// matchy_open_options_t to enable automatic background updates.
///
/// # Returns
/// * true if auto-update feature is compiled in
/// * false if not available (updates from URL will not work)
///
/// # Example
/// ```c
/// if (matchy_has_auto_update()) {
///     opts.auto_update = true;
///     opts.update_interval_secs = 3600;  // Check hourly
/// }
/// ```
#[no_mangle]
pub extern "C" fn matchy_has_auto_update() -> bool {
    #[cfg(feature = "auto-update")]
    {
        true
    }
    #[cfg(not(feature = "auto-update"))]
    {
        false
    }
}

/// Convert query result data to JSON string
///
/// This is a convenience function to convert the structured DataValue
/// to a JSON string for simple use cases.
///
/// # Parameters
/// * `result` - Query result (must not be NULL, must have found=true)
///
/// # Returns
/// * JSON string (caller must free with matchy_free_string)
/// * NULL if result is NULL, not found, or conversion fails
///
/// # Safety
/// * `result` must be a valid pointer to a result from matchy_query
/// * Result must not have been freed
///
/// # Example
/// ```c
/// matchy_result_t result = matchy_query(db, "8.8.8.8");
/// if (result.found) {
///     char *json = matchy_result_to_json(&result);
///     if (json) {
///         printf("Data: %s\n", json);
///         matchy_free_string(json);
///     }
/// }
/// matchy_free_result(&result);
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_result_to_json(result: *const matchy_result_t) -> *mut c_char {
    if result.is_null() || !(*result).found || (*result)._db_ref.is_null() {
        return ptr::null_mut();
    }

    let internal = matchy_t::as_internal((*result)._db_ref);
    let data = match internal.database.decode_at_offset((*result)._data_offset) {
        Ok(d) => d,
        Err(_) => return ptr::null_mut(),
    };

    let json_str = match serde_json::to_string(&data) {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };

    match CString::new(json_str) {
        Ok(c_str) => c_str.into_raw(),
        Err(_) => ptr::null_mut(),
    }
}

// ============================================================================
// VALIDATION API
// ============================================================================

/// Standard validation level - all offsets, UTF-8, basic structure
pub const MATCHY_VALIDATION_STANDARD: i32 = 0;
/// Strict validation level - standard plus deep graph analysis and consistency checks (default)
pub const MATCHY_VALIDATION_STRICT: i32 = 1;

/// Validate a database file
///
/// Validates a .mxy database file to ensure it's safe to use.
/// Returns MATCHY_SUCCESS if the database is valid, or an error code if invalid.
///
/// # Parameters
/// * `filename` - Path to database file (null-terminated C string, must not be NULL)
/// * `level` - Validation level (MATCHY_VALIDATION_STANDARD or _STRICT)
/// * `error_message` - Pointer to receive error message (may be NULL if not needed)
///   If non-NULL and validation fails, receives a string that must be freed with matchy_free_string
///
/// # Returns
/// * MATCHY_SUCCESS (0) if database is valid
/// * Error code < 0 if validation failed or parameters invalid
///
/// # Safety
/// * `filename` must be a valid null-terminated C string
/// * If `error_message` is non-NULL, caller must free the returned string
///
/// # Example
/// ```c
/// char *error = NULL;
/// int result = matchy_validate("/path/to/database.mxy", MATCHY_VALIDATION_STRICT, &error);
/// if (result != MATCHY_SUCCESS) {
///     fprintf(stderr, "Validation failed: %s\n", error ? error : "unknown error");
///     if (error) matchy_free_string(error);
///     return 1;
/// }
/// printf("Database is valid and safe to use!\n");
/// ```
#[no_mangle]
pub unsafe extern "C" fn matchy_validate(
    filename: *const c_char,
    level: i32,
    error_message: *mut *mut c_char,
) -> i32 {
    use crate::validation::{validate_database, ValidationLevel};
    use std::path::Path;

    if filename.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let path_str = match CStr::from_ptr(filename).to_str() {
        Ok(s) => s,
        Err(_) => return MATCHY_ERROR_INVALID_PARAM,
    };

    let validation_level = match level {
        MATCHY_VALIDATION_STANDARD => ValidationLevel::Standard,
        MATCHY_VALIDATION_STRICT => ValidationLevel::Strict,
        _ => return MATCHY_ERROR_INVALID_PARAM,
    };

    match validate_database(Path::new(path_str), validation_level) {
        Ok(report) => {
            if report.is_valid() {
                MATCHY_SUCCESS
            } else {
                // Validation failed - populate error message if requested
                if !error_message.is_null() {
                    let error_text = if report.errors.is_empty() {
                        "Validation failed (no error details)".to_string()
                    } else {
                        report.errors.join("; ")
                    };

                    if let Ok(c_str) = CString::new(error_text) {
                        *error_message = c_str.into_raw();
                    } else {
                        *error_message = ptr::null_mut();
                    }
                }
                MATCHY_ERROR_CORRUPT_DATA
            }
        }
        Err(_) => {
            if !error_message.is_null() {
                if let Ok(c_str) = CString::new("Failed to validate database") {
                    *error_message = c_str.into_raw();
                }
            }
            MATCHY_ERROR_IO
        }
    }
}

// ============================================================================
// EXTRACTOR API
// ============================================================================

use crate::extractor::{ExtractedItem, Extractor, ExtractorBuilder, HashType};

// Extraction flags (bitmask)
/// Extract domain names (e.g., "example.com")
pub const MATCHY_EXTRACT_DOMAINS: u32 = 1 << 0;
/// Extract email addresses (e.g., "user@example.com")
pub const MATCHY_EXTRACT_EMAILS: u32 = 1 << 1;
/// Extract IPv4 addresses
pub const MATCHY_EXTRACT_IPV4: u32 = 1 << 2;
/// Extract IPv6 addresses
pub const MATCHY_EXTRACT_IPV6: u32 = 1 << 3;
/// Extract file hashes (MD5, SHA1, SHA256, SHA384, SHA512)
pub const MATCHY_EXTRACT_HASHES: u32 = 1 << 4;
/// Extract Bitcoin addresses
pub const MATCHY_EXTRACT_BITCOIN: u32 = 1 << 5;
/// Extract Ethereum addresses
pub const MATCHY_EXTRACT_ETHEREUM: u32 = 1 << 6;
/// Extract Monero addresses
pub const MATCHY_EXTRACT_MONERO: u32 = 1 << 7;
/// Extract all supported types
pub const MATCHY_EXTRACT_ALL: u32 = 0xFF;

// Item type constants (returned in match results)
/// Domain name
pub const MATCHY_ITEM_TYPE_DOMAIN: u8 = 0;
/// Email address
pub const MATCHY_ITEM_TYPE_EMAIL: u8 = 1;
/// IPv4 address
pub const MATCHY_ITEM_TYPE_IPV4: u8 = 2;
/// IPv6 address
pub const MATCHY_ITEM_TYPE_IPV6: u8 = 3;
/// MD5 hash (32 hex characters)
pub const MATCHY_ITEM_TYPE_MD5: u8 = 4;
/// SHA1 hash (40 hex characters)
pub const MATCHY_ITEM_TYPE_SHA1: u8 = 5;
/// SHA256 hash (64 hex characters)
pub const MATCHY_ITEM_TYPE_SHA256: u8 = 6;
/// SHA384 hash (96 hex characters)
pub const MATCHY_ITEM_TYPE_SHA384: u8 = 7;
/// SHA512 hash (128 hex characters)
pub const MATCHY_ITEM_TYPE_SHA512: u8 = 8;
/// Bitcoin address
pub const MATCHY_ITEM_TYPE_BITCOIN: u8 = 9;
/// Ethereum address
pub const MATCHY_ITEM_TYPE_ETHEREUM: u8 = 10;
/// Monero address
pub const MATCHY_ITEM_TYPE_MONERO: u8 = 11;

/// Opaque extractor handle
#[repr(C)]
pub struct matchy_extractor_t {
    _private: [u8; 0],
}

/// A single extracted match
#[repr(C)]
pub struct matchy_match_t {
    /// Item type (one of MATCHY_ITEM_TYPE_* constants)
    pub item_type: u8,
    /// The extracted value as a null-terminated string
    /// Valid for the lifetime of the matchy_matches_t
    pub value: *const c_char,
    /// Byte offset where the match starts in the input
    pub start: usize,
    /// Byte offset where the match ends in the input (exclusive)
    pub end: usize,
}

/// Array of extracted matches
#[repr(C)]
pub struct matchy_matches_t {
    /// Pointer to array of matches
    pub items: *const matchy_match_t,
    /// Number of matches
    pub count: usize,
    /// Internal pointer (do not use)
    _internal: *mut c_void,
}

// Internal storage for matches (keeps strings alive)
struct MatchesInternal {
    matches: Vec<matchy_match_t>,
    #[allow(dead_code)] // Kept to extend CString lifetimes for FFI pointers
    strings: Vec<CString>,
}

impl matchy_extractor_t {
    fn from_internal(internal: Box<Extractor>) -> *mut Self {
        Box::into_raw(internal).cast::<Self>()
    }

    unsafe fn to_internal(ptr: *mut Self) -> Box<Extractor> {
        Box::from_raw(ptr.cast::<Extractor>())
    }

    unsafe fn as_internal(ptr: *const Self) -> &'static Extractor {
        &*ptr.cast::<Extractor>()
    }
}

/// Get item type constant from ExtractedItem
fn item_type_from_extracted(item: &ExtractedItem) -> u8 {
    match item {
        ExtractedItem::Domain(_) => MATCHY_ITEM_TYPE_DOMAIN,
        ExtractedItem::Email(_) => MATCHY_ITEM_TYPE_EMAIL,
        ExtractedItem::Ipv4(_) => MATCHY_ITEM_TYPE_IPV4,
        ExtractedItem::Ipv6(_) => MATCHY_ITEM_TYPE_IPV6,
        ExtractedItem::Hash(HashType::Md5, _) => MATCHY_ITEM_TYPE_MD5,
        ExtractedItem::Hash(HashType::Sha1, _) => MATCHY_ITEM_TYPE_SHA1,
        ExtractedItem::Hash(HashType::Sha256, _) => MATCHY_ITEM_TYPE_SHA256,
        ExtractedItem::Hash(HashType::Sha384, _) => MATCHY_ITEM_TYPE_SHA384,
        ExtractedItem::Hash(HashType::Sha512, _) => MATCHY_ITEM_TYPE_SHA512,
        ExtractedItem::Bitcoin(_) => MATCHY_ITEM_TYPE_BITCOIN,
        ExtractedItem::Ethereum(_) => MATCHY_ITEM_TYPE_ETHEREUM,
        ExtractedItem::Monero(_) => MATCHY_ITEM_TYPE_MONERO,
    }
}

/// Create an extractor with specified extraction types
///
/// # Parameters
/// * `flags` - Bitmask of MATCHY_EXTRACT_* flags specifying what to extract
///
/// # Returns
/// * Non-null extractor handle on success
/// * NULL on failure
///
/// # Example
/// ```c
/// // Extract everything
/// matchy_extractor_t *ext = matchy_extractor_create(MATCHY_EXTRACT_ALL);
///
/// // Extract only domains and IPs
/// matchy_extractor_t *ext = matchy_extractor_create(
///     MATCHY_EXTRACT_DOMAINS | MATCHY_EXTRACT_IPV4 | MATCHY_EXTRACT_IPV6
/// );
/// ```
#[no_mangle]
pub extern "C" fn matchy_extractor_create(flags: u32) -> *mut matchy_extractor_t {
    let builder = ExtractorBuilder::new()
        .extract_domains((flags & MATCHY_EXTRACT_DOMAINS) != 0)
        .extract_emails((flags & MATCHY_EXTRACT_EMAILS) != 0)
        .extract_ipv4((flags & MATCHY_EXTRACT_IPV4) != 0)
        .extract_ipv6((flags & MATCHY_EXTRACT_IPV6) != 0)
        .extract_hashes((flags & MATCHY_EXTRACT_HASHES) != 0)
        .extract_bitcoin((flags & MATCHY_EXTRACT_BITCOIN) != 0)
        .extract_ethereum((flags & MATCHY_EXTRACT_ETHEREUM) != 0)
        .extract_monero((flags & MATCHY_EXTRACT_MONERO) != 0);

    match builder.build() {
        Ok(extractor) => matchy_extractor_t::from_internal(Box::new(extractor)),
        Err(_) => ptr::null_mut(),
    }
}

/// Extract patterns from a chunk of data
///
/// Extracts all enabled pattern types (domains, IPs, emails, hashes, crypto)
/// from the input data in a single pass.
///
/// # Parameters
/// * `extractor` - Extractor handle (must not be NULL)
/// * `data` - Input data buffer (must not be NULL)
/// * `len` - Length of input data in bytes
/// * `matches` - Output matches structure (must not be NULL)
///
/// # Returns
/// * MATCHY_SUCCESS on success
/// * MATCHY_ERROR_INVALID_PARAM if any parameter is NULL
///
/// # Memory Management
/// Caller must free the matches with matchy_matches_free()
///
/// # Example
/// ```c
/// matchy_extractor_t *extractor = matchy_extractor_create(MATCHY_EXTRACT_ALL);
/// const char *text = "Check evil.com and 192.168.1.1";
/// matchy_matches_t matches;
///
/// if (matchy_extractor_extract_chunk(extractor, (const uint8_t *)text, strlen(text), &matches) == MATCHY_SUCCESS) {
///     for (size_t i = 0; i < matches.count; i++) {
///         printf("%s: %s\n",
///                matchy_item_type_name(matches.items[i].item_type),
///                matches.items[i].value);
///     }
///     matchy_matches_free(&matches);
/// }
/// matchy_extractor_free(extractor);
/// ```
///
/// # Safety
/// * `extractor` must be a valid pointer returned by `matchy_extractor_create`
/// * `data` must point to a valid buffer of at least `len` bytes
/// * `matches` must be a valid pointer to an uninitialized `matchy_matches_t`
#[no_mangle]
pub unsafe extern "C" fn matchy_extractor_extract_chunk(
    extractor: *const matchy_extractor_t,
    data: *const u8,
    len: usize,
    matches: *mut matchy_matches_t,
) -> i32 {
    if extractor.is_null() || data.is_null() || matches.is_null() {
        return MATCHY_ERROR_INVALID_PARAM;
    }

    let ext = matchy_extractor_t::as_internal(extractor);
    let chunk = slice::from_raw_parts(data, len);

    // Extract matches
    let rust_matches = ext.extract_from_chunk(chunk);

    // Convert to C representation
    let mut strings = Vec::with_capacity(rust_matches.len());
    let mut c_matches = Vec::with_capacity(rust_matches.len());

    for m in rust_matches {
        let value_str = m.item.as_value();
        let c_string = match CString::new(value_str) {
            Ok(s) => s,
            Err(_) => continue, // Skip invalid strings
        };

        c_matches.push(matchy_match_t {
            item_type: item_type_from_extracted(&m.item),
            value: c_string.as_ptr(),
            start: m.span.0,
            end: m.span.1,
        });
        strings.push(c_string);
    }

    // Store internal data and populate output
    let internal = Box::new(MatchesInternal {
        matches: c_matches,
        strings,
    });

    (*matches).items = internal.matches.as_ptr();
    (*matches).count = internal.matches.len();
    (*matches)._internal = Box::into_raw(internal).cast::<c_void>();

    MATCHY_SUCCESS
}

/// Free the matches returned by matchy_extractor_extract_chunk
///
/// # Parameters
/// * `matches` - Matches structure to free (must not be NULL)
///
/// # Safety
/// * Must not use the matches after calling this function
#[no_mangle]
pub unsafe extern "C" fn matchy_matches_free(matches: *mut matchy_matches_t) {
    if matches.is_null() {
        return;
    }

    if !(*matches)._internal.is_null() {
        let _ = Box::from_raw((*matches)._internal.cast::<MatchesInternal>());
        (*matches)._internal = ptr::null_mut();
        (*matches).items = ptr::null();
        (*matches).count = 0;
    }
}

/// Free the extractor
///
/// # Parameters
/// * `extractor` - Extractor handle (may be NULL)
///
/// # Safety
/// * Must not be used after calling this function
#[no_mangle]
pub unsafe extern "C" fn matchy_extractor_free(extractor: *mut matchy_extractor_t) {
    if !extractor.is_null() {
        let _ = matchy_extractor_t::to_internal(extractor);
    }
}

/// Get the string name for an item type constant
///
/// # Parameters
/// * `item_type` - One of the MATCHY_ITEM_TYPE_* constants
///
/// # Returns
/// * Static string like "Domain", "Email", "IPv4", etc.
/// * "Unknown" for invalid type values
///
/// # Note
/// The returned string is static and must not be freed.
#[no_mangle]
pub extern "C" fn matchy_item_type_name(item_type: u8) -> *const c_char {
    static DOMAIN: &[u8] = b"Domain\0";
    static EMAIL: &[u8] = b"Email\0";
    static IPV4: &[u8] = b"IPv4\0";
    static IPV6: &[u8] = b"IPv6\0";
    static MD5: &[u8] = b"MD5\0";
    static SHA1: &[u8] = b"SHA1\0";
    static SHA256: &[u8] = b"SHA256\0";
    static SHA384: &[u8] = b"SHA384\0";
    static SHA512: &[u8] = b"SHA512\0";
    static BITCOIN: &[u8] = b"Bitcoin\0";
    static ETHEREUM: &[u8] = b"Ethereum\0";
    static MONERO: &[u8] = b"Monero\0";
    static UNKNOWN: &[u8] = b"Unknown\0";

    let name = match item_type {
        MATCHY_ITEM_TYPE_DOMAIN => DOMAIN,
        MATCHY_ITEM_TYPE_EMAIL => EMAIL,
        MATCHY_ITEM_TYPE_IPV4 => IPV4,
        MATCHY_ITEM_TYPE_IPV6 => IPV6,
        MATCHY_ITEM_TYPE_MD5 => MD5,
        MATCHY_ITEM_TYPE_SHA1 => SHA1,
        MATCHY_ITEM_TYPE_SHA256 => SHA256,
        MATCHY_ITEM_TYPE_SHA384 => SHA384,
        MATCHY_ITEM_TYPE_SHA512 => SHA512,
        MATCHY_ITEM_TYPE_BITCOIN => BITCOIN,
        MATCHY_ITEM_TYPE_ETHEREUM => ETHEREUM,
        MATCHY_ITEM_TYPE_MONERO => MONERO,
        _ => UNKNOWN,
    };
    name.as_ptr().cast::<c_char>()
}