alec-ffi 1.3.10

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

//! C/C++ bindings for ALEC compression library
//!
//! This crate provides a C-compatible FFI layer for the ALEC compression
//! library, enabling use from C/C++ firmware and embedded systems.
//!
//! # Safety
//!
//! All functions in this module use raw pointers.
//! Callers must ensure:
//! - Pointers are valid and non-null (unless documented otherwise)
//! - Buffer sizes are accurate
//! - Handles are not used after being freed
//! - Thread safety is managed by the caller

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]

#[cfg(not(feature = "std"))]
extern crate alloc;

// Zephyr RTOS support: global allocator via k_malloc/k_free, no panic handler
#[cfg(feature = "zephyr")]
mod zephyr_support {
    use core::alloc::{GlobalAlloc, Layout};

    extern "C" {
        // k_aligned_alloc is required instead of k_malloc because k_malloc
        // returns 4-byte aligned memory on ARM. Rust types such as
        // Vec<(u16, f64)> and BTreeMap nodes require 8-byte alignment;
        // using k_malloc causes misaligned access (UB) on Cortex-M33.
        fn k_aligned_alloc(align: usize, size: usize) -> *mut u8;
        fn k_free(ptr: *mut u8);
    }

    struct ZephyrAllocator;

    unsafe impl GlobalAlloc for ZephyrAllocator {
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            unsafe { k_aligned_alloc(layout.align(), layout.size()) }
        }

        unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
            unsafe { k_free(ptr) }
        }
    }

    #[global_allocator]
    static ALLOCATOR: ZephyrAllocator = ZephyrAllocator;

    /// No-op on Zephyr — heap is managed by the RTOS.
    ///
    /// Provided for API compatibility with bare-metal builds.
    #[no_mangle]
    pub extern "C" fn alec_heap_init() {
        // Zephyr manages its own heap; nothing to do.
    }

    #[panic_handler]
    fn panic(_: &core::panic::PanicInfo) -> ! {
        loop {}
    }
}

// Bare-metal support: global allocator and panic handler
#[cfg(feature = "bare-metal")]
mod bare_metal_support {
    use embedded_alloc::LlffHeap as Heap;

    #[global_allocator]
    static HEAP: Heap = Heap::empty();

    /// Initialize the heap allocator. Must be called before any alloc usage.
    ///
    /// # Safety
    ///
    /// Must be called exactly once, before any heap allocation.
    #[no_mangle]
    pub unsafe extern "C" fn alec_heap_init() {
        const HEAP_SIZE: usize = 8192;
        static mut HEAP_MEM: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
        unsafe {
            HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE);
        }
    }

    /// Initialize the heap allocator with a caller-provided buffer.
    ///
    /// Required on RTOSes (FreeRTOS, Milesight firmware) where the heap
    /// region is managed by the integrator and must not be statically
    /// embedded in the ALEC library itself.
    ///
    /// # Arguments
    ///
    /// * `buf` - Pointer to the start of the heap region. Must remain
    ///   valid for the lifetime of the program. Must be non-NULL.
    /// * `len` - Size of the heap region in bytes. Must be > 0.
    ///
    /// # Safety
    ///
    /// * Must be called exactly once, before any ALEC allocation.
    /// * `buf` must point to `len` bytes of writable memory that stays
    ///   valid for the lifetime of the process.
    /// * This function must not be combined with `alec_heap_init()`.
    /// * No-op if `buf` is NULL or `len == 0`.
    #[no_mangle]
    pub unsafe extern "C" fn alec_heap_init_with_buffer(buf: *mut u8, len: usize) {
        if buf.is_null() || len == 0 {
            return;
        }
        unsafe {
            HEAP.init(buf as usize, len);
        }
    }

    #[panic_handler]
    fn panic(_info: &core::panic::PanicInfo) -> ! {
        loop {}
    }
}

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};

use core::ffi::{c_char, CStr};
use core::slice;
#[cfg(feature = "std")]
use std::path::Path;

use alec::classifier::Classifier;
use alec::context::{Context, ContextConfig};
use alec::protocol::{ChannelInput, RawData};
#[cfg(feature = "decoder")]
use alec::Decoder;
use alec::Encoder;

/// Key used when `observe()`-ing channel `i` in a fixed-channel frame.
/// Must match `Encoder::fixed_channel_source_id` — kept here because
/// that helper is `pub(crate)` inside the `alec` crate.
#[inline]
fn fixed_channel_source_id(i: usize) -> u32 {
    (i as u32) + 1
}

// ============================================================================
// Default configuration values (also documented in AlecEncoderConfig)
// ============================================================================

/// Default history size per source (validated on 99-message EM500-CO2 dataset).
pub const ALEC_DEFAULT_HISTORY_SIZE: u32 = 20;
/// Default maximum number of patterns retained in the dictionary.
pub const ALEC_DEFAULT_MAX_PATTERNS: u32 = 256;
/// Default maximum memory budget for the context (bytes).
pub const ALEC_DEFAULT_MAX_MEMORY_BYTES: u32 = 2048;
/// Default keyframe interval (messages between forced Raw32 keyframes).
pub const ALEC_DEFAULT_KEYFRAME_INTERVAL: u32 = 50;
/// Default for smart-resync via LoRaWAN downlink.
pub const ALEC_DEFAULT_SMART_RESYNC: bool = true;

/// Default pre-warm channel count. `0` disables the pre-warm (legacy
/// behaviour — first encode allocates per-channel state).
pub const ALEC_DEFAULT_NUM_CHANNELS: u32 = 0;

/// Runtime configuration for a new ALEC encoder.
///
/// Mirrors the Milesight-integration defaults (history=20,
/// patterns=256, memory=2048B, keyframe=50, smart_resync=true).
///
/// Pass a NULL pointer to `alec_encoder_new_with_config` to use all
/// defaults. Any numeric field set to 0 is replaced by its default, so
/// callers can opt in to a single override while keeping the rest.
/// `num_channels` is the only documented exception — `0` means "do not
/// pre-warm" (legacy behaviour), any positive value activates the
/// init-time pre-warm described below.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct AlecEncoderConfig {
    /// Per-source history window size. Default: 20.
    pub history_size: u32,
    /// Maximum patterns retained in the context dictionary. Default: 256.
    pub max_patterns: u32,
    /// Maximum memory budget for the context in bytes. Default: 2048.
    pub max_memory_bytes: u32,
    /// Interval (in messages) between forced Raw32 keyframes. Default: 50.
    /// Set to 0 to disable periodic keyframes.
    pub keyframe_interval: u32,
    /// If true, the encoder honours downlink-driven resync requests
    /// (via `alec_force_keyframe`). Default: true.
    pub smart_resync: bool,
    /// **v1.3.9 addition.** Number of fixed channels to pre-allocate at
    /// encoder-creation time. When > 0, `alec_encoder_new_with_config`
    /// immediately allocates one `SourceStats` entry per channel (ids
    /// `1..=num_channels`, matching the `fixed_channel_source_id`
    /// convention), so the first call to `alec_encode_multi_fixed`
    /// performs ZERO heap allocations.
    ///
    /// Set to the number of channels your firmware uses (5 for the
    /// Milesight EM500-CO2). `0` disables the pre-warm and keeps the
    /// pre-v1.3.9 behaviour — the first encode allocates on demand,
    /// which can panic on heaps partially consumed between
    /// `alec_encoder_new_with_config` and the first encode.
    ///
    /// Upper bound: 64 (matches `Encoder::encode_multi_fixed`'s
    /// channel cap). Values above 64 are treated as 0.
    pub num_channels: u32,
}

impl AlecEncoderConfig {
    /// Return a config pre-populated with all Milesight defaults.
    pub fn defaults() -> Self {
        Self {
            history_size: ALEC_DEFAULT_HISTORY_SIZE,
            max_patterns: ALEC_DEFAULT_MAX_PATTERNS,
            max_memory_bytes: ALEC_DEFAULT_MAX_MEMORY_BYTES,
            keyframe_interval: ALEC_DEFAULT_KEYFRAME_INTERVAL,
            smart_resync: ALEC_DEFAULT_SMART_RESYNC,
            num_channels: ALEC_DEFAULT_NUM_CHANNELS,
        }
    }

    /// Resolve the effective config, replacing any 0 numeric field by
    /// its default. Numeric fields set to 0 are treated as "use default"
    /// rather than "disable" — except `keyframe_interval` and
    /// `num_channels`, where 0 is a legitimate value (disable keyframes
    /// / disable the v1.3.9 pre-warm respectively).
    fn resolved(self) -> Self {
        let d = Self::defaults();
        Self {
            history_size: if self.history_size == 0 {
                d.history_size
            } else {
                self.history_size
            },
            max_patterns: if self.max_patterns == 0 {
                d.max_patterns
            } else {
                self.max_patterns
            },
            max_memory_bytes: if self.max_memory_bytes == 0 {
                d.max_memory_bytes
            } else {
                self.max_memory_bytes
            },
            // keyframe_interval == 0 is a valid value (disabled), so keep as-is.
            keyframe_interval: self.keyframe_interval,
            smart_resync: self.smart_resync,
            // num_channels == 0 means "no pre-warm" (legacy behaviour), keep as-is.
            // Values above 64 (encode_multi_fixed's channel cap) are clamped to 0
            // so the caller is not silently given an encoder that pre-warmed too
            // many sources and then failed at encode time.
            num_channels: if self.num_channels > 64 {
                0
            } else {
                self.num_channels
            },
        }
    }

    /// Build an `alec::context::ContextConfig` from this FFI config.
    fn to_context_config(self) -> ContextConfig {
        let r = self.resolved();
        ContextConfig {
            history_size: r.history_size as usize,
            max_patterns: r.max_patterns as usize,
            max_memory: r.max_memory_bytes as usize,
            ..ContextConfig::default()
        }
    }
}

/// Hash a C source_id string to a u32 for context keying.
/// Returns 0 if the pointer is null.
fn hash_source_id(source_id: *const c_char) -> u32 {
    if source_id.is_null() {
        return 0;
    }
    let bytes = unsafe { CStr::from_ptr(source_id) }.to_bytes();
    // Map to 1..=127 so the source_id always encodes as a 1-byte varint.
    // 0 is reserved for NULL / "no source".
    (xxhash_rust::xxh64::xxh64(bytes, 0) % 127 + 1) as u32
}

/// Result codes for ALEC FFI functions
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlecResult {
    /// Operation completed successfully
    Ok = 0,
    /// Invalid input data provided
    ErrorInvalidInput = 1,
    /// Output buffer is too small
    ErrorBufferTooSmall = 2,
    /// Encoding operation failed
    ErrorEncodingFailed = 3,
    /// Decoding operation failed
    ErrorDecodingFailed = 4,
    /// Null pointer was provided
    ErrorNullPointer = 5,
    /// Invalid UTF-8 string
    ErrorInvalidUtf8 = 6,
    /// File I/O error
    ErrorFileIo = 7,
    /// Context version mismatch
    ErrorVersionMismatch = 8,
    /// Corrupt or malformed context-state data (bad magic, bad CRC,
    /// truncated buffer, etc.). Produced by `alec_decoder_import_state`.
    ErrorCorruptData = 9,
}

/// Opaque encoder handle
///
/// Created with `alec_encoder_new()`, freed with `alec_encoder_free()`.
/// Do not access internal fields directly.
pub struct AlecEncoder {
    encoder: Encoder,
    classifier: Classifier,
    context: Context,
    /// If set, the next encode call should emit a keyframe (Raw32 for all
    /// channels). Consumed by the Bloc B/C fixed-channel encode path.
    /// Plumbed here in Bloc A so downlink handlers can set the flag
    /// immediately without waiting for the encode path to land.
    force_keyframe_pending: bool,
    /// Number of encoded messages since the last keyframe. Used by the
    /// fixed-channel encode path (Bloc C) to trigger periodic keyframes.
    #[allow(dead_code)] // Consumed by Bloc C keyframe mechanism.
    messages_since_keyframe: u32,
    /// Configured keyframe interval (0 disables periodic keyframes).
    #[allow(dead_code)] // Consumed by Bloc C keyframe mechanism.
    keyframe_interval: u32,
    /// Honour downlink-driven resync.
    smart_resync: bool,
}

/// Opaque decoder handle
///
/// Created with `alec_decoder_new()`, freed with `alec_decoder_free()`.
/// Do not access internal fields directly.
///
/// Decoder FFI is only available when the `decoder` Cargo feature is
/// enabled (default on hosted/server builds, off on `zephyr`/MCU builds).
#[cfg(feature = "decoder")]
pub struct AlecDecoder {
    decoder: Decoder,
    context: Context,
    /// Header sequence number observed on the most recent multi-frame
    /// decode (None if none has been decoded yet).
    last_header_sequence: Option<u16>,
    /// Number of missing frames detected on the most recent decode
    /// (clipped to 255). 0 means no gap.
    last_gap_size: u8,
}

// ============================================================================
// Version and Utility Functions
// ============================================================================

/// Get the ALEC library version string
///
/// # Returns
///
/// A null-terminated string containing the version (e.g., "1.0.0").
/// The returned pointer is valid for the lifetime of the program.
///
/// # Example (C)
///
/// ```c
/// printf("ALEC version: %s\n", alec_version());
/// ```
#[no_mangle]
pub extern "C" fn alec_version() -> *const c_char {
    // Include null terminator
    static VERSION: &[u8] = b"1.3.10\0";
    VERSION.as_ptr() as *const c_char
}

/// Convert a result code to a human-readable string
///
/// # Arguments
///
/// * `result` - The result code to convert
///
/// # Returns
///
/// A null-terminated string describing the result.
/// The returned pointer is valid for the lifetime of the program.
#[no_mangle]
pub extern "C" fn alec_result_to_string(result: AlecResult) -> *const c_char {
    let msg: &'static [u8] = match result {
        AlecResult::Ok => b"Success\0",
        AlecResult::ErrorInvalidInput => b"Invalid input data\0",
        AlecResult::ErrorBufferTooSmall => b"Output buffer too small\0",
        AlecResult::ErrorEncodingFailed => b"Encoding failed\0",
        AlecResult::ErrorDecodingFailed => b"Decoding failed\0",
        AlecResult::ErrorNullPointer => b"Null pointer provided\0",
        AlecResult::ErrorInvalidUtf8 => b"Invalid UTF-8 string\0",
        AlecResult::ErrorFileIo => b"File I/O error\0",
        AlecResult::ErrorVersionMismatch => b"Context version mismatch\0",
        AlecResult::ErrorCorruptData => b"Corrupt or malformed context state\0",
    };
    msg.as_ptr() as *const c_char
}

// ============================================================================
// Encoder Functions
// ============================================================================

/// Create a new ALEC encoder
///
/// # Returns
///
/// A pointer to a new encoder, or NULL on allocation failure.
/// The encoder must be freed with `alec_encoder_free()` when no longer needed.
///
/// # Example (C)
///
/// ```c
/// AlecEncoder* enc = alec_encoder_new();
/// if (enc == NULL) {
///     // Handle allocation failure
/// }
/// // ... use encoder ...
/// alec_encoder_free(enc);
/// ```
#[no_mangle]
pub extern "C" fn alec_encoder_new() -> *mut AlecEncoder {
    let defaults = AlecEncoderConfig::defaults();
    let encoder = Box::new(AlecEncoder {
        encoder: Encoder::new(),
        classifier: Classifier::default(),
        context: Context::new(),
        force_keyframe_pending: false,
        messages_since_keyframe: 0,
        keyframe_interval: defaults.keyframe_interval,
        smart_resync: defaults.smart_resync,
    });
    Box::into_raw(encoder)
}

/// Create a new encoder with checksum enabled
///
/// # Returns
///
/// A pointer to a new encoder with checksum enabled, or NULL on failure.
#[no_mangle]
pub extern "C" fn alec_encoder_new_with_checksum() -> *mut AlecEncoder {
    let defaults = AlecEncoderConfig::defaults();
    let encoder = Box::new(AlecEncoder {
        encoder: Encoder::with_checksum(),
        classifier: Classifier::default(),
        context: Context::new(),
        force_keyframe_pending: false,
        messages_since_keyframe: 0,
        keyframe_interval: defaults.keyframe_interval,
        smart_resync: defaults.smart_resync,
    });
    Box::into_raw(encoder)
}

/// Create a new ALEC encoder with a custom configuration.
///
/// Mirrors the Milesight integration requirements: the caller specifies
/// `history_size`, `max_patterns`, `max_memory_bytes`, `keyframe_interval`,
/// `smart_resync` and (v1.3.9+) `num_channels`. See `AlecEncoderConfig`
/// for defaults.
///
/// # Arguments
///
/// * `config` - Pointer to an `AlecEncoderConfig`. If NULL, all defaults
///   are used. Numeric fields set to 0 are replaced by their default
///   (except `keyframe_interval`, where 0 disables periodic keyframes,
///   and `num_channels`, where 0 disables the v1.3.9 pre-warm).
///
/// # v1.3.9 pre-warm
///
/// If `config.num_channels > 0`, one `SourceStats` entry is pre-allocated
/// per channel (ids `1..=num_channels`) at encoder-creation time. This
/// moves per-channel heap allocations out of the hot encode path and
/// prevents OOM panics on MCUs with a partially-consumed heap at
/// firmware init. Recommended for all fixed-channel MCU deployments.
///
/// # Returns
///
/// A pointer to a new encoder, or NULL on allocation failure.
/// Must be freed with `alec_encoder_free()`.
#[no_mangle]
pub extern "C" fn alec_encoder_new_with_config(
    config: *const AlecEncoderConfig,
) -> *mut AlecEncoder {
    let cfg = if config.is_null() {
        AlecEncoderConfig::defaults()
    } else {
        unsafe { *config }.resolved()
    };

    let mut context = Context::with_config(cfg.to_context_config());

    // v1.3.9 pre-warm: pre-allocate per-channel SourceStats so the
    // first `alec_encode_multi_fixed` call performs ZERO heap
    // allocation. Keys match `fixed_channel_source_id(i) = i + 1`.
    // `resolved()` clamps `num_channels > 64` to 0, so we never
    // over-allocate.
    for i in 0..cfg.num_channels {
        context.ensure_source_stats(i + 1);
    }

    let encoder = Box::new(AlecEncoder {
        encoder: Encoder::new(),
        classifier: Classifier::default(),
        context,
        force_keyframe_pending: false,
        messages_since_keyframe: 0,
        keyframe_interval: cfg.keyframe_interval,
        smart_resync: cfg.smart_resync,
    });
    Box::into_raw(encoder)
}

/// Force the next encode call to emit a keyframe (Raw32 for all channels).
///
/// Intended to be called from a LoRaWAN downlink handler receiving the
/// 0xFF resync command from the server-side sidecar. The keyframe is
/// emitted by the next call to `alec_encode_multi_fixed`: marker 0xA2,
/// Raw32 for every channel.
///
/// No-op if `encoder` is NULL or if the encoder was configured with
/// `smart_resync = false`.
///
/// Most integrators will prefer the `alec_downlink_handler` wrapper,
/// which parses a raw downlink payload and applies the right action.
///
/// # Arguments
///
/// * `encoder` - Encoder handle.
#[no_mangle]
pub extern "C" fn alec_force_keyframe(encoder: *mut AlecEncoder) {
    if encoder.is_null() {
        return;
    }
    let enc = unsafe { &mut *encoder };
    if !enc.smart_resync {
        return;
    }
    enc.force_keyframe_pending = true;
}

/// Parse a raw LoRaWAN downlink payload and apply the right action
/// to the encoder.
///
/// This is a convenience wrapper over `alec_force_keyframe`. A single
/// command byte is defined today:
///
/// - `0xFF` — "request immediate keyframe": the encoder's next
///   `alec_encode_multi_fixed` call will emit marker `0xA2` and
///   Raw32 for every channel.
///
/// Any other first byte is treated as an invalid command and the
/// encoder state is left untouched. Additional bytes after byte 0
/// are reserved for future commands and are currently ignored.
///
/// Worst-case drift after a packet loss:
///
/// - No smart resync (downlink disabled):
///   `drift ≤ keyframe_interval × uplink_period`
///   (e.g. 50 × 10 min ≈ 8 h at a 10-minute cadence).
/// - With smart resync + downlink `0xFF`:
///   `drift ≤ 1 × uplink_period` (next uplink is a keyframe).
///
/// # Arguments
///
/// * `encoder` - Encoder handle.
/// * `data` - Downlink payload bytes (the raw LoRaWAN FRMPayload).
/// * `len` - Length of `data` in bytes.
///
/// # Returns
///
/// * `ALEC_OK` if the downlink was a recognized command and was
///   applied.
/// * `ALEC_ERROR_NULL_POINTER` if `encoder` or `data` is NULL.
/// * `ALEC_ERROR_INVALID_INPUT` for an empty payload or unknown
///   command byte — encoder state is NOT modified.
#[no_mangle]
pub extern "C" fn alec_downlink_handler(
    encoder: *mut AlecEncoder,
    data: *const u8,
    len: usize,
) -> AlecResult {
    if encoder.is_null() || data.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    if len == 0 {
        return AlecResult::ErrorInvalidInput;
    }
    // SAFETY: caller promised `data` is valid for `len` bytes.
    let cmd = unsafe { *data };
    match cmd {
        0xFF => {
            alec_force_keyframe(encoder);
            AlecResult::Ok
        }
        other => {
            log::warn!(
                "ALEC downlink: unknown command byte 0x{:02X} ({} byte payload, ignored)",
                other,
                len
            );
            AlecResult::ErrorInvalidInput
        }
    }
}

/// Free an encoder
///
/// # Arguments
///
/// * `encoder` - Encoder to free. May be NULL (no-op).
///
/// # Safety
///
/// The encoder must not be used after calling this function.
#[no_mangle]
pub extern "C" fn alec_encoder_free(encoder: *mut AlecEncoder) {
    if !encoder.is_null() {
        unsafe {
            drop(Box::from_raw(encoder));
        }
    }
}

/// Encode a single floating-point value
///
/// # Arguments
///
/// * `encoder` - Encoder handle (must not be NULL)
/// * `value` - The value to encode
/// * `timestamp` - Timestamp for the value (can be 0 if not used)
/// * `source_id` - Source identifier string (null-terminated, can be NULL)
/// * `output` - Output buffer for encoded data
/// * `output_capacity` - Size of output buffer in bytes
/// * `output_len` - Pointer to store actual encoded length
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[no_mangle]
pub extern "C" fn alec_encode_value(
    encoder: *mut AlecEncoder,
    value: f64,
    timestamp: u64,
    source_id: *const c_char,
    output: *mut u8,
    output_capacity: usize,
    output_len: *mut usize,
) -> AlecResult {
    // Null checks
    if encoder.is_null() || output.is_null() || output_len.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    let enc = unsafe { &mut *encoder };
    let sid = hash_source_id(source_id);

    // Create RawData with hashed source_id for per-channel context isolation
    let raw_data = RawData::with_source(sid, value, timestamp);

    // Classify the data
    let classification = enc.classifier.classify(&raw_data, &enc.context);

    // Encode the message
    let message = enc.encoder.encode(&raw_data, &classification, &enc.context);

    // Convert to bytes
    let encoded = message.to_bytes();
    if encoded.len() > output_capacity {
        return AlecResult::ErrorBufferTooSmall;
    }

    let output_slice = unsafe { slice::from_raw_parts_mut(output, output_capacity) };
    output_slice[..encoded.len()].copy_from_slice(&encoded);
    unsafe {
        *output_len = encoded.len();
    }

    // Observe the data for context learning
    enc.context.observe(&raw_data);

    AlecResult::Ok
}

/// Encode multiple values with adaptive per-channel compression.
///
/// Each channel is independently classified (P1–P5) and encoded using the
/// optimal strategy (Repeated, Delta8, Delta16, etc.). P5 channels are
/// excluded from the output frame but their context is still updated.
///
/// # Arguments
///
/// * `encoder` - Encoder handle
/// * `values` - Array of f64 values to encode (one per channel)
/// * `value_count` - Number of channels
/// * `timestamps` - Per-channel timestamps (array of uint64_t), or NULL to
///   use 0 for all channels
/// * `source_ids` - Per-channel source identifier strings (array of
///   `const char*`), or NULL for automatic index-based IDs
/// * `priorities` - Per-channel priority overrides (1–5), or NULL for
///   classifier-assigned priorities
/// * `output` - Output buffer for encoded data
/// * `output_capacity` - Size of output buffer in bytes
/// * `output_len` - Pointer to store actual encoded length
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[no_mangle]
pub extern "C" fn alec_encode_multi(
    encoder: *mut AlecEncoder,
    values: *const f64,
    value_count: usize,
    timestamps: *const u64,
    source_ids: *const *const c_char,
    priorities: *const u8,
    output: *mut u8,
    output_capacity: usize,
    output_len: *mut usize,
) -> AlecResult {
    // Null checks
    if encoder.is_null() || values.is_null() || output.is_null() || output_len.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    if value_count == 0 {
        return AlecResult::ErrorInvalidInput;
    }

    let enc = unsafe { &mut *encoder };
    let values_slice = unsafe { slice::from_raw_parts(values, value_count) };

    // Build ChannelInput array
    let channels: Vec<ChannelInput> = (0..value_count)
        .map(|i| {
            let sid = if source_ids.is_null() {
                // Use index+1 as source_id (1-byte varint, non-zero)
                (i as u32) + 1
            } else {
                let ptr = unsafe { *source_ids.add(i) };
                hash_source_id(ptr)
            };

            ChannelInput {
                name_id: i as u8,
                source_id: sid,
                value: values_slice[i],
            }
        })
        .collect();

    // Apply priority overrides if provided
    let timestamp = if timestamps.is_null() {
        0u64
    } else {
        // Use first timestamp for the shared header
        unsafe { *timestamps }
    };

    // If priorities are provided, set critical thresholds to force classification.
    // Otherwise let the classifier decide naturally.
    // For now, we use the classifier and override priorities post-classification.
    let (message, classifications) =
        enc.encoder
            .encode_multi_adaptive(&channels, timestamp, &enc.context, &enc.classifier);

    // If explicit priorities were provided, we need to re-encode with those.
    // However, the cleaner approach is to let the classifier work and use the
    // priorities parameter as an override. Since encode_multi_adaptive already
    // classified, and the user's priority is just a hint, we accept the
    // classifier result. If the caller passes priorities != NULL, we could
    // use them, but for v1.3 we trust the classifier.
    let _ = priorities; // Reserved for future override support
    let _ = classifications;

    // Convert to bytes
    let encoded = message.to_bytes();
    if encoded.len() > output_capacity {
        return AlecResult::ErrorBufferTooSmall;
    }

    let output_slice = unsafe { slice::from_raw_parts_mut(output, output_capacity) };
    output_slice[..encoded.len()].copy_from_slice(&encoded);
    unsafe {
        *output_len = encoded.len();
    }

    // Observe ALL channels (including P5) for context learning.
    // Use name_id as source_id — matches encode/decode convention for multi frames.
    for ch in &channels {
        let rd = RawData::with_source(ch.name_id as u32, ch.value, timestamp);
        enc.context.observe(&rd);
    }

    AlecResult::Ok
}

/// Save encoder context to a file (for preload generation)
///
/// # Arguments
///
/// * `encoder` - Encoder handle
/// * `path` - File path (null-terminated string)
/// * `sensor_type` - Sensor type identifier (null-terminated string)
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[cfg(feature = "std")]
#[no_mangle]
pub extern "C" fn alec_encoder_save_context(
    encoder: *mut AlecEncoder,
    path: *const c_char,
    sensor_type: *const c_char,
) -> AlecResult {
    if encoder.is_null() || path.is_null() || sensor_type.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    let enc = unsafe { &*encoder };

    let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
        Ok(s) => s,
        Err(_) => return AlecResult::ErrorInvalidUtf8,
    };

    let sensor_type_str = match unsafe { CStr::from_ptr(sensor_type) }.to_str() {
        Ok(s) => s,
        Err(_) => return AlecResult::ErrorInvalidUtf8,
    };

    match enc
        .context
        .save_to_file(Path::new(path_str), sensor_type_str)
    {
        Ok(()) => AlecResult::Ok,
        Err(_) => AlecResult::ErrorFileIo,
    }
}

/// Load encoder context from a preload file
///
/// # Arguments
///
/// * `encoder` - Encoder handle
/// * `path` - File path to preload (null-terminated string)
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[cfg(feature = "std")]
#[no_mangle]
pub extern "C" fn alec_encoder_load_context(
    encoder: *mut AlecEncoder,
    path: *const c_char,
) -> AlecResult {
    if encoder.is_null() || path.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    let enc = unsafe { &mut *encoder };

    let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
        Ok(s) => s,
        Err(_) => return AlecResult::ErrorInvalidUtf8,
    };

    match Context::load_from_file(Path::new(path_str)) {
        Ok(ctx) => {
            enc.context = ctx;
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorFileIo,
    }
}

/// Get the current context version
///
/// # Arguments
///
/// * `encoder` - Encoder handle
///
/// # Returns
///
/// The context version number, or 0 if encoder is NULL.
#[no_mangle]
pub extern "C" fn alec_encoder_context_version(encoder: *const AlecEncoder) -> u32 {
    if encoder.is_null() {
        return 0;
    }
    let enc = unsafe { &*encoder };
    enc.context.context_version()
}

// ============================================================================
// Encoder context save / load with RAM buffers (v1.3.7)
//
// Buffer-based mirror of alec_decoder_context_save / _context_load, callable
// from MCUs that have no filesystem. In addition to the Context payload
// (predictions, patterns, dictionary — reused from the decoder's ALCS
// serialization), the encoder blob also carries the runtime state needed
// to roll back a discarded frame exactly: the encoder sequence counter,
// the pending force-keyframe flag and messages-since-last-keyframe.
//
// Wire format (little-endian for the header, ALCS payload is already
// little-endian):
//
//   Offset  Size  Field
//   0       4     magic "ALEE" (ALec Encoder state)
//   4       1     format version (= 1)
//   5       1     flags (bit 0: force_keyframe_pending)
//   6       2     sequence              (u16 big-endian)
//   8       4     messages_since_keyframe (u32 big-endian)
//   12      4     alcs_len              (u32 big-endian)
//   16      8     header xxh64         (bytes [0..16), big-endian)
//   24      N     ALCS payload (Context::to_preload_bytes, CRC32 inside)
//
// The header xxh64 catches corruption of any of the small fields above
// (sequence/flags/msk) that ALCS's inner CRC wouldn't notice. The ALCS
// inner CRC32 covers the bulk Context payload.
// ============================================================================

/// Magic bytes identifying an encoder-state buffer.
const ENC_STATE_MAGIC: [u8; 4] = *b"ALEE";
/// Current encoder-state wire format version.
const ENC_STATE_VERSION: u8 = 1;
/// Fixed header size before the embedded ALCS payload.
const ENC_STATE_HEADER_SIZE: usize = 24;
/// Sensor-type tag used when serializing the context portion. Kept
/// stable so the embedded ALCS bytes remain interoperable with the
/// decoder's `_context_load` / `_import_state` readers.
const ENC_STATE_CTX_TAG: &str = "ffi";

/// bit 0 of the flags byte: `force_keyframe_pending`.
const ENC_FLAG_FORCE_KEYFRAME: u8 = 0b0000_0001;

/// Save the encoder's runtime state to a caller-provided RAM buffer.
///
/// The saved blob captures:
/// * The full `Context` — per-channel prediction model (EMA, last
///   values, history), pattern dictionary and context version.
/// * The encoder's sequence counter.
/// * The pending force-keyframe flag and the messages-since-keyframe
///   counter consumed by the periodic keyframe mechanism.
///
/// Intended use (firmware, v1.3.7):
///
/// ```text
///     snapshot      = alec_encoder_context_save(enc, buf, cap, &len)
///     wire          = alec_encode_multi_fixed(enc, …)
///     if wire_len > ceiling:
///         alec_encoder_context_load(enc, buf, len)   // roll back
///         alec_force_keyframe(enc)                   // next frame = keyframe
/// ```
///
/// On `ALEC_ERROR_BUFFER_TOO_SMALL`, `*written` reports the exact
/// size the buffer would have needed and `buf` is NOT modified
/// (no partial write — callers can safely retry with a larger buffer).
///
/// # Arguments
///
/// * `enc`     - Encoder handle.
/// * `buf`     - Destination buffer.
/// * `buf_cap` - Size of `buf` in bytes.
/// * `written` - Out: bytes written (on success) or required size
///   (on `ALEC_ERROR_BUFFER_TOO_SMALL`).
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_BUFFER_TOO_SMALL` if `buf_cap` is too small —
///   `*written` reports the required size, `buf` is unchanged.
/// * `ALEC_ERROR_NULL_POINTER` for a NULL required pointer.
/// * `ALEC_ERROR_ENCODING_FAILED` if the underlying context
///   serialization fails (pathological config).
#[no_mangle]
pub extern "C" fn alec_encoder_context_save(
    enc: *const AlecEncoder,
    buf: *mut u8,
    buf_cap: usize,
    written: *mut usize,
) -> AlecResult {
    if enc.is_null() || buf.is_null() || written.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    let e = unsafe { &*enc };

    // v1.3.9: zero-heap streaming write directly into the caller's
    // buffer. We avoid the ~1.5 KB temporary `Vec<u8>` that the
    // previous implementation produced via `Context::to_preload_bytes`
    // — that allocation was the reported crash trigger on the
    // partner's 4 KB heap Cortex-M4.
    //
    // Contract (unchanged from v1.3.7 / v1.3.8):
    //   * on success: `*written` = total bytes written, return Ok.
    //   * on BufferTooSmall: `*written` = required size, `buf` NOT
    //     touched (no partial write). Callers can retry with a
    //     larger buffer.
    //   * on any other error: return EncodingFailed, `buf` / `written`
    //     semantics best-effort (no partial writes from this path
    //     because we size-check everything up front).

    // Required size = 24-byte encoder header + ALCS payload.
    let alcs_needed = match e.context.preload_bytes_len(ENC_STATE_CTX_TAG) {
        Ok(n) => n,
        Err(_) => return AlecResult::ErrorEncodingFailed,
    };
    let total = ENC_STATE_HEADER_SIZE + alcs_needed;
    if total > buf_cap {
        unsafe { *written = total };
        return AlecResult::ErrorBufferTooSmall;
    }

    let out = unsafe { slice::from_raw_parts_mut(buf, buf_cap) };

    // --- 24-byte encoder-state header (see module comment above) ---
    out[0..4].copy_from_slice(&ENC_STATE_MAGIC);
    out[4] = ENC_STATE_VERSION;
    out[5] = if e.force_keyframe_pending {
        ENC_FLAG_FORCE_KEYFRAME
    } else {
        0
    };
    out[6..8].copy_from_slice(&e.encoder.sequence().to_be_bytes());
    out[8..12].copy_from_slice(&e.messages_since_keyframe.to_be_bytes());
    out[12..16].copy_from_slice(&(alcs_needed as u32).to_be_bytes());
    let hdr_hash = xxhash_rust::xxh64::xxh64(&out[0..16], 0);
    out[16..24].copy_from_slice(&hdr_hash.to_be_bytes());

    // --- ALCS payload written directly into the caller buffer ---
    // Byte-identical to the v1.3.8 output — same ALCS wire format.
    let alcs_slice = &mut out[ENC_STATE_HEADER_SIZE..ENC_STATE_HEADER_SIZE + alcs_needed];
    let alcs_written = match e.context.write_preload_bytes(ENC_STATE_CTX_TAG, alcs_slice) {
        Ok(n) => n,
        Err(_) => return AlecResult::ErrorEncodingFailed,
    };
    debug_assert_eq!(alcs_written, alcs_needed);

    unsafe { *written = total };
    AlecResult::Ok
}

/// Restore encoder state from bytes produced by `alec_encoder_context_save`.
///
/// On success the encoder's `context`, `sequence`, `force_keyframe_pending`
/// and `messages_since_keyframe` are all overwritten. Static
/// configuration (`keyframe_interval`, `smart_resync`, checksum flag)
/// is preserved — those are properties of the encoder instance, not
/// of the transient runtime state.
///
/// # State transitions (v1.3.9)
///
/// On a tight-heap MCU, building the new `Context` while the old one
/// is still alive briefly needs ~2× the per-instance heap — enough to
/// blow a 4 KB allocator. v1.3.9 trades the previous all-or-nothing
/// contract for a heap-safe three-phase restore:
///
/// 1. **Pre-validate** the input buffer without any allocation
///    (magic, version, header xxh64, ALCS magic/CRC). If anything
///    fails here → return `ALEC_ERROR_CORRUPT_DATA`, encoder
///    **unchanged** (old contract preserved for the common
///    caller-error case — wrong magic, CRC mismatch, truncation,
///    etc.).
/// 2. **Free** the old Context by replacing it with a fresh empty
///    `Context`. Peak heap now drops back to ~1 × Context.
/// 3. **Rebuild** the new Context from the input buffer. Peak heap
///    is now ~1 × Context (new) instead of ~2 × (old + new). If the
///    inner `from_preload_bytes` still fails for some reason that
///    the pre-validator didn't catch (structural inconsistency
///    between advertised counts and inner section lengths), the
///    encoder ends up in a *freshly reset* state. This is the
///    single behavioural change vs v1.3.8 and is documented under
///    `ALEC_ERROR_CORRUPT_DATA` below.
///
/// # Arguments
///
/// * `enc`     - Encoder handle.
/// * `buf`     - Input bytes produced by `alec_encoder_context_save`.
/// * `buf_len` - Length of `buf` in bytes.
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_NULL_POINTER` for a NULL required pointer.
/// * `ALEC_ERROR_CORRUPT_DATA` if `buf` cannot be parsed.
///   * If the pre-validator rejects the buffer (bad magic, unknown
///     format version, header xxh64 mismatch, length mismatch,
///     ALCS CRC mismatch): the encoder is **unchanged**.
///   * If the outer validation succeeded but the inner
///     `from_preload_bytes` fails (rare, implies a CRC-valid but
///     structurally inconsistent buffer): the encoder is left in a
///     **freshly reset state** — not the old state, not corrupted.
///     Callers can safely `alec_force_keyframe` + resume encoding;
///     the decoder will resync on the next keyframe.
#[no_mangle]
pub extern "C" fn alec_encoder_context_load(
    enc: *mut AlecEncoder,
    buf: *const u8,
    buf_len: usize,
) -> AlecResult {
    if enc.is_null() || buf.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    if buf_len < ENC_STATE_HEADER_SIZE {
        return AlecResult::ErrorCorruptData;
    }
    let data = unsafe { slice::from_raw_parts(buf, buf_len) };

    // === PHASE 1: Pre-validate (zero heap allocation) ===
    // Magic + version.
    if data[0..4] != ENC_STATE_MAGIC {
        return AlecResult::ErrorCorruptData;
    }
    if data[4] != ENC_STATE_VERSION {
        return AlecResult::ErrorCorruptData;
    }
    // Header xxh64 — catches corruption of flags/sequence/msk/alcs_len.
    let stored_hash = u64::from_be_bytes([
        data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23],
    ]);
    let computed_hash = xxhash_rust::xxh64::xxh64(&data[0..16], 0);
    if stored_hash != computed_hash {
        return AlecResult::ErrorCorruptData;
    }
    // ALCS payload length must account for all remaining bytes exactly.
    let alcs_len = u32::from_be_bytes([data[12], data[13], data[14], data[15]]) as usize;
    if alcs_len != buf_len.saturating_sub(ENC_STATE_HEADER_SIZE) {
        return AlecResult::ErrorCorruptData;
    }
    let alcs = &data[ENC_STATE_HEADER_SIZE..ENC_STATE_HEADER_SIZE + alcs_len];

    // Zero-heap ALCS header / CRC check — walks the buffer, computes
    // the CRC32 table-based checksum against the rodata lookup, and
    // returns a bool. Rejects the common failure modes
    // (corruption, wrong format) before we touch the encoder.
    if !Context::validate_preload_header(alcs) {
        return AlecResult::ErrorCorruptData;
    }

    // === PHASE 2: Drop the old Context (frees heap) ===
    // Extract scalar fields we'll need below BEFORE we take any
    // mutable borrow of the encoder.
    let flags = data[5];
    let sequence = u16::from_be_bytes([data[6], data[7]]);
    let msk = u32::from_be_bytes([data[8], data[9], data[10], data[11]]);

    let e = unsafe { &mut *enc };
    // `Context::new()` is stack-only (no allocations until a source
    // is inserted). Assigning it drops the old Context here,
    // returning its BTreeMap nodes / Vec<f64> history / Pattern data
    // to the allocator.
    e.context = Context::new();

    // === PHASE 3: Build the new Context from the pre-validated buffer ===
    // Peak heap now is only ~1× Context (the new one being built),
    // not ~2× (old + new). Still calls into `from_preload_bytes`,
    // whose allocations all end up persistent in the returned
    // Context — no intermediate scratch Vec / temp Box.
    match Context::from_preload_bytes(alcs) {
        Ok(ctx) => {
            e.context = ctx;
            e.encoder.restore_sequence(sequence);
            e.messages_since_keyframe = msk;
            e.force_keyframe_pending = (flags & ENC_FLAG_FORCE_KEYFRAME) != 0;
            AlecResult::Ok
        }
        Err(_) => {
            // Unreachable on buffers produced by this library (the
            // v1.3.9 validator + ALCS CRC32 catch every malformation
            // we can emit). Defensive: if some third-party writer
            // produced a CRC-valid but structurally inconsistent
            // buffer, the encoder is left with the fresh
            // `Context::new()` from Phase 2 — documented behaviour.
            AlecResult::ErrorCorruptData
        }
    }
}

// ============================================================================
// Decoder Functions
//
// All decoder FFI is gated behind the `decoder` Cargo feature, which is on
// by default for hosted/server builds and OFF for `--features zephyr` MCU
// builds (encoder-only firmware target). The decoder requires `std` for
// HashMap / Vec / String.
// ============================================================================

/// Create a new ALEC decoder
///
/// # Returns
///
/// A pointer to a new decoder, or NULL on allocation failure.
/// The decoder must be freed with `alec_decoder_free()` when no longer needed.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_new() -> *mut AlecDecoder {
    let decoder = Box::new(AlecDecoder {
        decoder: Decoder::new(),
        context: Context::new(),
        last_header_sequence: None,
        last_gap_size: 0,
    });
    Box::into_raw(decoder)
}

/// Create a new decoder with checksum verification enabled
///
/// # Returns
///
/// A pointer to a new decoder with checksum enabled, or NULL on failure.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_new_with_checksum() -> *mut AlecDecoder {
    let decoder = Box::new(AlecDecoder {
        decoder: Decoder::with_checksum_verification(),
        context: Context::new(),
        last_header_sequence: None,
        last_gap_size: 0,
    });
    Box::into_raw(decoder)
}

/// Create a new ALEC decoder with a custom configuration.
///
/// Mirrors `alec_encoder_new_with_config` for the decoder side. The
/// `AlecEncoderConfig` struct is reused because the decoder must run
/// with the same `history_size`, `max_patterns` and `max_memory_bytes`
/// as the matching encoder for the prediction model to stay in sync.
///
/// `keyframe_interval` and `smart_resync` are encoder-only knobs and
/// are accepted but ignored on the decoder side.
///
/// # Arguments
///
/// * `config` - Pointer to an `AlecEncoderConfig`. If NULL, all defaults
///   are used. Numeric fields set to 0 are replaced by their default.
///
/// # Returns
///
/// A pointer to a new decoder, or NULL on allocation failure.
/// Must be freed with `alec_decoder_free()`.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_new_with_config(
    config: *const AlecEncoderConfig,
) -> *mut AlecDecoder {
    let cfg = if config.is_null() {
        AlecEncoderConfig::defaults()
    } else {
        unsafe { *config }.resolved()
    };

    let context = Context::with_config(cfg.to_context_config());
    let decoder = Box::new(AlecDecoder {
        decoder: Decoder::new(),
        context,
        last_header_sequence: None,
        last_gap_size: 0,
    });
    Box::into_raw(decoder)
}

/// Reset a decoder to its initial state.
///
/// Wipes all per-channel prediction state (the per-source EMA, last
/// values, history) and clears the session-tracking counters
/// (`last_header_sequence`, `last_gap_size`). The next frame the
/// decoder sees should be a keyframe (marker `0xA2`) which will
/// re-seed the prediction state from Raw32 values.
///
/// Use after detecting an unrecoverable desync that the in-band gap
/// recovery can't handle (e.g. the server-side sidecar restarting
/// without a saved context).
///
/// No-op if `dec` is NULL.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_reset(dec: *mut AlecDecoder) {
    if dec.is_null() {
        return;
    }
    let d = unsafe { &mut *dec };
    d.decoder.reset();
    d.context.reset_to_baseline();
    d.last_header_sequence = None;
    d.last_gap_size = 0;
}

/// Check whether the most recent decode detected a sequence gap.
///
/// The server-side sidecar uses this to decide whether to issue a
/// resync downlink (0xFF) to the device. The gap size is the number
/// of missing frames between the previous `last_sequence` and the
/// current one, clipped to 255.
///
/// # Arguments
///
/// * `decoder`      - Decoder handle.
/// * `out_gap_size` - Out parameter receiving the gap size (may be NULL).
///
/// # Returns
///
/// `true` if the most recent multi-frame decode observed missing
/// frames (gap > 0). `false` if no gap, if no decode has been
/// performed yet, or if `decoder` is NULL.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_gap_detected(
    decoder: *const AlecDecoder,
    out_gap_size: *mut u8,
) -> bool {
    if decoder.is_null() {
        if !out_gap_size.is_null() {
            unsafe { *out_gap_size = 0 };
        }
        return false;
    }
    let dec = unsafe { &*decoder };
    if !out_gap_size.is_null() {
        unsafe { *out_gap_size = dec.last_gap_size };
    }
    dec.last_gap_size > 0
}

/// Free a decoder
///
/// # Arguments
///
/// * `decoder` - Decoder to free. May be NULL (no-op).
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_free(decoder: *mut AlecDecoder) {
    if !decoder.is_null() {
        unsafe {
            drop(Box::from_raw(decoder));
        }
    }
}

/// Decode compressed data to a single value
///
/// # Arguments
///
/// * `decoder` - Decoder handle
/// * `input` - Compressed input data
/// * `input_len` - Length of input data
/// * `value` - Pointer to store decoded value
/// * `timestamp` - Pointer to store decoded timestamp (can be NULL)
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decode_value(
    decoder: *mut AlecDecoder,
    input: *const u8,
    input_len: usize,
    value: *mut f64,
    timestamp: *mut u64,
) -> AlecResult {
    if decoder.is_null() || input.is_null() || value.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    let dec = unsafe { &mut *decoder };
    let input_slice = unsafe { slice::from_raw_parts(input, input_len) };

    match dec.decoder.decode_bytes(input_slice, &dec.context) {
        Ok(decoded_data) => {
            unsafe {
                *value = decoded_data.value;
                if !timestamp.is_null() {
                    *timestamp = decoded_data.timestamp;
                }
            }
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorDecodingFailed,
    }
}

/// Decode compressed data to multiple values
///
/// # Arguments
///
/// * `decoder` - Decoder handle
/// * `input` - Compressed input data
/// * `input_len` - Length of input data
/// * `values` - Output buffer for decoded values
/// * `values_capacity` - Maximum number of values that can be stored
/// * `values_count` - Pointer to store actual number of decoded values
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decode_multi(
    decoder: *mut AlecDecoder,
    input: *const u8,
    input_len: usize,
    values: *mut f64,
    values_capacity: usize,
    values_count: *mut usize,
) -> AlecResult {
    if decoder.is_null() || input.is_null() || values.is_null() || values_count.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    let dec = unsafe { &mut *decoder };
    let input_slice = unsafe { slice::from_raw_parts(input, input_len) };

    // First parse the message from bytes
    let message = match alec::protocol::EncodedMessage::from_bytes(input_slice) {
        Some(msg) => msg,
        None => return AlecResult::ErrorDecodingFailed,
    };

    // Gap detection: compute the number of missing frames between the
    // previous header sequence and this one. `decode_multi` does not
    // touch `Decoder::last_sequence`, so we track it here at the FFI
    // layer. Clipped to 255 to fit `last_gap_size: u8`.
    let cur_seq = message.header.sequence;
    dec.last_gap_size = match dec.last_header_sequence {
        Some(prev) => {
            let diff = cur_seq.wrapping_sub(prev);
            if diff == 0 {
                0 // same frame replayed — treat as no gap
            } else {
                let missing = diff.saturating_sub(1);
                missing.min(u8::MAX as u16) as u8
            }
        }
        None => 0,
    };
    dec.last_header_sequence = Some(cur_seq);

    match dec.decoder.decode_multi(&message, &dec.context) {
        Ok(value_pairs) => {
            if value_pairs.len() > values_capacity {
                return AlecResult::ErrorBufferTooSmall;
            }

            let values_slice = unsafe { slice::from_raw_parts_mut(values, values_capacity) };
            for (i, (_, val)) in value_pairs.iter().enumerate() {
                values_slice[i] = *val;
            }
            unsafe {
                *values_count = value_pairs.len();
            }
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorDecodingFailed,
    }
}

/// Load decoder context from a preload file
///
/// # Arguments
///
/// * `decoder` - Decoder handle
/// * `path` - File path to preload (null-terminated string)
///
/// # Returns
///
/// `ALEC_OK` on success, error code otherwise.
#[cfg(all(feature = "decoder", feature = "std"))]
#[no_mangle]
pub extern "C" fn alec_decoder_load_context(
    decoder: *mut AlecDecoder,
    path: *const c_char,
) -> AlecResult {
    if decoder.is_null() || path.is_null() {
        return AlecResult::ErrorNullPointer;
    }

    let dec = unsafe { &mut *decoder };

    let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
        Ok(s) => s,
        Err(_) => return AlecResult::ErrorInvalidUtf8,
    };

    match Context::load_from_file(Path::new(path_str)) {
        Ok(ctx) => {
            dec.context = ctx;
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorFileIo,
    }
}

/// Get the current decoder context version
///
/// # Arguments
///
/// * `decoder` - Decoder handle
///
/// # Returns
///
/// The context version number, or 0 if decoder is NULL.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_context_version(decoder: *const AlecDecoder) -> u32 {
    if decoder.is_null() {
        return 0;
    }
    let dec = unsafe { &*decoder };
    dec.context.context_version()
}

// ============================================================================
// Bloc B — Compact fixed-channel FFI (Milesight EM500-CO2)
// ============================================================================

/// Encode a fixed-channel frame using the compact 4-byte header
/// (Milesight EM500-CO2 wire format).
///
/// The number of channels is passed explicitly and must match the
/// value used by the peer decoder — the wire format does not carry
/// it. The encoder keeps a positional view of the channels, so
/// `values[i]` is the value for channel index `i`.
///
/// If `keyframe_interval > 0` and `messages_since_keyframe`
/// has reached that interval, OR if `alec_force_keyframe` was called
/// since the last encode AND `smart_resync` is enabled, this frame
/// is emitted as a **keyframe** (marker 0xA2, Raw32 for every
/// channel). Otherwise a regular data frame (marker 0xA1) is emitted.
///
/// # Arguments
///
/// * `encoder`         - Encoder handle (must not be NULL).
/// * `values` - Per-channel f64 values, positional.
/// * `channel_count` - Number of channels in `values`.
/// * `output` - Destination buffer for the wire bytes.
/// * `output_capacity` - Size of `output` in bytes.
/// * `out_len` - Pointer receiving the number of bytes written to
///   `output`.
///
/// # Returns
///
/// `ALEC_OK` on success. `ALEC_ERROR_BUFFER_TOO_SMALL` if the
/// encoded frame does not fit in `output`. `ALEC_ERROR_INVALID_INPUT`
/// for zero channels. `ALEC_ERROR_NULL_POINTER` for any required
/// NULL pointer.
///
/// The caller can detect that the frame must be replaced by the
/// legacy TLV fallback by comparing `*out_len` against the 11-byte
/// LoRaWAN ceiling: if `*out_len > 11`, emit the TLV frame instead.
#[no_mangle]
pub extern "C" fn alec_encode_multi_fixed(
    encoder: *mut AlecEncoder,
    values: *const f64,
    channel_count: usize,
    output: *mut u8,
    output_capacity: usize,
    out_len: *mut usize,
) -> AlecResult {
    if encoder.is_null() || values.is_null() || output.is_null() || out_len.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    if channel_count == 0 {
        return AlecResult::ErrorInvalidInput;
    }

    let enc = unsafe { &mut *encoder };
    let values_slice = unsafe { slice::from_raw_parts(values, channel_count) };
    let output_slice = unsafe { slice::from_raw_parts_mut(output, output_capacity) };

    // Decide whether this frame should be a keyframe.
    let periodic_due =
        enc.keyframe_interval > 0 && enc.messages_since_keyframe >= enc.keyframe_interval;
    let downlink_forced = enc.force_keyframe_pending && enc.smart_resync;
    let keyframe = periodic_due || downlink_forced;

    match enc
        .encoder
        .encode_multi_fixed(values_slice, &enc.context, keyframe, output_slice)
    {
        Ok(n) => {
            unsafe {
                *out_len = n;
            }

            // Counter housekeeping — only after a successful encode.
            // On a keyframe we reset to 1 (not 0): the keyframe IS the
            // first frame of the next cycle, so subsequent keyframes
            // land at a fixed modular offset (e.g. interval=10 →
            // frames 10, 20, 30 …). Off-by-one matters for the spec's
            // "Frames 10 and 20 must be Raw32" assertion.
            if keyframe {
                enc.messages_since_keyframe = 1;
                enc.force_keyframe_pending = false;
            } else {
                enc.messages_since_keyframe = enc.messages_since_keyframe.saturating_add(1);
            }

            // Observe each channel so the next encode sees this value
            // in the prediction cache. We observe the ORIGINAL input
            // (not the reconstructed value): on truly-stable signals
            // this is what lets `Repeated` fire frame-after-frame.
            // Observing the reconstructed value would break Repeated
            // detection because f32 roundtrip of e.g. 3.600 yields
            // 3.5999999046…, which is > f64::EPSILON away from 3.600.
            //
            // The trade-off is a bounded drift between encoder and
            // decoder contexts on delta-encoded channels. This drift
            // is capped by the periodic keyframe mechanism: every
            // `keyframe_interval` frames the encoder emits Raw32 for
            // every channel, which forces the decoder's view back to
            // f32-precision truth. See `test_encode_decode_fixed_roundtrip_5ch`.
            for (i, &v) in values_slice.iter().enumerate() {
                let rd = RawData::with_source(fixed_channel_source_id(i), v, 0);
                enc.context.observe(&rd);
            }

            AlecResult::Ok
        }
        Err(alec::error::AlecError::Encode(alec::error::EncodeError::BufferTooSmall {
            ..
        })) => AlecResult::ErrorBufferTooSmall,
        Err(alec::error::AlecError::Encode(alec::error::EncodeError::PayloadTooLarge {
            ..
        })) => AlecResult::ErrorInvalidInput,
        Err(_) => AlecResult::ErrorEncodingFailed,
    }
}

/// Decode a fixed-channel frame produced by `alec_encode_multi_fixed`.
///
/// The wire format does NOT carry the channel count — encoder and
/// decoder must agree on it out-of-band (the LoRaWAN device model
/// pins a fixed channel count per DevEUI). The decoder uses
/// `max_channels` as both the channel count and the capacity of
/// `values_out`; `*num_channels_out` is set to that same value on
/// success.
///
/// On a successful decode:
///   - `values_out[..*num_channels_out]` receives the decoded values
///     in channel order.
///   - `*sequence_out` receives the wire sequence number.
///   - `*is_keyframe_out` is `true` when the frame's marker was `0xA2`.
///   - The decoder's last-sequence and last-ctx-version are updated.
///   - The gap size (if any) is available via `alec_decoder_gap_detected`.
///
/// # Arguments
///
/// * `dec`              - Decoder handle.
/// * `frame_data`       - Raw ALEC wire bytes (starting at the marker byte).
/// * `frame_len`        - Length of `frame_data` in bytes.
/// * `values_out`       - Destination buffer for decoded channel values.
/// * `max_channels`     - Capacity of `values_out` AND number of channels
///   in the frame. Must match the encoder's count.
/// * `num_channels_out` - Out: number of channels written to `values_out`.
///   May be NULL if the caller does not need it.
/// * `sequence_out`     - Out: sequence number from the compact header.
///   May be NULL.
/// * `is_keyframe_out`  - Out: `true` iff the frame was a keyframe (`0xA2`).
///   May be NULL.
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_INVALID_INPUT` for zero channels or a non-ALEC marker byte.
/// * `ALEC_ERROR_BUFFER_TOO_SMALL` if the input is shorter than the header
///   + bitmap + data bytes.
/// * `ALEC_ERROR_DECODING_FAILED` for any other decode error.
/// * `ALEC_ERROR_NULL_POINTER` for a NULL required pointer
///   (`dec`, `frame_data`, `values_out`).
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decode_multi_fixed(
    dec: *mut AlecDecoder,
    frame_data: *const u8,
    frame_len: usize,
    values_out: *mut f64,
    max_channels: usize,
    num_channels_out: *mut usize,
    sequence_out: *mut u16,
    is_keyframe_out: *mut bool,
) -> AlecResult {
    if dec.is_null() || frame_data.is_null() || values_out.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    if max_channels == 0 {
        return AlecResult::ErrorInvalidInput;
    }

    let d = unsafe { &mut *dec };
    let input_slice = unsafe { slice::from_raw_parts(frame_data, frame_len) };
    let output_slice = unsafe { slice::from_raw_parts_mut(values_out, max_channels) };
    let channel_count = max_channels;

    match d
        .decoder
        .decode_multi_fixed(input_slice, channel_count, &d.context, output_slice)
    {
        Ok(info) => {
            // Mirror the gap tracking used by the legacy multi path
            // so `alec_decoder_gap_detected` returns the same view
            // regardless of which decode entry point was used.
            d.last_header_sequence = Some(info.sequence);
            d.last_gap_size = info.gap_size;

            // Bloc C recovery: on a non-keyframe frame, if the
            // decoder observed a sequence gap OR a context-version
            // mismatch, wipe the per-channel prediction state so
            // stale Delta predictions cannot silently corrupt the
            // next decode. The next keyframe (marker 0xA2) will
            // re-seed the state. A keyframe itself NEVER triggers a
            // reset — its payload is Raw32 for every channel and
            // fully re-builds the context on its own.
            if !info.keyframe {
                if info.gap_size > 0 {
                    log::warn!(
                        "ALEC gap detected on fixed-channel decode: {} frame(s) missing \
                         (seq={}), context reset to baseline",
                        info.gap_size,
                        info.sequence
                    );
                    d.context.reset_to_baseline();
                } else if info.context_mismatch {
                    // Also surface a u32-level check via the core
                    // Context::check_version API. We truncate our
                    // tracked u32 version to the low 16 bits so the
                    // comparison is wire-format-accurate; the full
                    // u32 version is informational only here.
                    let wire_ver = info.context_version as u32;
                    let _result = d.context.check_version(wire_ver);
                    log::warn!(
                        "ALEC ctx_ver mismatch on fixed-channel decode: \
                         wire={}, context reset to baseline",
                        info.context_version
                    );
                    d.context.reset_to_baseline();
                }
            }

            // Observe every decoded value so the NEXT frame can
            // decode delta-encoded channels correctly. This runs
            // AFTER any reset_to_baseline(): on a keyframe these
            // observations reconstruct the prediction state from
            // the Raw32 values, which is exactly what we want.
            for (i, &value) in output_slice.iter().take(channel_count).enumerate() {
                let rd = RawData::with_source(fixed_channel_source_id(i), value, 0);
                d.context.observe(&rd);
            }

            // Surface frame-level outputs (all optional).
            if !num_channels_out.is_null() {
                unsafe { *num_channels_out = channel_count };
            }
            if !sequence_out.is_null() {
                unsafe { *sequence_out = info.sequence };
            }
            if !is_keyframe_out.is_null() {
                unsafe { *is_keyframe_out = info.keyframe };
            }

            AlecResult::Ok
        }
        Err(alec::error::AlecError::Decode(alec::error::DecodeError::BufferTooShort {
            ..
        })) => AlecResult::ErrorBufferTooSmall,
        Err(alec::error::AlecError::Decode(alec::error::DecodeError::MalformedMessage {
            reason,
            ..
        })) if reason.contains("not a fixed-channel ALEC frame") => AlecResult::ErrorInvalidInput,
        Err(_) => AlecResult::ErrorDecodingFailed,
    }
}

/// Feed raw sensor values into the decoder to advance its prediction
/// model, **without** an ALEC wire frame.
///
/// Use this on the server side when the device sent a legacy TLV
/// frame (or any non-ALEC wire format) instead of an ALEC frame for
/// a given uplink — typically because the ALEC-encoded frame would
/// have exceeded the LoRaWAN payload ceiling and the firmware fell
/// back to TLV. The encoder advanced its sequence counter, its
/// `context_version`, and its per-channel prediction state when it
/// produced the discarded frame; the decoder needs to mirror those
/// state changes or the next real ALEC frame will be reported as a
/// sequence gap (and trigger a `reset_to_baseline`).
///
/// After this call, the decoder is in the exact same prediction
/// state as it would be if `alec_decode_multi_fixed` had decoded the
/// matching ALEC wire bytes. Subsequent ALEC frames decode correctly
/// without a "gap detected" warning.
///
/// # State changes (mirrors `alec_decode_multi_fixed`)
///
/// 1. The wire-equivalent sequence (= `last_fixed_sequence + 1`,
///    matching what the encoder would have written) is recorded —
///    `alec_decoder_gap_detected` returns `false` after this call.
/// 2. The wire-equivalent ctx_version (= low 16 bits of the
///    decoder's CURRENT `context.version`, captured BEFORE the
///    observe loop) is recorded so a context-version mismatch on
///    the next real frame is computed against the right baseline.
/// 3. Each value is fed through `Context::observe` — same loop as
///    the post-decode path in `alec_decode_multi_fixed`. This
///    advances `context.version` by `num_values`.
///
/// # Arguments
///
/// * `dec`        - Decoder handle.
/// * `values`     - Array of `f64` sensor values, in the same channel
///   order the encoder uses.
/// * `num_values` - Number of values in `values`. Must be in `1..=64`
///   (matching `alec_encode_multi_fixed`'s channel cap).
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_NULL_POINTER` if `dec` or `values` is NULL.
/// * `ALEC_ERROR_INVALID_INPUT` if `num_values == 0` or `num_values > 64`.
///
/// # Zero heap
///
/// This function performs zero heap allocations once the decoder's
/// per-channel `SourceStats` entries exist (i.e. after the first
/// observation per source_id, or after `num_channels` pre-warm at
/// `alec_decoder_new_with_config` time).
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_feed_values(
    dec: *mut AlecDecoder,
    values: *const f64,
    num_values: usize,
) -> AlecResult {
    if dec.is_null() || values.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    // Match the encoder's `Encoder::encode_multi_fixed` cap of 64
    // channels. Reject 0 (no-op) and >64 (out of wire-format range)
    // up front — same shape as `alec_encode_multi_fixed`.
    if num_values == 0 || num_values > 64 {
        return AlecResult::ErrorInvalidInput;
    }

    let d = unsafe { &mut *dec };
    let values_slice = unsafe { slice::from_raw_parts(values, num_values) };

    // Step 1: capture the wire-equivalent ctx_ver BEFORE observing.
    // The encoder writes `(context.version & 0xFFFF) as u16` into the
    // CompactHeader BEFORE its post-encode observe loop; we mirror
    // that exactly so a future real frame's ctx_ver-mismatch check
    // sees the same value the encoder will write.
    let wire_ctx_ver = (d.context.context_version() & 0xFFFF) as u16;

    // Step 2: compute the wire-equivalent sequence. The encoder
    // increments its `Encoder::sequence` once per encode call; the
    // wire seq is the pre-increment value. The decoder's
    // `last_fixed_sequence` records what wire seq it last saw; the
    // next frame (real or "ghost") would be `last + 1`. None means
    // "no frame yet" — the encoder's first wire seq is 0, so we use
    // u16::MAX so wrapping_add(1) lands on 0.
    let wire_seq = d
        .decoder
        .last_fixed_sequence()
        .unwrap_or(u16::MAX)
        .wrapping_add(1);

    // Step 3: advance the alec::Decoder's fixed-path trackers. This
    // is the only place we need a setter on the inner Decoder —
    // `Decoder::record_fixed_frame` was added in v1.3.10 for exactly
    // this use case.
    d.decoder.record_fixed_frame(wire_seq, wire_ctx_ver);

    // Step 4: FFI-layer trackers — mirror the post-decode bookkeeping
    // in `alec_decode_multi_fixed`. By construction `feed_values` is
    // the lockstep path (no gap, no version mismatch), so gap_size = 0.
    d.last_header_sequence = Some(wire_seq);
    d.last_gap_size = 0;

    // Step 5: per-channel observe — same loop as the post-decode
    // path. Each `observe` increments `context.version` by 1; after
    // `num_values` observes the decoder's context.version has
    // advanced by exactly the same amount the encoder's did when it
    // produced the discarded frame.
    for (i, &v) in values_slice.iter().enumerate() {
        let rd = RawData::with_source(fixed_channel_source_id(i), v, 0);
        d.context.observe(&rd);
    }

    AlecResult::Ok
}

// ============================================================================
// Bloc D — Context persistence FFI
//
// These functions expose Context::to_preload_bytes / from_preload_bytes to
// C callers. Intended use: the ChirpStack sidecar periodically exports each
// DevEUI's decoder context (Redis persistence) and restores it on startup.
// ============================================================================

/// Compute the exact number of bytes `alec_decoder_export_state` would
/// write for this decoder + sensor_type. Lets the caller allocate the
/// right-sized buffer up front without any reallocation.
///
/// # Arguments
///
/// * `decoder`     - Decoder handle.
/// * `sensor_type` - Null-terminated sensor-type identifier.
/// * `out_size`    - Pointer receiving the required size in bytes.
///
/// # Returns
///
/// `ALEC_OK` on success; `ALEC_ERROR_NULL_POINTER` for a NULL pointer;
/// `ALEC_ERROR_INVALID_UTF8` if `sensor_type` is not valid UTF-8;
/// `ALEC_ERROR_INVALID_INPUT` if `sensor_type` exceeds 255 bytes.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_export_state_size(
    decoder: *const AlecDecoder,
    sensor_type: *const c_char,
    out_size: *mut usize,
) -> AlecResult {
    if decoder.is_null() || sensor_type.is_null() || out_size.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    let dec = unsafe { &*decoder };
    let sens_str = match unsafe { CStr::from_ptr(sensor_type) }.to_str() {
        Ok(s) => s,
        Err(_) => return AlecResult::ErrorInvalidUtf8,
    };
    match dec.context.to_preload_bytes(sens_str) {
        Ok(bytes) => {
            unsafe { *out_size = bytes.len() };
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorInvalidInput,
    }
}

/// Serialize the decoder's context to a caller-provided buffer.
///
/// The output is a self-contained byte buffer (magic `ALCS`, CRC32
/// protected) that can be persisted to Redis, a file, etc. Typical
/// size is 1-2 KB for a 5-channel EM500-CO2 decoder with
/// `history_size = 20`.
///
/// Session state (last_header_sequence, last_gap_size) is **NOT**
/// serialized — those are transient tracking counters that reset
/// naturally on sidecar restart.
///
/// # Arguments
///
/// * `decoder` - Decoder handle.
/// * `sensor_type` - Null-terminated sensor-type identifier (≤ 255 bytes).
/// * `out_buf` - Destination buffer.
/// * `out_capacity` - Size of `out_buf` in bytes.
/// * `out_len` - Pointer receiving the number of bytes written (on
///   success) or the required size (on `ALEC_ERROR_BUFFER_TOO_SMALL`).
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_BUFFER_TOO_SMALL` if `out_capacity` is less than the
///   required size. In that case `*out_len` is set to the required
///   size and `out_buf` is NOT written (no partial write).
/// * `ALEC_ERROR_NULL_POINTER` for a NULL required pointer.
/// * `ALEC_ERROR_INVALID_UTF8` if `sensor_type` is not valid UTF-8.
/// * `ALEC_ERROR_INVALID_INPUT` if `sensor_type` exceeds 255 bytes.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_export_state(
    decoder: *const AlecDecoder,
    sensor_type: *const c_char,
    out_buf: *mut u8,
    out_capacity: usize,
    out_len: *mut usize,
) -> AlecResult {
    if decoder.is_null() || sensor_type.is_null() || out_buf.is_null() || out_len.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    let dec = unsafe { &*decoder };
    let sens_str = match unsafe { CStr::from_ptr(sensor_type) }.to_str() {
        Ok(s) => s,
        Err(_) => return AlecResult::ErrorInvalidUtf8,
    };
    let bytes = match dec.context.to_preload_bytes(sens_str) {
        Ok(b) => b,
        Err(_) => return AlecResult::ErrorInvalidInput,
    };
    if bytes.len() > out_capacity {
        // Buffer too small — report the required size but do not
        // partially write the output (contract: out_buf unchanged).
        unsafe { *out_len = bytes.len() };
        return AlecResult::ErrorBufferTooSmall;
    }
    let out_slice = unsafe { slice::from_raw_parts_mut(out_buf, out_capacity) };
    out_slice[..bytes.len()].copy_from_slice(&bytes);
    unsafe { *out_len = bytes.len() };
    AlecResult::Ok
}

/// Restore a decoder's context from bytes produced by
/// `alec_decoder_export_state`.
///
/// On success, `decoder.context` is replaced by the deserialized
/// context. The decoder's session state — `last_header_sequence` and
/// `last_gap_size` — is **preserved** (those are transient
/// frame-level trackers, not context state).
///
/// If the input buffer is corrupted (bad magic, CRC mismatch,
/// truncation, etc.), the decoder is NOT modified in any way —
/// neither the context nor the session state. The caller can safely
/// retry after repairing the input.
///
/// # Arguments
///
/// * `decoder`  - Decoder handle.
/// * `data`     - Input bytes produced by `alec_decoder_export_state`.
/// * `data_len` - Length of `data` in bytes.
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_NULL_POINTER` for a NULL pointer.
/// * `ALEC_ERROR_CORRUPT_DATA` if `data` cannot be parsed (bad magic,
///   CRC mismatch, truncation, unknown format version).
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_import_state(
    decoder: *mut AlecDecoder,
    data: *const u8,
    data_len: usize,
) -> AlecResult {
    if decoder.is_null() || data.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    let data_slice = unsafe { slice::from_raw_parts(data, data_len) };
    match Context::from_preload_bytes(data_slice) {
        Ok(ctx) => {
            let dec = unsafe { &mut *decoder };
            // Replace context only — session state (last_header_sequence,
            // last_gap_size) is intentionally preserved.
            dec.context = ctx;
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorCorruptData,
    }
}

// ============================================================================
// Decoder context save / load (sensor-type-agnostic, v1.3.6+)
//
// Thin wrappers over alec_decoder_export_state / alec_decoder_import_state
// that hide the `sensor_type` tag from callers that don't use it. The
// underlying preload format requires a sensor-type label; we use a fixed
// "ffi" tag so the produced bytes remain interoperable with the lower-level
// `_state` APIs (an "ffi"-tagged buffer is also a valid preload buffer).
// ============================================================================

/// Sensor-type tag used by `alec_decoder_context_save`. Kept short
/// (≤ 255 bytes) and version-stable so the produced bytes round-trip
/// across `_save` / `_load` and across `_state` / `_state` boundaries.
#[cfg(feature = "decoder")]
const FFI_CONTEXT_TAG: &str = "ffi";

/// Save the decoder's context to a caller-provided buffer.
///
/// On success `*written` reports the number of bytes written to `buf`.
/// On `ALEC_ERROR_BUFFER_TOO_SMALL`, `*written` reports the required
/// size and `buf` is NOT modified (no partial write).
///
/// The output is a self-contained byte buffer (magic `ALCS`, CRC32
/// protected) suitable for Redis/disk persistence. Typical size is
/// 1–2 KB for a 5-channel decoder with `history_size = 20`.
///
/// Use `alec_decoder_context_load` (or the lower-level
/// `alec_decoder_import_state`) to restore.
///
/// Session state (`last_header_sequence`, `last_gap_size`) is NOT
/// serialized — those are transient frame-level trackers that reset
/// naturally when the sidecar restarts.
///
/// # Arguments
///
/// * `dec`     - Decoder handle.
/// * `buf`     - Destination buffer.
/// * `buf_cap` - Size of `buf` in bytes.
/// * `written` - Out: bytes written (on success) or required size
///   (on `ALEC_ERROR_BUFFER_TOO_SMALL`).
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_BUFFER_TOO_SMALL` if `buf_cap` is too small —
///   `*written` reports the required size, `buf` is unchanged.
/// * `ALEC_ERROR_NULL_POINTER` for a NULL required pointer.
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_context_save(
    dec: *const AlecDecoder,
    buf: *mut u8,
    buf_cap: usize,
    written: *mut usize,
) -> AlecResult {
    if dec.is_null() || buf.is_null() || written.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    let d = unsafe { &*dec };
    let bytes = match d.context.to_preload_bytes(FFI_CONTEXT_TAG) {
        Ok(b) => b,
        Err(_) => return AlecResult::ErrorEncodingFailed,
    };
    if bytes.len() > buf_cap {
        unsafe { *written = bytes.len() };
        return AlecResult::ErrorBufferTooSmall;
    }
    let out_slice = unsafe { slice::from_raw_parts_mut(buf, buf_cap) };
    out_slice[..bytes.len()].copy_from_slice(&bytes);
    unsafe { *written = bytes.len() };
    AlecResult::Ok
}

/// Restore the decoder's context from bytes produced by
/// `alec_decoder_context_save` (or `alec_decoder_export_state`).
///
/// On success the decoder's `context` is replaced; session state
/// (`last_header_sequence`, `last_gap_size`) is preserved. On
/// `ALEC_ERROR_CORRUPT_DATA` the decoder is NOT modified.
///
/// # Arguments
///
/// * `dec`     - Decoder handle.
/// * `buf`     - Input bytes.
/// * `buf_len` - Length of `buf` in bytes.
///
/// # Returns
///
/// * `ALEC_OK` on success.
/// * `ALEC_ERROR_NULL_POINTER` for a NULL required pointer.
/// * `ALEC_ERROR_CORRUPT_DATA` if `buf` cannot be parsed (bad magic,
///   CRC mismatch, truncation, unknown format version).
#[cfg(feature = "decoder")]
#[no_mangle]
pub extern "C" fn alec_decoder_context_load(
    dec: *mut AlecDecoder,
    buf: *const u8,
    buf_len: usize,
) -> AlecResult {
    if dec.is_null() || buf.is_null() {
        return AlecResult::ErrorNullPointer;
    }
    let data_slice = unsafe { slice::from_raw_parts(buf, buf_len) };
    match Context::from_preload_bytes(data_slice) {
        Ok(ctx) => {
            let d = unsafe { &mut *dec };
            d.context = ctx;
            AlecResult::Ok
        }
        Err(_) => AlecResult::ErrorCorruptData,
    }
}

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

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

    #[test]
    fn test_version() {
        let version = alec_version();
        assert!(!version.is_null());
        let version_str = unsafe { CStr::from_ptr(version) }.to_str().unwrap();
        assert_eq!(version_str, "1.3.10");
    }

    #[test]
    fn test_result_to_string() {
        let ok_str = alec_result_to_string(AlecResult::Ok);
        assert!(!ok_str.is_null());
        let ok = unsafe { CStr::from_ptr(ok_str) }.to_str().unwrap();
        assert_eq!(ok, "Success");
    }

    #[test]
    fn test_encoder_lifecycle() {
        let enc = alec_encoder_new();
        assert!(!enc.is_null());
        alec_encoder_free(enc);
    }

    #[test]
    fn test_encoder_free_null() {
        // Should not crash
        alec_encoder_free(ptr::null_mut());
    }

    #[test]
    fn test_decoder_lifecycle() {
        let dec = alec_decoder_new();
        assert!(!dec.is_null());
        alec_decoder_free(dec);
    }

    #[test]
    fn test_encode_value() {
        let enc = alec_encoder_new();
        assert!(!enc.is_null());

        let mut output = [0u8; 256];
        let mut output_len: usize = 0;

        let result = alec_encode_value(
            enc,
            22.5,
            1234567890,
            ptr::null(),
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );

        assert_eq!(result, AlecResult::Ok);
        assert!(output_len > 0);

        alec_encoder_free(enc);
    }

    #[test]
    fn test_encode_null_pointer() {
        let mut output = [0u8; 256];
        let mut output_len: usize = 0;

        let result = alec_encode_value(
            ptr::null_mut(),
            22.5,
            0,
            ptr::null(),
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );

        assert_eq!(result, AlecResult::ErrorNullPointer);
    }

    #[test]
    fn test_encode_multi() {
        let enc = alec_encoder_new();
        let values: [f64; 4] = [22.0, 22.5, 23.0, 22.8];
        let mut output = [0u8; 256];
        let mut output_len: usize = 0;

        let result = alec_encode_multi(
            enc,
            values.as_ptr(),
            values.len(),
            ptr::null(), // timestamps
            ptr::null(), // source_ids
            ptr::null(), // priorities
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );

        assert_eq!(result, AlecResult::Ok);
        assert!(output_len > 0);

        alec_encoder_free(enc);
    }

    #[test]
    fn test_context_version() {
        let enc = alec_encoder_new();
        let version = alec_encoder_context_version(enc);
        assert_eq!(version, 0); // Initial version

        // Encode some data to increment version
        let mut output = [0u8; 256];
        let mut output_len: usize = 0;
        alec_encode_value(
            enc,
            22.5,
            0,
            ptr::null(),
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );

        let new_version = alec_encoder_context_version(enc);
        assert!(new_version > version);

        alec_encoder_free(enc);
    }

    #[test]
    fn test_encoder_with_checksum() {
        let enc = alec_encoder_new_with_checksum();
        assert!(!enc.is_null());

        let mut output = [0u8; 256];
        let mut output_len: usize = 0;

        let result = alec_encode_value(
            enc,
            22.5,
            0,
            ptr::null(),
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );

        assert_eq!(result, AlecResult::Ok);
        alec_encoder_free(enc);
    }

    #[test]
    fn test_encode_value_with_source_id() {
        let enc = alec_encoder_new();
        let mut output = [0u8; 256];
        let mut output_len: usize = 0;

        let source = b"temperature\0";
        let result = alec_encode_value(
            enc,
            22.5,
            0,
            source.as_ptr() as *const c_char,
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );

        assert_eq!(result, AlecResult::Ok);
        assert!(output_len > 0);

        // Encoding with NULL source_id should also work (defaults to 0)
        let result2 = alec_encode_value(
            enc,
            22.5,
            1,
            ptr::null(),
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );
        assert_eq!(result2, AlecResult::Ok);

        alec_encoder_free(enc);
    }

    #[test]
    fn test_hash_source_id() {
        // NULL returns 0
        assert_eq!(hash_source_id(ptr::null()), 0);

        // Non-null returns a deterministic hash in 1..=127 (1-byte varint)
        let a = b"temperature\0";
        let b = b"pressure\0";
        let ha = hash_source_id(a.as_ptr() as *const c_char);
        let hb = hash_source_id(b.as_ptr() as *const c_char);
        assert!(
            ha >= 1 && ha <= 127,
            "hash out of 1-byte varint range: {}",
            ha
        );
        assert!(
            hb >= 1 && hb <= 127,
            "hash out of 1-byte varint range: {}",
            hb
        );
        assert_ne!(ha, hb);

        // Same input → same hash
        let ha2 = hash_source_id(a.as_ptr() as *const c_char);
        assert_eq!(ha, ha2);
    }

    #[test]
    fn test_encode_decode_roundtrip() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();

        let original_value = 22.5;
        let mut encoded = [0u8; 256];
        let mut encoded_len: usize = 0;

        // Encode
        let result = alec_encode_value(
            enc,
            original_value,
            12345,
            ptr::null(),
            encoded.as_mut_ptr(),
            encoded.len(),
            &mut encoded_len,
        );
        assert_eq!(result, AlecResult::Ok);

        // Decode
        let mut decoded_value: f64 = 0.0;
        let mut decoded_timestamp: u64 = 0;
        let result = alec_decode_value(
            dec,
            encoded.as_ptr(),
            encoded_len,
            &mut decoded_value,
            &mut decoded_timestamp,
        );
        assert_eq!(result, AlecResult::Ok);
        assert!((decoded_value - original_value).abs() < 0.01);

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    // ============================================================================
    // Bloc A1: Config FFI + keyframe + gap detection
    // ============================================================================

    #[test]
    fn test_encoder_config_defaults_constants() {
        // Guard against silent drift of the Milesight-integration defaults.
        assert_eq!(ALEC_DEFAULT_HISTORY_SIZE, 20);
        assert_eq!(ALEC_DEFAULT_MAX_PATTERNS, 256);
        assert_eq!(ALEC_DEFAULT_MAX_MEMORY_BYTES, 2048);
        assert_eq!(ALEC_DEFAULT_KEYFRAME_INTERVAL, 50);
        assert!(ALEC_DEFAULT_SMART_RESYNC);

        let d = AlecEncoderConfig::defaults();
        assert_eq!(d.history_size, ALEC_DEFAULT_HISTORY_SIZE);
        assert_eq!(d.max_patterns, ALEC_DEFAULT_MAX_PATTERNS);
        assert_eq!(d.max_memory_bytes, ALEC_DEFAULT_MAX_MEMORY_BYTES);
        assert_eq!(d.keyframe_interval, ALEC_DEFAULT_KEYFRAME_INTERVAL);
        assert!(d.smart_resync);
    }

    #[test]
    fn test_encoder_new_with_config_null_uses_defaults() {
        let enc = alec_encoder_new_with_config(ptr::null());
        assert!(!enc.is_null());
        let e = unsafe { &*enc };
        assert_eq!(e.keyframe_interval, ALEC_DEFAULT_KEYFRAME_INTERVAL);
        assert!(e.smart_resync);
        assert!(!e.force_keyframe_pending);
        assert_eq!(e.messages_since_keyframe, 0);
        alec_encoder_free(enc);
    }

    #[test]
    fn test_encoder_new_with_config_custom() {
        let cfg = AlecEncoderConfig {
            history_size: 10,
            max_patterns: 128,
            max_memory_bytes: 1024,
            keyframe_interval: 25,
            smart_resync: false,
            num_channels: 0,
        };
        let enc = alec_encoder_new_with_config(&cfg);
        assert!(!enc.is_null());
        let e = unsafe { &*enc };
        assert_eq!(e.keyframe_interval, 25);
        assert!(!e.smart_resync);
        alec_encoder_free(enc);
    }

    #[test]
    fn test_encoder_new_with_config_zero_uses_defaults() {
        // Numeric fields set to 0 (except keyframe_interval) should
        // fall back to the Milesight defaults.
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 0, // 0 means "disabled", kept as-is
            smart_resync: true,
            num_channels: 0,
        };
        let enc = alec_encoder_new_with_config(&cfg);
        assert!(!enc.is_null());
        let e = unsafe { &*enc };
        // keyframe_interval=0 must be preserved verbatim (disabled).
        assert_eq!(e.keyframe_interval, 0);
        // Encoding should still succeed — history/patterns/memory got defaults.
        let mut output = [0u8; 256];
        let mut output_len: usize = 0;
        let result = alec_encode_value(
            enc,
            22.5,
            0,
            ptr::null(),
            output.as_mut_ptr(),
            output.len(),
            &mut output_len,
        );
        assert_eq!(result, AlecResult::Ok);
        alec_encoder_free(enc);
    }

    #[test]
    fn test_force_keyframe_sets_flag() {
        let enc = alec_encoder_new();
        assert!(!enc.is_null());
        assert!(!unsafe { &*enc }.force_keyframe_pending);
        alec_force_keyframe(enc);
        assert!(unsafe { &*enc }.force_keyframe_pending);
        alec_encoder_free(enc);
    }

    #[test]
    fn test_force_keyframe_null_is_noop() {
        // Must not crash on NULL.
        alec_force_keyframe(ptr::null_mut());
    }

    #[test]
    fn test_force_keyframe_respects_smart_resync_disabled() {
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 50,
            smart_resync: false,
            num_channels: 0,
        };
        let enc = alec_encoder_new_with_config(&cfg);
        alec_force_keyframe(enc);
        // smart_resync=false → force_keyframe is a no-op.
        assert!(!unsafe { &*enc }.force_keyframe_pending);
        alec_encoder_free(enc);
    }

    #[test]
    fn test_gap_detected_null_decoder() {
        let mut gap: u8 = 42;
        let detected = alec_decoder_gap_detected(ptr::null(), &mut gap);
        assert!(!detected);
        assert_eq!(gap, 0);

        // NULL out_gap_size is also fine.
        let detected2 = alec_decoder_gap_detected(ptr::null(), ptr::null_mut());
        assert!(!detected2);
    }

    #[test]
    fn test_gap_detected_fresh_decoder() {
        // No decode has happened yet — no gap.
        let dec = alec_decoder_new();
        let mut gap: u8 = 99;
        let detected = alec_decoder_gap_detected(dec, &mut gap);
        assert!(!detected);
        assert_eq!(gap, 0);
        alec_decoder_free(dec);
    }

    /// End-to-end: encode 5 multi-frames, drop two between frame #1 and #2
    /// from the decoder's perspective, verify the gap is reported.
    #[test]
    fn test_gap_detected_after_dropped_frames() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();

        let values: [f64; 4] = [22.0, 22.5, 23.0, 22.8];
        let mut frames: Vec<Vec<u8>> = Vec::new();
        for _ in 0..5 {
            let mut out = [0u8; 128];
            let mut out_len = 0usize;
            let res = alec_encode_multi(
                enc,
                values.as_ptr(),
                values.len(),
                ptr::null(),
                ptr::null(),
                ptr::null(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(res, AlecResult::Ok);
            frames.push(out[..out_len].to_vec());
        }

        // Decode frame 0 (no gap yet).
        let mut vals = [0f64; 4];
        let mut vcount: usize = 0;
        let r0 = alec_decode_multi(
            dec,
            frames[0].as_ptr(),
            frames[0].len(),
            vals.as_mut_ptr(),
            vals.len(),
            &mut vcount,
        );
        assert_eq!(r0, AlecResult::Ok);
        let mut gap: u8 = 0;
        assert!(!alec_decoder_gap_detected(dec, &mut gap));
        assert_eq!(gap, 0);

        // Skip frames 1 and 2, decode frame 3 → gap of 2.
        let r3 = alec_decode_multi(
            dec,
            frames[3].as_ptr(),
            frames[3].len(),
            vals.as_mut_ptr(),
            vals.len(),
            &mut vcount,
        );
        assert_eq!(r3, AlecResult::Ok);
        let mut gap: u8 = 0;
        assert!(alec_decoder_gap_detected(dec, &mut gap));
        assert_eq!(gap, 2);

        // Decode frame 4 — contiguous with frame 3 → no gap.
        let r4 = alec_decode_multi(
            dec,
            frames[4].as_ptr(),
            frames[4].len(),
            vals.as_mut_ptr(),
            vals.len(),
            &mut vcount,
        );
        assert_eq!(r4, AlecResult::Ok);
        let mut gap: u8 = 99;
        assert!(!alec_decoder_gap_detected(dec, &mut gap));
        assert_eq!(gap, 0);

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// cbindgen should surface the new symbols. This test is a compile-time
    /// guarantee that the FFI entry points exist with the expected signatures.
    #[test]
    fn test_ffi_symbols_exist() {
        let _new: extern "C" fn(*const AlecEncoderConfig) -> *mut AlecEncoder =
            alec_encoder_new_with_config;
        let _force: extern "C" fn(*mut AlecEncoder) = alec_force_keyframe;
        let _gap: extern "C" fn(*const AlecDecoder, *mut u8) -> bool = alec_decoder_gap_detected;
        let _enc_fixed: extern "C" fn(
            *mut AlecEncoder,
            *const f64,
            usize,
            *mut u8,
            usize,
            *mut usize,
        ) -> AlecResult = alec_encode_multi_fixed;
        let _dec_fixed: extern "C" fn(
            *mut AlecDecoder,
            *const u8,
            usize,
            *mut f64,
            usize,
            *mut usize,
            *mut u16,
            *mut bool,
        ) -> AlecResult = alec_decode_multi_fixed;
        let _dec_new_cfg: extern "C" fn(*const AlecEncoderConfig) -> *mut AlecDecoder =
            alec_decoder_new_with_config;
        let _dec_reset: extern "C" fn(*mut AlecDecoder) = alec_decoder_reset;
        let _ctx_save: extern "C" fn(*const AlecDecoder, *mut u8, usize, *mut usize) -> AlecResult =
            alec_decoder_context_save;
        let _ctx_load: extern "C" fn(*mut AlecDecoder, *const u8, usize) -> AlecResult =
            alec_decoder_context_load;
    }

    // ========================================================================
    // Bloc B5 — Compact fixed-channel tests
    //
    // A synthesized slow-drift EM500-CO2 dataset is used in lieu of a
    // 99-message CSV that is not shipped with the repo. The dataset is
    // built to reproduce the regime described in docs/CONTEXT.md:
    //   - 5 channels: battery / temperature / humidity / CO2 / pressure
    //   - 99 messages at a 10-minute cadence
    //   - slow drift on all channels → most channels encode as Repeated
    //     or Delta8 in steady state
    // ========================================================================

    /// Deterministic 99-message EM500-CO2 slow-drift dataset.
    ///
    /// Real EM500-CO2 sensors are polled every 10 minutes on a very
    /// slow-drift signal. The raw sensor has coarse quantization
    /// (battery 0.001V, temperature 0.01°C, humidity 0.1%, CO2 1ppm,
    /// pressure 0.01hPa) and values typically REPEAT across many
    /// consecutive reads. This dataset reproduces that regime with
    /// step changes that are rare and small (≤1 quantization step),
    /// matching the ~58% Repeated / ~42% Delta8 distribution cited
    /// in docs/CONTEXT.md.
    fn em500_co2_dataset() -> Vec<[f64; 5]> {
        const N: usize = 99;
        let mut out = Vec::with_capacity(N);
        // Values change rarely; most frames carry exact repeats.
        // Channel 0: battery (V). Drops by 1mV every ~33 frames.
        // Channel 1: temperature (°C). Walks ±0.01 every ~4 frames.
        // Channel 2: humidity (%). Walks ±0.1 every ~7 frames.
        // Channel 3: CO2 (ppm). +1 ppm every ~3 frames (slow ramp).
        // Channel 4: pressure (hPa). ±0.01 every ~11 frames.
        for i in 0..N {
            // Battery at 10mV granularity (real LoRaWAN battery
            // telemetry — devices don't change 1mV in 10 minutes,
            // and scale_factor=100 can't represent sub-0.01V anyway).
            let battery = 3.60 - 0.01 * ((i / 33) as f64);
            let temp_step = if i % 8 < 4 { 0.01 } else { 0.00 };
            let temperature = 22.50 + temp_step;
            let humidity = 45.0 + 0.1 * ((i / 7) % 3) as f64;
            let co2 = 420.0 + (i / 3) as f64;
            let pressure = 1013.25 + 0.01 * ((i / 11) % 3) as f64;
            out.push([battery, temperature, humidity, co2, pressure]);
        }
        out
    }

    /// Run the whole dataset through a fresh encoder+decoder pair and
    /// return (per-frame wire bytes, per-frame decoded values).
    fn encode_decode_dataset(
        data: &[[f64; 5]],
        cfg: Option<AlecEncoderConfig>,
    ) -> (Vec<Vec<u8>>, Vec<[f64; 5]>) {
        let enc = match cfg {
            Some(c) => alec_encoder_new_with_config(&c),
            None => alec_encoder_new(),
        };
        let dec = alec_decoder_new();

        let mut frames = Vec::with_capacity(data.len());
        let mut decoded = Vec::with_capacity(data.len());

        let mut out = [0u8; 128];
        let mut out_len: usize = 0;
        let mut values = [0f64; 5];

        for row in data {
            let r = alec_encode_multi_fixed(
                enc,
                row.as_ptr(),
                row.len(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(r, AlecResult::Ok);
            let frame = out[..out_len].to_vec();

            let r2 = alec_decode_multi_fixed(
                dec,
                frame.as_ptr(),
                frame.len(),
                values.as_mut_ptr(),
                values.len(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
            );
            assert_eq!(
                r2,
                AlecResult::Ok,
                "decode failed at frame {}",
                frames.len()
            );

            frames.push(frame);
            decoded.push(values);
        }

        alec_encoder_free(enc);
        alec_decoder_free(dec);
        (frames, decoded)
    }

    /// B5-1. Encode 99 real-shaped EM500-CO2 rows through the FFI,
    /// decode each frame, and verify the values round-trip within
    /// one quantization step.
    ///
    /// Delta encoding uses a global scale_factor of 100 (1/100
    /// resolution), so each frame carries ≤0.005 of quantization
    /// error per channel. The moving-average prediction residue on
    /// top of that is bounded by the history EMA alpha — with
    /// slow-drift inputs the combined error stays well under
    /// `0.01` (one quantization step).
    #[test]
    fn test_encode_decode_fixed_roundtrip_5ch() {
        let data = em500_co2_dataset();
        let (_frames, decoded) = encode_decode_dataset(&data, None);
        assert_eq!(decoded.len(), data.len());
        // Allowed drift is expressed in units of each channel's
        // native sensor resolution at `scale_factor=100` granularity:
        //   battery  0.01 V (LoRaWAN 10mV telemetry)
        //   temp     0.01 °C
        //   humidity 0.1 %
        //   CO2      1 ppm
        //   pressure 0.01 hPa
        // We allow ≤ 1 physical LSB of drift on every channel, which
        // is effectively lossless at the application level.
        let max_drift = [0.01_f64, 0.01, 0.1, 1.0, 0.01];
        for (i, (src, dst)) in data.iter().zip(decoded.iter()).enumerate() {
            for ch in 0..5 {
                let diff = (src[ch] - dst[ch]).abs();
                assert!(
                    diff <= max_drift[ch] + 1e-9,
                    "frame {} ch {}: expected {}, got {}, diff {} (max {})",
                    i,
                    ch,
                    src[ch],
                    dst[ch],
                    diff,
                    max_drift[ch]
                );
            }
        }
    }

    /// B5-2. Property: from message 8 onward, the compact wire
    /// frame must fit in the 11-byte LoRaWAN ceiling on the slow-drift
    /// EM500-CO2 profile.
    #[test]
    fn test_fixed_header_11b_ceiling() {
        let data = em500_co2_dataset();
        // Use a large keyframe_interval to stop periodic keyframes
        // from interfering with the steady-state size assertion.
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 10_000,
            smart_resync: false,
            num_channels: 0,
        };
        let (frames, _decoded) = encode_decode_dataset(&data, Some(cfg));

        // Skip the warm-up window. Message 0 has no prediction at all,
        // and a handful of subsequent messages still produce Raw32 for
        // a channel while the per-source EMA settles. Docs/CONTEXT.md
        // assumes frames from ~#8 onward are steady-state.
        let warmup = 8;
        for (i, frame) in frames.iter().enumerate().skip(warmup) {
            assert!(
                frame.len() <= 11,
                "frame #{} was {} bytes > 11B ceiling",
                i,
                frame.len()
            );
        }
    }

    /// B5-3. The very first frame has no prediction history available
    /// so every channel falls back to Raw32 — this frame is expected
    /// to exceed the 11-byte LoRaWAN ceiling, and the caller must
    /// detect that and send a legacy TLV frame instead.
    #[test]
    fn test_cold_start_first_frame() {
        let data = em500_co2_dataset();
        let enc = alec_encoder_new();
        let mut out = [0u8; 64];
        let mut out_len: usize = 0;
        let r = alec_encode_multi_fixed(
            enc,
            data[0].as_ptr(),
            data[0].len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        );
        assert_eq!(r, AlecResult::Ok);

        // Layout: 1B marker + 4B header + 2B bitmap (5 ch × 2 bits = 10 bits)
        //         + 5 × 4B Raw32 = 27 bytes exactly.
        assert_eq!(out_len, 27, "cold-start frame should be 27B");
        assert!(out_len > 11, "cold-start frame must exceed 11B ceiling");
        // Marker is the data marker (cold start frame is NOT a keyframe —
        // the FFI only emits 0xA2 when the force/periodic rules fire).
        assert_eq!(out[0], 0xA1);
        alec_encoder_free(enc);
    }

    /// B5-4. Context version truncates u32 → u16 and wraps at 65535.
    /// The decoder must accept the wrap without flagging a mismatch.
    #[test]
    fn test_ctx_ver_wraparound() {
        // Start the encoder's context just below the wrap boundary.
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();

        unsafe {
            (*enc).context.set_version(65530);
            (*dec).context.set_version(65530);
        }

        let row = [3.6, 22.5, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];
        let mut out_len: usize = 0;
        let mut values = [0f64; 5];

        let mut seen_pre_wrap = false;
        let mut seen_post_wrap = false;
        // Each encode-step observes 5 channels → +5 ctx_version per frame.
        // 10 frames × 5 obs = 50 obs → passes through 65535 → 0.
        for i in 0..10 {
            let r = alec_encode_multi_fixed(
                enc,
                row.as_ptr(),
                row.len(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(r, AlecResult::Ok);

            // Read the wire context_version.
            let cv = u16::from_be_bytes([out[3], out[4]]);
            if cv > 60_000 {
                seen_pre_wrap = true;
            }
            if cv < 1_000 {
                seen_post_wrap = true;
            }

            let r2 = alec_decode_multi_fixed(
                dec,
                out.as_ptr(),
                out_len,
                values.as_mut_ptr(),
                values.len(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
            );
            assert_eq!(
                r2,
                AlecResult::Ok,
                "decode failed at wrap boundary, frame {}",
                i
            );
        }

        assert!(seen_pre_wrap, "never observed a ctx_ver near the wrap edge");
        assert!(seen_post_wrap, "ctx_ver never wrapped to a low value");

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// B5-5. A non-ALEC first byte (e.g. the legacy TLV header byte)
    /// must return a clean error, NOT panic.
    #[test]
    fn test_marker_byte_dispatch() {
        let data = em500_co2_dataset();
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();

        let mut out = [0u8; 64];
        let mut out_len: usize = 0;
        let r = alec_encode_multi_fixed(
            enc,
            data[0].as_ptr(),
            data[0].len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        );
        assert_eq!(r, AlecResult::Ok);
        assert_eq!(out[0], 0xA1); // regular data marker

        // 0xA1 frame decodes successfully.
        let mut values = [0f64; 5];
        let r_ok = alec_decode_multi_fixed(
            dec,
            out.as_ptr(),
            out_len,
            values.as_mut_ptr(),
            values.len(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        );
        assert_eq!(r_ok, AlecResult::Ok);

        // Corrupt marker to a known-not-ALEC byte (legacy TLV first
        // byte is 0x7A for MessageType::DataFixedChannel but a
        // production TLV message begins with 0x5A = Data | P3 | v1).
        let mut corrupt = out[..out_len].to_vec();
        corrupt[0] = 0x5A;
        let r_err = alec_decode_multi_fixed(
            alec_decoder_new(), // fresh decoder so prior state doesn't leak
            corrupt.as_ptr(),
            corrupt.len(),
            values.as_mut_ptr(),
            values.len(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        );
        assert_eq!(r_err, AlecResult::ErrorInvalidInput);

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// B5-6. With `keyframe_interval=10` on a stable signal, the
    /// frames at interval boundaries must be larger (Raw32 for all
    /// channels) while the in-between frames should be compact
    /// (mostly Repeated/Delta8).
    #[test]
    fn test_keyframe_forced_at_interval() {
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 10,
            smart_resync: true,
            num_channels: 0,
        };
        let enc = alec_encoder_new_with_config(&cfg);
        // Stable signal: identical row every frame.
        let row = [3.6, 22.5, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];
        let mut out_len: usize = 0;
        let mut frames: Vec<(usize, u8)> = Vec::new();

        for _ in 0..25 {
            let r = alec_encode_multi_fixed(
                enc,
                row.as_ptr(),
                row.len(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(r, AlecResult::Ok);
            frames.push((out_len, out[0]));
        }

        // Layout sizes for 5 channels:
        //   keyframe (Raw32 ×5) = 1 + 4 + 2 + 20 = 27 bytes, marker 0xA2
        //   steady   (Repeated ×5) = 1 + 4 + 2 + 0 = 7 bytes, marker 0xA1
        let keyframe_indices: Vec<usize> = frames
            .iter()
            .enumerate()
            .filter(|(_, (_, m))| *m == 0xA2)
            .map(|(i, _)| i)
            .collect();

        // Frame #10 and #20 are the interval boundaries (counter reaches 10).
        assert_eq!(keyframe_indices, vec![10, 20]);
        for (i, (len, marker)) in frames.iter().enumerate() {
            if *marker == 0xA2 {
                assert_eq!(*len, 27, "keyframe at #{} should be 27B, got {}", i, *len);
            } else {
                assert_eq!(*marker, 0xA1);
                // Frame 0 is the cold-start Raw32 frame (27B).
                if i == 0 {
                    assert_eq!(*len, 27);
                } else {
                    assert!(*len <= 11, "data frame at #{} is {} bytes > 11B", i, *len);
                }
            }
        }

        alec_encoder_free(enc);
    }

    /// Diagnostic (ignored by default) — prints per-frame sizes and
    /// encoding distribution for the synthesized EM500-CO2 dataset.
    /// Run with `cargo test -p alec-ffi diag_fixed_sizes -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn diag_fixed_sizes() {
        let data = em500_co2_dataset();
        // Disable periodic keyframes so the observed sizes reflect
        // pure steady-state encoding.
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 10_000,
            smart_resync: false,
            num_channels: 0,
        };
        let (frames, _) = encode_decode_dataset(&data, Some(cfg));
        let mut counts = [0u32; 4]; // Repeated, Delta8, Delta16, Raw32
        for frame in &frames {
            // 5 channels → 2 bitmap bytes starting at offset 5.
            let b0 = frame[5];
            let b1 = frame[6];
            for i in 0..5 {
                let bits = if i < 4 { (b0 >> (i * 2)) & 3 } else { b1 & 3 };
                counts[bits as usize] += 1;
            }
        }
        let total_ch = 99 * 5;
        println!("\n=== FIXED-CHANNEL DIAGNOSTIC ===");
        let sizes: Vec<usize> = frames.iter().map(|f| f.len()).collect();
        let total: usize = sizes.iter().sum();
        println!(
            "99 frames: total={} avg={:.2} B/frame  min={} max={}",
            total,
            total as f64 / 99.0,
            sizes.iter().min().unwrap(),
            sizes.iter().max().unwrap()
        );
        let warm = 8;
        let steady: Vec<usize> = sizes[warm..].to_vec();
        let stotal: usize = steady.iter().sum();
        println!(
            "steady (frame>={}): total={} avg={:.2} B/frame  max={}",
            warm,
            stotal,
            stotal as f64 / steady.len() as f64,
            steady.iter().max().unwrap()
        );
        let labels = ["Repeated", "Delta8", "Delta16", "Raw32"];
        println!("encoding distribution across {} channels:", total_ch);
        for i in 0..4 {
            println!(
                "  {:10}: {:4}  ({:.1}%)",
                labels[i],
                counts[i],
                100.0 * counts[i] as f64 / total_ch as f64
            );
        }
        // Dump a typical steady-state frame.
        let idx = 30;
        println!(
            "Frame #{}: {} bytes = {:02X?}",
            idx,
            frames[idx].len(),
            &frames[idx][..]
        );
    }

    /// B5-7. `alec_force_keyframe` forces the very next frame to be
    /// a keyframe (marker 0xA2, Raw32 for every channel), and the
    /// frame after that returns to the compact encoding.
    #[test]
    fn test_force_keyframe_ffi() {
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 10_000, // avoid periodic keyframes
            smart_resync: true,
            num_channels: 0,
        };
        let enc = alec_encoder_new_with_config(&cfg);
        let row = [3.6, 22.5, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];
        let mut out_len: usize = 0;

        // Warm up the context with a few stable frames.
        for _ in 0..5 {
            let r = alec_encode_multi_fixed(
                enc,
                row.as_ptr(),
                row.len(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(r, AlecResult::Ok);
        }
        // After warm-up the frame is compact (data marker).
        assert_eq!(out[0], 0xA1);
        let warm_len = out_len;
        assert!(
            warm_len <= 11,
            "warm frame should be <=11B, got {}",
            warm_len
        );

        // Downlink-style force: next encode must be a keyframe.
        alec_force_keyframe(enc);
        let r = alec_encode_multi_fixed(
            enc,
            row.as_ptr(),
            row.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        );
        assert_eq!(r, AlecResult::Ok);
        assert_eq!(out[0], 0xA2, "forced frame must carry the keyframe marker");
        assert_eq!(
            out_len, 27,
            "forced keyframe must be Raw32 for all channels"
        );

        // The frame after the keyframe must be compact again.
        let r = alec_encode_multi_fixed(
            enc,
            row.as_ptr(),
            row.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        );
        assert_eq!(r, AlecResult::Ok);
        assert_eq!(out[0], 0xA1, "post-keyframe frame must be a data frame");
        assert!(
            out_len <= 11,
            "post-keyframe frame should be <=11B, got {}",
            out_len
        );

        alec_encoder_free(enc);
    }

    // ========================================================================
    // Bloc C5 — Packet-loss recovery tests
    // ========================================================================

    /// Helper: build a matched encoder + decoder pair with
    /// a small keyframe_interval suitable for test runtime.
    fn new_pair(keyframe_interval: u32) -> (*mut AlecEncoder, *mut AlecDecoder) {
        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval,
            smart_resync: true,
            num_channels: 0,
        };
        (alec_encoder_new_with_config(&cfg), alec_decoder_new())
    }

    /// Encode one frame on `enc` into `out` and return its length.
    fn do_encode(enc: *mut AlecEncoder, row: &[f64; 5], out: &mut [u8; 64]) -> usize {
        let mut n: usize = 0;
        let r = alec_encode_multi_fixed(
            enc,
            row.as_ptr(),
            row.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut n,
        );
        assert_eq!(r, AlecResult::Ok);
        n
    }

    /// Decode `frame` on `dec`. Returns the decoded values.
    fn do_decode(dec: *mut AlecDecoder, frame: &[u8]) -> [f64; 5] {
        let mut values = [0f64; 5];
        let r = alec_decode_multi_fixed(
            dec,
            frame.as_ptr(),
            frame.len(),
            values.as_mut_ptr(),
            values.len(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        );
        assert_eq!(r, AlecResult::Ok);
        values
    }

    /// C5-1. `reset_to_baseline` wipes per-channel prediction state
    /// so the next encode can only fall back to Raw32 (no prediction
    /// to delta against). Existing patterns in the dictionary are
    /// preserved (the FFI path never registers any, so the dict is
    /// empty to begin with — but the contract matters for preloaded
    /// contexts).
    #[test]
    fn test_reset_to_baseline_wipes_stats() {
        let (enc, _dec) = new_pair(10_000); // no periodic keyframes
        let row = [3.60, 22.50, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];

        // Build up 20 frames of prediction state.
        for _ in 0..20 {
            do_encode(enc, &row, &mut out);
        }
        // Context should now hold non-trivial state.
        let e = unsafe { &*enc };
        assert!(e.context.last_value(1).is_some());
        assert!(e.context.last_value(5).is_some());
        let pre_version = e.context.version();

        // Reset.
        unsafe { &mut *enc }.context.reset_to_baseline();

        // All per-channel last_value are cleared — but the version
        // counter is preserved (see C1 contract).
        let e = unsafe { &*enc };
        assert!(e.context.last_value(1).is_none());
        assert!(e.context.last_value(5).is_none());
        assert_eq!(e.context.version(), pre_version);

        // Next encode, with no prediction available, must fall back
        // to Raw32 on every channel — same wire shape as a keyframe
        // (minus the 0xA2 marker, since this is a regular frame).
        // Layout: 1 marker + 4 header + 2 bitmap + 5×Raw32 = 27 B.
        let n = do_encode(enc, &row, &mut out);
        assert_eq!(n, 27, "post-reset frame must be Raw32-all-channels (27 B)");
        assert_eq!(out[0], 0xA1);
        let b0 = out[5];
        let b1 = out[6];
        // All bitmap bits = 0b11 = Raw32.
        assert_eq!(b0, 0b1111_1111);
        assert_eq!(b1 & 0b11, 0b11);

        alec_encoder_free(enc);
    }

    /// C5-2. Simulate a 4-frame gap (encoder produces frames 0..=20
    /// but frames 15..=18 never reach the decoder). On frame 19 the
    /// decoder must detect gap_size=4 and trigger a reset; full
    /// recovery must happen at the next periodic keyframe (frame 20
    /// with keyframe_interval=10).
    #[test]
    fn test_packet_loss_recovery_at_keyframe() {
        let (enc, dec) = new_pair(10);
        let row = [3.60, 22.50, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];
        let mut frames: Vec<Vec<u8>> = Vec::new();

        // Encode 21 frames (0..=20). Frame 10 and 20 are keyframes.
        for _ in 0..=20 {
            let n = do_encode(enc, &row, &mut out);
            frames.push(out[..n].to_vec());
        }
        assert_eq!(frames[10][0], 0xA2, "frame 10 must be a keyframe");
        assert_eq!(frames[20][0], 0xA2, "frame 20 must be a keyframe");

        // Decode frames 0..=14 normally.
        for f in &frames[0..=14] {
            do_decode(dec, f);
        }
        // Do NOT decode frames 15..=18 — simulate 4 dropped uplinks.

        // Decode frame 19 → gap_size = 4 reported, reset triggered.
        do_decode(dec, &frames[19]);
        let mut gap: u8 = 0;
        assert!(alec_decoder_gap_detected(dec, &mut gap));
        assert_eq!(gap, 4, "decoder must report 4-frame gap");

        // After the reset, the decoder's last_value is cleared for
        // every channel, so any subsequent Delta/Repeated-encoded
        // frame would error out. Frame 19 itself does NOT error
        // because we observe the decoded values *after* the reset
        // (re-seeding the context from frame 19's output).

        // Frame 20 is a keyframe — Raw32 for every channel, so it
        // decodes correctly regardless of context state, and it
        // re-synchronises the decoder for good.
        let values_20 = do_decode(dec, &frames[20]);
        for (ch, &v) in row.iter().enumerate() {
            let tol = [0.01_f64, 0.01, 0.1, 1.0, 0.01][ch];
            assert!(
                (v - values_20[ch]).abs() <= tol,
                "ch {}: expected {}, got {}",
                ch,
                v,
                values_20[ch]
            );
        }

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// C5-3. No silent corruption: when the encoder emits a stable
    /// signal and the decoder drops frame 20, subsequent frames
    /// 21..=49 are either clearly divergent or clearly re-synced
    /// by the next keyframe at frame 50. Frame 50+ MUST decode
    /// within sensor resolution.
    #[test]
    fn test_no_silent_corruption() {
        let (enc, dec) = new_pair(50);
        let mut out = [0u8; 64];
        let mut frames: Vec<Vec<u8>> = Vec::new();
        // Slow-drift signal — mostly Repeated, occasional Delta8.
        let rows: Vec<[f64; 5]> = (0..100)
            .map(|i| [3.60, 22.50, 45.0, 420.0 + (i / 3) as f64, 1013.25])
            .collect();
        for row in &rows {
            let n = do_encode(enc, row, &mut out);
            frames.push(out[..n].to_vec());
        }

        // Decode frames 0..=19 normally.
        for f in &frames[0..=19] {
            do_decode(dec, f);
        }
        // Drop frame 20 entirely.

        // Decode frames 21..=49. The first one triggers reset; the
        // rest may or may not decode successfully (Delta frames
        // error out because there is no prediction after reset). We
        // ignore the outcome — the contract is only that the
        // decoder does not panic and does not silently corrupt the
        // post-keyframe values.
        for f in &frames[21..50] {
            let mut v = [0f64; 5];
            let _ = alec_decode_multi_fixed(
                dec,
                f.as_ptr(),
                f.len(),
                v.as_mut_ptr(),
                v.len(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
            );
        }

        // Frame 50 is a keyframe — decode must succeed and values
        // must match the corresponding input within sensor LSB.
        let values_50 = do_decode(dec, &frames[50]);
        assert_eq!(frames[50][0], 0xA2);
        let expected = rows[50];
        let tols = [0.01_f64, 0.01, 0.1, 1.0, 0.01];
        for ch in 0..5 {
            assert!(
                (expected[ch] - values_50[ch]).abs() <= tols[ch] + 1e-9,
                "ch {} at frame 50: expected {}, got {}",
                ch,
                expected[ch],
                values_50[ch]
            );
        }
        // Frames 51..=60 must also decode correctly now that the
        // context is re-synced.
        for i in 51..=60 {
            let values = do_decode(dec, &frames[i]);
            for ch in 0..5 {
                assert!(
                    (rows[i][ch] - values[ch]).abs() <= tols[ch] + 1e-9,
                    "ch {} at frame {}: expected {}, got {}",
                    ch,
                    i,
                    rows[i][ch],
                    values[ch]
                );
            }
        }

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// C5-4. Smart resync via the downlink handler: decoder detects
    /// a gap and calls `alec_downlink_handler(enc, [0xFF], 1)` to
    /// request an immediate keyframe. Recovery happens on the very
    /// next uplink, not at the far-off periodic keyframe.
    #[test]
    fn test_smart_resync_downlink() {
        let (enc, dec) = new_pair(10_000); // no periodic keyframes
        let row = [3.60, 22.50, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];
        let mut frames: Vec<Vec<u8>> = Vec::new();

        // Encode 10 frames. Decoder drops frame 5.
        for _ in 0..10 {
            let n = do_encode(enc, &row, &mut out);
            frames.push(out[..n].to_vec());
        }
        for f in &frames[0..=4] {
            do_decode(dec, f);
        }
        // Skip frame 5. Decoding frame 6..=9 will produce divergent
        // values, but that's fine — the point is the RESYNC.
        for f in &frames[6..=9] {
            let mut v = [0f64; 5];
            let _ = alec_decode_multi_fixed(
                dec,
                f.as_ptr(),
                f.len(),
                v.as_mut_ptr(),
                v.len(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
            );
        }

        // Decoder realises it's out of sync — simulate the sidecar
        // checking alec_decoder_gap_detected and sending a 0xFF
        // downlink. The device-side integration calls the downlink
        // handler on the encoder:
        let cmd = [0xFF_u8];
        let r = alec_downlink_handler(enc, cmd.as_ptr(), cmd.len());
        assert_eq!(r, AlecResult::Ok);
        assert!(
            unsafe { &*enc }.force_keyframe_pending,
            "downlink 0xFF must arm the force-keyframe flag"
        );

        // The very next uplink (frame 10) MUST be a keyframe.
        let n = do_encode(enc, &row, &mut out);
        assert_eq!(out[0], 0xA2, "post-downlink frame must be a keyframe");
        assert_eq!(n, 27);

        // Decoder catches up immediately.
        let values = do_decode(dec, &out[..n]);
        let tols = [0.01_f64, 0.01, 0.1, 1.0, 0.01];
        for ch in 0..5 {
            assert!(
                (row[ch] - values[ch]).abs() <= tols[ch] + 1e-9,
                "ch {}: expected {}, got {}",
                ch,
                row[ch],
                values[ch]
            );
        }

        // Without smart resync, recovery would have required waiting
        // for the next periodic keyframe at frame keyframe_interval
        // (50 by default) — an 8h drift on EM500-CO2's 10-min cadence.
        // With smart resync, recovery happened on frame 10 — a 10-min
        // drift. That is the order-of-magnitude improvement.

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// C5-5. An unknown downlink command is rejected with
    /// `ALEC_ERROR_INVALID_INPUT` and leaves the encoder state
    /// unchanged.
    #[test]
    fn test_downlink_handler_invalid_command() {
        let enc = alec_encoder_new();
        assert!(!unsafe { &*enc }.force_keyframe_pending);

        let cmd = [0x00_u8];
        let r = alec_downlink_handler(enc, cmd.as_ptr(), cmd.len());
        assert_eq!(r, AlecResult::ErrorInvalidInput);
        assert!(
            !unsafe { &*enc }.force_keyframe_pending,
            "unknown downlink must NOT arm the force-keyframe flag"
        );

        // Another uncommon but not-special byte.
        let cmd = [0x7E_u8, 0xFF, 0xAA];
        let r = alec_downlink_handler(enc, cmd.as_ptr(), cmd.len());
        assert_eq!(r, AlecResult::ErrorInvalidInput);
        assert!(!unsafe { &*enc }.force_keyframe_pending);

        // NULL / empty inputs are defensively handled.
        assert_eq!(
            alec_downlink_handler(ptr::null_mut(), cmd.as_ptr(), cmd.len()),
            AlecResult::ErrorNullPointer
        );
        assert_eq!(
            alec_downlink_handler(enc, ptr::null(), 1),
            AlecResult::ErrorNullPointer
        );
        assert_eq!(
            alec_downlink_handler(enc, cmd.as_ptr(), 0),
            AlecResult::ErrorInvalidInput
        );

        alec_encoder_free(enc);
    }

    /// C5-6. A deliberately-corrupted context_version on the decoder
    /// triggers a mismatch when the next non-keyframe arrives; the
    /// decoder resets and recovers at the subsequent keyframe.
    #[test]
    fn test_context_mismatch_triggers_reset() {
        let (enc, dec) = new_pair(10);
        let row = [3.60, 22.50, 45.0, 420.0, 1013.25];
        let mut out = [0u8; 64];
        let mut frames: Vec<Vec<u8>> = Vec::new();

        // Encode 12 frames (0..=11); frame 10 is a keyframe.
        for _ in 0..=11 {
            let n = do_encode(enc, &row, &mut out);
            frames.push(out[..n].to_vec());
        }

        // Decode 0..=8 normally.
        for f in &frames[0..=8] {
            do_decode(dec, f);
        }

        // Corrupt the decoder's tracked ctx_ver to something that
        // looks like a backwards jump (outside ctx_version_compatible's
        // tolerance of 256 forward units). The encoder's ctx_ver is
        // currently 9*5=45 post-observation; we pretend the decoder
        // last saw a version ~30k ahead so the next non-keyframe
        // trips the mismatch detector.
        unsafe { &mut *dec }.decoder.reset();
        // reset() clears last_fixed_sequence too, so replay a frame
        // to re-arm sequence tracking:
        do_decode(dec, &frames[8]);
        // Now set last_fixed_ctx_version artificially by pushing
        // through a synthesised decode state. A cleaner API would be
        // nice — for the test we use the *encoded* route: change
        // our tracked version by decoding a frame whose payload we
        // hand-crafted. Since that's gnarly, instead we simulate
        // the effect by directly walking into a known-mismatch
        // scenario: inject a frame whose ctx_ver is very far from
        // what the decoder expects.

        // Build a synthetic non-keyframe with an impossible ctx_ver
        // (wire bytes: 0xA1 <seq> <ctx> <bitmap> …). Use frame 9's
        // real bytes but rewrite bytes 3..=4 (ctx_ver).
        let mut tampered = frames[9].clone();
        // Replace ctx_ver with 0x1234 — far from the decoder's
        // current state (which just observed frame 8 ≈ version ~45).
        tampered[3] = 0x12;
        tampered[4] = 0x34;

        // Before the tamper the decoder has seen at least 9 identical
        // readings for channel 1, so its per-source observation count
        // is ≥ 3 and `predict()` reports the `MovingAverage` model.
        use alec::context::PredictionModel;
        let model_before = unsafe { &*dec }.context.predict(1).unwrap().model_type;
        assert_eq!(model_before, PredictionModel::MovingAverage);

        // Decoding the tampered frame must surface a mismatch and
        // trigger `reset_to_baseline()`. The decode itself may
        // produce garbage values for Delta-encoded channels (since
        // the reset happens after decode but before the re-observe),
        // which is acceptable — the contract is that subsequent
        // keyframe decodes are correct.
        let mut v = [0f64; 5];
        let _ = alec_decode_multi_fixed(
            dec,
            tampered.as_ptr(),
            tampered.len(),
            v.as_mut_ptr(),
            v.len(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        );

        // After the reset the history has been wiped. The FFI then
        // re-observes the single tampered frame's output, so each
        // per-channel observation count is exactly 1 and
        // `predict()` reports the `LastValue` model (count < 3
        // branch in SourceStats::predict). If the reset had NOT
        // fired, count would be 10 and the model would still be
        // MovingAverage.
        let model_after = unsafe { &*dec }.context.predict(1).unwrap().model_type;
        assert_eq!(
            model_after,
            PredictionModel::LastValue,
            "reset_to_baseline should have dropped source_stats count below the \
             MovingAverage threshold (count < 3)"
        );

        // Frame 10 is a real keyframe — decode must succeed and
        // values must match the input within sensor tolerance.
        let values_10 = do_decode(dec, &frames[10]);
        assert_eq!(frames[10][0], 0xA2);
        let tols = [0.01_f64, 0.01, 0.1, 1.0, 0.01];
        for ch in 0..5 {
            assert!(
                (row[ch] - values_10[ch]).abs() <= tols[ch] + 1e-9,
                "ch {}: expected {}, got {}",
                ch,
                row[ch],
                values_10[ch]
            );
        }

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    // ========================================================================
    // Bloc D4 — Context persistence FFI tests
    // ========================================================================

    /// Helper: CString-safe sensor type.
    const SENSOR_TYPE: &[u8] = b"em500-co2\0";

    /// Run `frames` rows through the encoder + decoder. Returns the
    /// wire frames for later replay.
    fn drive_pair(enc: *mut AlecEncoder, dec: *mut AlecDecoder, rows: &[[f64; 5]]) -> Vec<Vec<u8>> {
        let mut out = [0u8; 64];
        let mut out_len: usize = 0;
        let mut values = [0f64; 5];
        let mut frames = Vec::with_capacity(rows.len());
        for row in rows {
            let r = alec_encode_multi_fixed(
                enc,
                row.as_ptr(),
                row.len(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(r, AlecResult::Ok);
            let frame = out[..out_len].to_vec();
            let r2 = alec_decode_multi_fixed(
                dec,
                frame.as_ptr(),
                frame.len(),
                values.as_mut_ptr(),
                values.len(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
            );
            assert_eq!(r2, AlecResult::Ok);
            frames.push(frame);
        }
        frames
    }

    /// D4-1. End-to-end in-memory roundtrip: train a decoder's
    /// context, export → import into a fresh decoder, then verify
    /// that both decoders produce identical output for the same
    /// subsequent encoded frames.
    #[test]
    fn test_context_roundtrip_in_memory() {
        // Slow-drift signal so frames stay compact.
        let rows: Vec<[f64; 5]> = (0..30)
            .map(|i| [3.60, 22.50, 45.0, 420.0 + (i / 3) as f64, 1013.25])
            .collect();

        let cfg = AlecEncoderConfig {
            history_size: 0,
            max_patterns: 0,
            max_memory_bytes: 0,
            keyframe_interval: 10_000, // avoid periodic keyframes
            smart_resync: false,
            num_channels: 0,
        };
        let enc = alec_encoder_new_with_config(&cfg);
        let dec_orig = alec_decoder_new();

        // Train.
        let _ = drive_pair(enc, dec_orig, &rows);

        // Export the trained decoder.
        let mut size: usize = 0;
        let r = alec_decoder_export_state_size(
            dec_orig,
            SENSOR_TYPE.as_ptr() as *const c_char,
            &mut size,
        );
        assert_eq!(r, AlecResult::Ok);
        assert!(size > 0 && size < 3072, "export size {} out of range", size);
        let mut buf = vec![0u8; size];
        let mut written: usize = 0;
        let r = alec_decoder_export_state(
            dec_orig,
            SENSOR_TYPE.as_ptr() as *const c_char,
            buf.as_mut_ptr(),
            buf.len(),
            &mut written,
        );
        assert_eq!(r, AlecResult::Ok);
        assert_eq!(written, size);

        // Fresh decoder, import the state.
        let dec_new = alec_decoder_new();
        let r = alec_decoder_import_state(dec_new, buf.as_ptr(), buf.len());
        assert_eq!(r, AlecResult::Ok);

        // Drive 10 more frames on the encoder and decode each
        // through BOTH decoders. Identical output confirms the
        // restored context is operationally equivalent.
        let more: Vec<[f64; 5]> = (30..40)
            .map(|i| [3.60, 22.50, 45.0, 420.0 + (i / 3) as f64, 1013.25])
            .collect();
        let mut out = [0u8; 64];
        let mut out_len: usize = 0;
        for row in &more {
            let r = alec_encode_multi_fixed(
                enc,
                row.as_ptr(),
                row.len(),
                out.as_mut_ptr(),
                out.len(),
                &mut out_len,
            );
            assert_eq!(r, AlecResult::Ok);
            let frame = &out[..out_len];

            let mut v_orig = [0f64; 5];
            let mut v_new = [0f64; 5];
            assert_eq!(
                alec_decode_multi_fixed(
                    dec_orig,
                    frame.as_ptr(),
                    frame.len(),
                    v_orig.as_mut_ptr(),
                    v_orig.len(),
                    ptr::null_mut(),
                    ptr::null_mut(),
                    ptr::null_mut(),
                ),
                AlecResult::Ok
            );
            assert_eq!(
                alec_decode_multi_fixed(
                    dec_new,
                    frame.as_ptr(),
                    frame.len(),
                    v_new.as_mut_ptr(),
                    v_new.len(),
                    ptr::null_mut(),
                    ptr::null_mut(),
                    ptr::null_mut(),
                ),
                AlecResult::Ok
            );
            // Bit-exact equality — both decoders ran the same
            // reconstruction logic on the same wire bytes with
            // identically-seeded contexts.
            for ch in 0..5 {
                assert_eq!(
                    v_orig[ch].to_bits(),
                    v_new[ch].to_bits(),
                    "ch {} diverged between original and restored decoder",
                    ch
                );
            }
        }

        alec_encoder_free(enc);
        alec_decoder_free(dec_orig);
        alec_decoder_free(dec_new);
    }

    /// D4-2. `export_state_size` matches the length reported by a
    /// real export call.
    #[test]
    fn test_export_state_size_matches_export() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();
        let rows: Vec<[f64; 5]> = (0..12)
            .map(|_| [3.60, 22.50, 45.0, 420.0, 1013.25])
            .collect();
        let _ = drive_pair(enc, dec, &rows);

        let mut size: usize = 0;
        let r =
            alec_decoder_export_state_size(dec, SENSOR_TYPE.as_ptr() as *const c_char, &mut size);
        assert_eq!(r, AlecResult::Ok);

        let mut buf = vec![0u8; size];
        let mut written: usize = 0;
        let r = alec_decoder_export_state(
            dec,
            SENSOR_TYPE.as_ptr() as *const c_char,
            buf.as_mut_ptr(),
            buf.len(),
            &mut written,
        );
        assert_eq!(r, AlecResult::Ok);
        assert_eq!(written, size);

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// D4-3. Too-small buffer → `ALEC_ERROR_BUFFER_TOO_SMALL`. The
    /// buffer is NOT written to (no partial write); `*out_len`
    /// reports the required size.
    #[test]
    fn test_export_buffer_too_small() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();
        let rows: Vec<[f64; 5]> = (0..8)
            .map(|_| [3.60, 22.50, 45.0, 420.0, 1013.25])
            .collect();
        let _ = drive_pair(enc, dec, &rows);

        // Tiny buffer pre-filled with a sentinel. After the failed
        // export every byte must still be the sentinel.
        let mut buf = [0xAAu8; 10];
        let mut written: usize = 0;
        let r = alec_decoder_export_state(
            dec,
            SENSOR_TYPE.as_ptr() as *const c_char,
            buf.as_mut_ptr(),
            buf.len(),
            &mut written,
        );
        assert_eq!(r, AlecResult::ErrorBufferTooSmall);
        assert!(
            written > buf.len(),
            "expected *out_len to report required size, got {}",
            written
        );
        for (i, &b) in buf.iter().enumerate() {
            assert_eq!(b, 0xAA, "buf[{}] was written despite error", i);
        }

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// D4-4. Corrupt input → `ALEC_ERROR_CORRUPT_DATA`. The
    /// decoder's context is NOT modified.
    #[test]
    fn test_import_corrupt_data() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();
        let rows: Vec<[f64; 5]> = (0..8)
            .map(|_| [3.60, 22.50, 45.0, 420.0, 1013.25])
            .collect();
        let _ = drive_pair(enc, dec, &rows);

        // Capture a snapshot we can compare against.
        let mut snap = vec![0u8; 4096];
        let mut snap_len: usize = 0;
        assert_eq!(
            alec_decoder_export_state(
                dec,
                SENSOR_TYPE.as_ptr() as *const c_char,
                snap.as_mut_ptr(),
                snap.len(),
                &mut snap_len,
            ),
            AlecResult::Ok
        );
        let snap_pre = snap[..snap_len].to_vec();

        // Random garbage → CORRUPT_DATA.
        let garbage = [0x00u8, 0x11, 0x22, 0x33, 0x44, 0x55];
        let r = alec_decoder_import_state(dec, garbage.as_ptr(), garbage.len());
        assert_eq!(r, AlecResult::ErrorCorruptData);

        // Bytes with the right magic but bad CRC → also CORRUPT_DATA.
        let mut tampered = snap_pre.clone();
        let mid = tampered.len() / 2;
        tampered[mid] ^= 0xFF;
        let r = alec_decoder_import_state(dec, tampered.as_ptr(), tampered.len());
        assert_eq!(r, AlecResult::ErrorCorruptData);

        // Snapshot the decoder again — must match pre-import bytes
        // exactly, confirming the failed imports left the context
        // untouched.
        let mut snap2 = vec![0u8; 4096];
        let mut snap2_len: usize = 0;
        assert_eq!(
            alec_decoder_export_state(
                dec,
                SENSOR_TYPE.as_ptr() as *const c_char,
                snap2.as_mut_ptr(),
                snap2.len(),
                &mut snap2_len,
            ),
            AlecResult::Ok
        );
        assert_eq!(snap2_len, snap_len);
        assert_eq!(&snap2[..snap2_len], &snap_pre[..]);

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// D4-5. Session state (last_header_sequence, last_gap_size) is
    /// preserved across an import.
    #[test]
    fn test_session_state_preserved_on_import() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();
        let rows: Vec<[f64; 5]> = (0..5)
            .map(|_| [3.60, 22.50, 45.0, 420.0, 1013.25])
            .collect();
        let _ = drive_pair(enc, dec, &rows);

        // Overwrite the session-state fields with a known tuple.
        unsafe {
            (*dec).last_header_sequence = Some(42);
            (*dec).last_gap_size = 2;
        }

        // Export and re-import — session state should survive.
        let mut buf = vec![0u8; 4096];
        let mut n: usize = 0;
        assert_eq!(
            alec_decoder_export_state(
                dec,
                SENSOR_TYPE.as_ptr() as *const c_char,
                buf.as_mut_ptr(),
                buf.len(),
                &mut n,
            ),
            AlecResult::Ok
        );
        assert_eq!(
            alec_decoder_import_state(dec, buf.as_ptr(), n),
            AlecResult::Ok
        );

        let dec_ref = unsafe { &*dec };
        assert_eq!(dec_ref.last_header_sequence, Some(42));
        assert_eq!(dec_ref.last_gap_size, 2);

        alec_encoder_free(enc);
        alec_decoder_free(dec);
    }

    /// D4-6. Exporting a context just after `reset_to_baseline()`
    /// produces a valid serialized buffer whose `source_stats`
    /// section is empty. Patterns registered before the reset are
    /// preserved (Bloc C contract — see `reset_to_baseline`).
    #[test]
    fn test_export_after_reset_to_baseline() {
        let enc = alec_encoder_new();
        let dec = alec_decoder_new();
        let rows: Vec<[f64; 5]> = (0..30)
            .map(|_| [3.60, 22.50, 45.0, 420.0, 1013.25])
            .collect();
        let _ = drive_pair(enc, dec, &rows);

        // Register one pattern directly on the context so we can
        // check it survives the reset.
        use alec::context::Pattern;
        let code = unsafe { &mut *dec }
            .context
            .register_pattern(Pattern::new(vec![0x11, 0x22, 0x33]))
            .unwrap();

        // Reset → export → import → verify.
        unsafe { &mut *dec }.context.reset_to_baseline();
        let mut buf = vec![0u8; 4096];
        let mut n: usize = 0;
        assert_eq!(
            alec_decoder_export_state(
                dec,
                SENSOR_TYPE.as_ptr() as *const c_char,
                buf.as_mut_ptr(),
                buf.len(),
                &mut n,
            ),
            AlecResult::Ok
        );

        let dec_fresh = alec_decoder_new();
        assert_eq!(
            alec_decoder_import_state(dec_fresh, buf.as_ptr(), n),
            AlecResult::Ok
        );

        // source_stats is empty (predict returns None for any sid).
        let d = unsafe { &*dec_fresh };
        assert!(d.context.predict(1).is_none());
        assert!(d.context.predict(5).is_none());
        // Pattern registered pre-reset must still be in the dictionary.
        assert!(d.context.get_pattern(code).is_some());

        alec_encoder_free(enc);
        alec_decoder_free(dec);
        alec_decoder_free(dec_fresh);
    }

    /// NULL-safety on the three new FFI entry points.
    #[test]
    fn test_persistence_ffi_null_safety() {
        use std::ptr;
        let dec = alec_decoder_new();
        let mut n: usize = 0;
        let mut buf = [0u8; 4];

        // export_state_size
        assert_eq!(
            alec_decoder_export_state_size(
                ptr::null(),
                SENSOR_TYPE.as_ptr() as *const c_char,
                &mut n
            ),
            AlecResult::ErrorNullPointer
        );
        assert_eq!(
            alec_decoder_export_state_size(dec, ptr::null(), &mut n),
            AlecResult::ErrorNullPointer
        );
        assert_eq!(
            alec_decoder_export_state_size(
                dec,
                SENSOR_TYPE.as_ptr() as *const c_char,
                ptr::null_mut()
            ),
            AlecResult::ErrorNullPointer
        );

        // export_state
        assert_eq!(
            alec_decoder_export_state(
                ptr::null(),
                SENSOR_TYPE.as_ptr() as *const c_char,
                buf.as_mut_ptr(),
                buf.len(),
                &mut n,
            ),
            AlecResult::ErrorNullPointer
        );

        // import_state
        assert_eq!(
            alec_decoder_import_state(ptr::null_mut(), buf.as_ptr(), buf.len()),
            AlecResult::ErrorNullPointer
        );
        assert_eq!(
            alec_decoder_import_state(dec, ptr::null(), buf.len()),
            AlecResult::ErrorNullPointer
        );

        alec_decoder_free(dec);
    }
}