rustpix-io 1.1.2

Memory-mapped file I/O for rustpix
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
//! ORNL SNS/HFIR `NXsnsevent` HDF5 export.
//!
//! Produces `NeXus` event files compatible with the ORNL SNS & HFIR data
//! pipeline (Mantid, etc.). Data is stored as 1D pixel-ID vectors with
//! bank-specific offsets, matching the `NXsnsevent` definition.

// Intentional truncation: u64→usize (safe on 64-bit), f64→f32 (SNS format uses f32 TOF),
// f64→u32 (pixel coords clamped to non-negative), u64→f64 (sub-ns precision loss is fine).
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_precision_loss
)]

use crate::hdf5::{
    append_slice, create_extendable_dataset, set_attr_str_group, set_dataset_units,
    to_var_len_unicode, NeutronEventBatch,
};
use crate::reader::EventBatch;
use crate::{Error, Result};
use hdf5::types::VarLenUnicode;
use hdf5::{Dataset, File, Group};
use std::collections::HashSet;
use std::path::Path;

const NS_PER_TICK: u64 = 25;
const US_PER_TICK: f64 = 25.0 / 1000.0;

/// Remap a coordinate from the source grid (which may contain chip-gap pixels)
/// to the target grid (which does not).
///
/// Gap positions are given as a sorted slice.  A coordinate that falls on a gap
/// returns `None`.  Coordinates beyond the gap are shifted down by the number
/// of gap positions below them.
fn remap_gap(coord: u32, gaps: &[u32]) -> Option<u32> {
    let shift = gaps.partition_point(|&g| g < coord);
    if gaps.get(shift).copied() == Some(coord) {
        return None; // coord is a gap pixel
    }
    Some(coord - shift as u32)
}

// ---------------------------------------------------------------------------
// Configuration types
// ---------------------------------------------------------------------------

/// Configuration for a single detector bank in SNS format.
#[derive(Clone, Debug)]
pub struct SnsBankConfig {
    /// Bank name (e.g., `"bank100"`). Used for HDF5 group naming.
    pub name: String,
    /// Pixel-ID offset for this bank (e.g., 1\_000\_000 for bank100).
    pub pixel_id_offset: u32,
    /// Number of columns (pixels per row).
    pub width: u32,
    /// Number of rows.
    pub height: u32,
    /// Column indices that are chip-gap pixels in the source coordinate space.
    /// Events at these columns are silently dropped; columns beyond the gap
    /// are shifted down by the gap width.  For VENUS this is `[256, 257]`.
    pub gap_columns: Vec<u32>,
    /// Row indices that are chip-gap pixels in the source coordinate space.
    /// Same semantics as `gap_columns`.  For VENUS this is `[256, 257]`.
    pub gap_rows: Vec<u32>,
}

/// Run-level metadata for an SNS `NXsnsevent` file.
#[derive(Clone, Debug)]
pub struct SnsRunMetadata {
    /// Run number (e.g., 15162).
    pub run_number: u32,
    /// IPTS experiment identifier (e.g., `"IPTS-35004"`).
    pub experiment_identifier: String,
    /// ISO 8601 start time of the run.
    pub start_time: String,
    /// ISO 8601 end time (filled at finalisation if `None`).
    pub end_time: Option<String>,
    /// Run duration in seconds.
    pub duration: Option<f64>,
    /// Total integrated proton charge in picoCoulombs.
    pub proton_charge: Option<f64>,
    /// Run title / description.
    pub title: Option<String>,
}

/// Instrument metadata for the `NXinstrument` group.
#[derive(Clone, Debug)]
pub struct SnsInstrumentConfig {
    /// Instrument short name (e.g., `"VENUS"`).
    pub name: String,
    /// Beamline identifier (e.g., `"BL10"`).
    pub beamline: String,
    /// Optional Instrument Definition File XML string.
    pub instrument_xml: Option<String>,
}

/// Top-level options for an SNS `NXsnsevent` export.
#[derive(Clone, Debug)]
pub struct SnsWriteOptions {
    /// Detector bank configurations (one per bank).
    pub banks: Vec<SnsBankConfig>,
    /// Run metadata.
    pub run: SnsRunMetadata,
    /// Instrument configuration.
    pub instrument: SnsInstrumentConfig,
    /// Super-resolution factor for neutron coordinates (default 1.0).
    ///
    /// When writing neutron events whose x/y are in super-resolution space,
    /// set this to the factor used during extraction (e.g., 8.0) so that
    /// pixel IDs are computed correctly.
    pub super_resolution_factor: f64,
    /// Chunk size along the event dimension.
    pub chunk_events: usize,
    /// Optional gzip compression level (0–9). `None` disables compression.
    pub compression: Option<u8>,
    /// Enable byte-shuffle filter before compression.
    pub shuffle: bool,
}

impl SnsWriteOptions {
    /// Create options with VENUS defaults.
    ///
    /// Bank100 with pixel-ID offset 1\_000\_000 and a 512×512 grid,
    /// instrument name "VENUS", beamline "BL10".
    #[must_use]
    pub fn venus_defaults(run: SnsRunMetadata) -> Self {
        Self {
            banks: vec![SnsBankConfig {
                name: "bank100".to_string(),
                pixel_id_offset: 1_000_000,
                width: 512,
                height: 512,
                gap_columns: vec![256, 257],
                gap_rows: vec![256, 257],
            }],
            run,
            instrument: SnsInstrumentConfig {
                name: "VENUS".to_string(),
                beamline: "BL10".to_string(),
                instrument_xml: None,
            },
            super_resolution_factor: 1.0,
            chunk_events: 100_000,
            compression: Some(1),
            shuffle: true,
        }
    }
}

/// A single `DASlogs` entry (process variable time series).
#[derive(Clone, Debug)]
pub struct DasLogEntry {
    /// Process variable name (e.g., `"BL10:Mot:S1:X"`).
    pub name: String,
    /// Timestamps in seconds from run start.
    pub time: Vec<f64>,
    /// Values at each timestamp.
    pub value: Vec<f64>,
    /// Units string (e.g., `"mm"`, `"K"`, `"deg"`).
    pub units: Option<String>,
}

// ---------------------------------------------------------------------------
// Internal bank writer
// ---------------------------------------------------------------------------

struct SnsBankEventWriter {
    event_id: Dataset,
    event_time_offset: Dataset,
    event_time_zero: Dataset,
    event_index: Dataset,
    total_counts_ds: Dataset,
    event_count: u64,
    pulse_count: u64,
    /// Buffered absolute pulse timestamps (in nanoseconds).  Written to
    /// `event_time_zero` as relative seconds during [`SnsEventSink::finalize`],
    /// once the global minimum timestamp across all banks is known.
    pulse_timestamps_ns: Vec<u64>,
}

impl SnsBankEventWriter {
    fn new(group: &Group, options: &SnsWriteOptions) -> Result<Self> {
        let event_id = create_extendable_dataset::<u32>(
            group,
            "event_id",
            options.chunk_events,
            options.compression,
            options.shuffle,
        )?;

        let event_time_offset = create_extendable_dataset::<f32>(
            group,
            "event_time_offset",
            options.chunk_events,
            options.compression,
            options.shuffle,
        )?;
        set_dataset_units(&event_time_offset, "microsecond")?;

        let event_time_zero = create_extendable_dataset::<f64>(
            group,
            "event_time_zero",
            options.chunk_events,
            options.compression,
            options.shuffle,
        )?;
        set_dataset_units(&event_time_zero, "second")?;

        let event_index = create_extendable_dataset::<u64>(
            group,
            "event_index",
            options.chunk_events,
            options.compression,
            options.shuffle,
        )?;

        let total_counts_ds = group
            .new_dataset::<u64>()
            .shape((1,))
            .create("total_counts")?;
        total_counts_ds.write_raw(&[0u64])?;

        Ok(Self {
            event_id,
            event_time_offset,
            event_time_zero,
            event_index,
            total_counts_ds,
            event_count: 0,
            pulse_count: 0,
            pulse_timestamps_ns: Vec::new(),
        })
    }

    /// Append hit events, returning the number of events actually written
    /// (may be fewer than the batch size when gap pixels are dropped).
    ///
    /// `pulse_ns` is the absolute pulse timestamp in nanoseconds.  It is
    /// buffered and converted to relative seconds in
    /// [`Self::write_pulse_times`].
    fn append_hits(
        &mut self,
        bank: &SnsBankConfig,
        batch: &EventBatch,
        pulse_ns: u64,
    ) -> Result<usize> {
        let n = batch.hits.x.len();
        if n == 0 {
            return Ok(0);
        }

        // 1. Filter events first — remap through chip-gap positions, drop
        //    gap pixels and out-of-bounds coordinates.
        let mut pixel_ids = Vec::with_capacity(n);
        let mut tof_us = Vec::with_capacity(n);
        for i in 0..n {
            let raw_x = u32::from(batch.hits.x[i]);
            let raw_y = u32::from(batch.hits.y[i]);
            let Some(px) = remap_gap(raw_x, &bank.gap_columns) else {
                continue; // gap pixel — skip
            };
            let Some(py) = remap_gap(raw_y, &bank.gap_rows) else {
                continue;
            };
            if px >= bank.width || py >= bank.height {
                continue; // out-of-bounds — skip
            }
            pixel_ids.push(bank.pixel_id_offset + py * bank.width + px);
            tof_us.push((f64::from(batch.hits.tof[i]) * US_PER_TICK) as f32);
        }

        if pixel_ids.is_empty() {
            return Ok(0); // no surviving events — no pulse entry
        }

        // 2. Write event_index and buffer pulse timestamp (event_time_zero
        //    is written in finalize once the global minimum is known).
        append_slice(
            &self.event_index,
            self.pulse_count as usize,
            &[self.event_count],
        )?;
        self.pulse_timestamps_ns.push(pulse_ns);
        self.pulse_count += 1;

        // 3. Write events
        append_slice(&self.event_id, self.event_count as usize, &pixel_ids)?;
        append_slice(&self.event_time_offset, self.event_count as usize, &tof_us)?;

        let written = pixel_ids.len();
        self.event_count += written as u64;
        Ok(written)
    }

    /// Append neutron events, returning the number of events actually written
    /// (may be fewer than the batch size when gap pixels are dropped).
    ///
    /// `pulse_ns` is the absolute pulse timestamp in nanoseconds.  It is
    /// buffered and converted to relative seconds in
    /// [`Self::write_pulse_times`].
    fn append_neutrons(
        &mut self,
        bank: &SnsBankConfig,
        batch: &NeutronEventBatch,
        pulse_ns: u64,
        super_resolution_factor: f64,
    ) -> Result<usize> {
        let n = batch.neutrons.x.len();
        if n == 0 {
            return Ok(0);
        }

        // 1. Filter events first — convert super-resolution coords to pixel
        //    coords, remap through chip-gap positions, and drop gap/OOB events.
        let inv = 1.0 / super_resolution_factor;
        let mut pixel_ids = Vec::with_capacity(n);
        let mut tof_us = Vec::with_capacity(n);
        for i in 0..n {
            let fx = (batch.neutrons.x[i] * inv).round();
            let fy = (batch.neutrons.y[i] * inv).round();
            if !fx.is_finite() || !fy.is_finite() || fx < 0.0 || fy < 0.0 {
                continue;
            }
            let raw_x = fx as u32;
            let raw_y = fy as u32;
            let Some(px) = remap_gap(raw_x, &bank.gap_columns) else {
                continue;
            };
            let Some(py) = remap_gap(raw_y, &bank.gap_rows) else {
                continue;
            };
            if px >= bank.width || py >= bank.height {
                continue; // out-of-bounds — skip
            }
            pixel_ids.push(bank.pixel_id_offset + py * bank.width + px);
            tof_us.push((f64::from(batch.neutrons.tof[i]) * US_PER_TICK) as f32);
        }

        if pixel_ids.is_empty() {
            return Ok(0); // no surviving events — no pulse entry
        }

        // 2. Write event_index and buffer pulse timestamp (event_time_zero
        //    is written in finalize once the global minimum is known).
        append_slice(
            &self.event_index,
            self.pulse_count as usize,
            &[self.event_count],
        )?;
        self.pulse_timestamps_ns.push(pulse_ns);
        self.pulse_count += 1;

        // 3. Write events
        append_slice(&self.event_id, self.event_count as usize, &pixel_ids)?;
        append_slice(&self.event_time_offset, self.event_count as usize, &tof_us)?;

        let written = pixel_ids.len();
        self.event_count += written as u64;
        Ok(written)
    }

    /// Flush buffered pulse timestamps to `event_time_zero` as seconds
    /// relative to `min_start_ns` (the global minimum across all banks).
    fn write_pulse_times(&self, min_start_ns: u64) -> Result<()> {
        let times_s: Vec<f64> = self
            .pulse_timestamps_ns
            .iter()
            .map(|&ns| (ns - min_start_ns) as f64 / 1_000_000_000.0)
            .collect();
        // Write all pulse times at once (dataset was created empty/extendable).
        if !times_s.is_empty() {
            append_slice(&self.event_time_zero, 0, &times_s)?;
        }
        Ok(())
    }

    fn write_total_counts(&self) -> Result<()> {
        self.total_counts_ds.write_raw(&[self.event_count])?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Public streaming writer
// ---------------------------------------------------------------------------

/// Streaming writer for ORNL SNS `NXsnsevent` HDF5 files.
///
/// Writes event data in bank-based format with pulse-indexed structure.
/// Call [`Self::write_hits`] or [`Self::write_neutrons`] per pulse, then [`Self::finalize`].
pub struct SnsEventSink {
    _file: File,
    entry: Group,
    writers: Vec<(SnsBankConfig, SnsBankEventWriter)>,
    options: SnsWriteOptions,
    /// Global minimum pulse timestamp across all banks.  Computed from the
    /// minimum first-pulse across every bank and used as the time origin for
    /// `event_time_zero` (written during [`Self::finalize`]).
    min_pulse_ns: Option<u64>,
    /// Per-bank last pulse timestamp for monotonicity enforcement.
    /// Each bank's event stream must be independently monotonic, but banks
    /// may be written in any order (e.g., all pulses for bank 0, then bank 1).
    last_pulse_ns_per_bank: Vec<u64>,
    /// Global maximum pulse timestamp across all banks, used for computing
    /// run duration in [`Self::finalize`].
    max_pulse_ns: u64,
    /// Set of pulse timestamps already counted toward `total_pulses`, used to
    /// de-duplicate counts when the same physical pulse is written to multiple
    /// banks regardless of write ordering.
    counted_pulse_ns: HashSet<u64>,
    total_counts: u64,
    total_pulses: u64,
    finalized: bool,
}

impl SnsEventSink {
    /// Create a new SNS event sink.
    ///
    /// Builds the full HDF5 skeleton (`NXentry`, banks, instrument, `DASlogs`).
    ///
    /// # Errors
    /// Returns an error if the file or HDF5 structures cannot be created.
    pub fn create<P: AsRef<Path>>(path: P, options: SnsWriteOptions) -> Result<Self> {
        let srf = options.super_resolution_factor;
        if !srf.is_finite() || srf <= 0.0 {
            return Err(crate::Error::InvalidFormat(format!(
                "super_resolution_factor must be finite and positive, got {srf}"
            )));
        }

        let file = File::create(path)?;

        // Root-level entry
        let entry = file.create_group("entry")?;
        set_attr_str_group(&entry, "NX_class", "NXentry")?;
        set_attr_str_group(&entry, "definition", "NXsnsevent")?;

        // Run metadata as datasets (matching SNS convention: scalar datasets, not attributes)
        write_str_dataset(&entry, "run_number", &options.run.run_number.to_string())?;
        write_str_dataset(
            &entry,
            "experiment_identifier",
            &options.run.experiment_identifier,
        )?;
        write_str_dataset(&entry, "start_time", &options.run.start_time)?;
        write_str_dataset(
            &entry,
            "end_time",
            options.run.end_time.as_deref().unwrap_or(""),
        )?;
        if let Some(title) = &options.run.title {
            write_str_dataset(&entry, "title", title)?;
        }

        // Scalar numeric metadata
        write_f64_dataset(
            &entry,
            "duration",
            options.run.duration.unwrap_or(0.0),
            "second",
        )?;
        write_f64_dataset(
            &entry,
            "proton_charge",
            options.run.proton_charge.unwrap_or(0.0),
            "picoCoulomb",
        )?;
        write_u64_dataset(&entry, "total_counts", 0)?;
        write_u64_dataset(&entry, "total_pulses", 0)?;

        // Bank event groups
        let mut writers = Vec::with_capacity(options.banks.len());
        for bank in &options.banks {
            let group_name = format!("{}_events", bank.name);
            let group = entry.create_group(&group_name)?;
            set_attr_str_group(&group, "NX_class", "NXevent_data")?;

            let writer = SnsBankEventWriter::new(&group, &options)?;
            writers.push((bank.clone(), writer));
        }

        // Instrument group with hard links to banks
        let instrument = entry.create_group("instrument")?;
        set_attr_str_group(&instrument, "NX_class", "NXinstrument")?;
        write_str_dataset(&instrument, "name", &options.instrument.name)?;
        write_str_dataset(&instrument, "beamline", &options.instrument.beamline)?;

        for bank in &options.banks {
            let src = format!("{}_events", bank.name);
            let dst = format!("instrument/{}", bank.name);
            entry.link_hard(&src, &dst)?;
        }

        // Instrument definition XML
        if let Some(ref xml) = options.instrument.instrument_xml {
            let xml_group = instrument.create_group("instrument_xml")?;
            set_attr_str_group(&xml_group, "NX_class", "NXnote")?;
            write_str_dataset(&xml_group, "data", xml)?;
            write_str_dataset(&xml_group, "type", "text/xml")?;
        }

        // DASlogs placeholder
        let daslogs = entry.create_group("DASlogs")?;
        set_attr_str_group(&daslogs, "NX_class", "NXcollection")?;

        // Sample placeholder
        let sample = entry.create_group("sample")?;
        set_attr_str_group(&sample, "NX_class", "NXsample")?;
        write_str_dataset(&sample, "name", "")?;

        let num_banks = writers.len();
        Ok(Self {
            _file: file,
            entry,
            writers,
            options,
            min_pulse_ns: None,
            last_pulse_ns_per_bank: vec![0u64; num_banks],
            max_pulse_ns: 0,
            counted_pulse_ns: HashSet::new(),
            total_counts: 0,
            total_pulses: 0,
            finalized: false,
        })
    }

    /// Write a hit-event batch to the specified bank.
    ///
    /// `bank_index` selects which bank in [`SnsWriteOptions::banks`] to write to.
    ///
    /// # Errors
    /// Returns an error if the bank index is out of bounds or HDF5 write fails.
    pub fn write_hits(&mut self, bank_index: usize, batch: &EventBatch) -> Result<()> {
        if self.finalized {
            return Err(Error::InvalidFormat(
                "cannot write after finalization".into(),
            ));
        }
        if bank_index >= self.writers.len() {
            return Err(Error::InvalidFormat(format!(
                "bank index {bank_index} out of range (have {} banks)",
                self.writers.len()
            )));
        }

        let pulse_ns = batch.tdc_timestamp_25ns * NS_PER_TICK;
        self.validate_pulse_monotonicity(pulse_ns, bank_index)?;

        let (ref bank, ref mut writer) = self.writers[bank_index];
        let written = writer.append_hits(bank, batch, pulse_ns)?;

        if written > 0 {
            self.track_written_pulse(pulse_ns);
            self.total_counts += written as u64;
            if self.counted_pulse_ns.insert(pulse_ns) {
                self.total_pulses += 1;
            }
        }
        Ok(())
    }

    /// Write a neutron-event batch to the specified bank.
    ///
    /// `bank_index` selects which bank in [`SnsWriteOptions::banks`] to write to.
    ///
    /// # Errors
    /// Returns an error if the bank index is out of bounds or HDF5 write fails.
    pub fn write_neutrons(&mut self, bank_index: usize, batch: &NeutronEventBatch) -> Result<()> {
        if self.finalized {
            return Err(Error::InvalidFormat(
                "cannot write after finalization".into(),
            ));
        }
        if bank_index >= self.writers.len() {
            return Err(Error::InvalidFormat(format!(
                "bank index {bank_index} out of range (have {} banks)",
                self.writers.len()
            )));
        }

        let pulse_ns = batch.tdc_timestamp_25ns * NS_PER_TICK;
        self.validate_pulse_monotonicity(pulse_ns, bank_index)?;

        let (ref bank, ref mut writer) = self.writers[bank_index];
        let written =
            writer.append_neutrons(bank, batch, pulse_ns, self.options.super_resolution_factor)?;

        if written > 0 {
            self.track_written_pulse(pulse_ns);
            self.total_counts += written as u64;
            if self.counted_pulse_ns.insert(pulse_ns) {
                self.total_pulses += 1;
            }
        }
        Ok(())
    }

    /// Write `DASlogs` process-variable entries.
    ///
    /// Can be called multiple times to add different variables.
    ///
    /// # Errors
    /// Returns an error if the HDF5 write fails.
    pub fn write_daslogs(&self, logs: &[DasLogEntry]) -> Result<()> {
        if self.finalized {
            return Err(Error::InvalidFormat(
                "cannot write after finalization".into(),
            ));
        }
        let daslogs = self.entry.group("DASlogs")?;
        for log in logs {
            if log.time.len() != log.value.len() {
                return Err(Error::InvalidFormat(format!(
                    "DASlog '{}': time length ({}) != value length ({})",
                    log.name,
                    log.time.len(),
                    log.value.len(),
                )));
            }
            let group = daslogs.create_group(&log.name)?;
            set_attr_str_group(&group, "NX_class", "NXlog")?;

            let time_ds = group
                .new_dataset::<f64>()
                .shape((log.time.len(),))
                .create("time")?;
            time_ds.write_raw(&log.time)?;
            set_dataset_units(&time_ds, "second")?;

            let value_ds = group
                .new_dataset::<f64>()
                .shape((log.value.len(),))
                .create("value")?;
            value_ds.write_raw(&log.value)?;
            if let Some(ref units) = log.units {
                set_dataset_units(&value_ds, units)?;
            }
        }
        Ok(())
    }

    /// Finalise the file: update total counts/pulses, per-bank totals, and
    /// end time / duration.
    ///
    /// Called automatically on [`Drop`], but an explicit call allows error handling.
    ///
    /// # Errors
    /// Returns an error if the HDF5 write fails.
    #[allow(clippy::cast_precision_loss)]
    pub fn finalize(&mut self) -> Result<()> {
        if self.finalized {
            return Ok(());
        }
        self.finalized = true;

        // Compute the global minimum pulse timestamp across all banks.
        // This is the time origin for event_time_zero.
        let min_start_ns = self.min_pulse_ns.unwrap_or(0);

        // Per-bank: write buffered pulse times and total counts
        for (_bank, writer) in &self.writers {
            writer.write_pulse_times(min_start_ns)?;
            writer.write_total_counts()?;
        }

        // Entry-level totals
        overwrite_u64_dataset(&self.entry, "total_counts", self.total_counts)?;
        overwrite_u64_dataset(&self.entry, "total_pulses", self.total_pulses)?;

        // Compute and write end_time and duration from pulse timestamps.
        // `min_pulse_ns` and `max_pulse_ns` are *relative* detector tick counts,
        // not Unix-epoch nanoseconds — the delta gives the measurement duration.
        if self.min_pulse_ns.is_some() {
            let duration_s =
                (self.max_pulse_ns.saturating_sub(min_start_ns)) as f64 / 1_000_000_000.0;
            overwrite_f64_dataset(&self.entry, "duration", duration_s)?;

            // Derive end_time by adding duration to the human-supplied start_time.
            // Truncate to whole seconds — the exact duration is already stored
            // as an f64 in the `duration` dataset.
            if let Some(start_epoch) = iso8601_to_epoch_secs(&self.options.run.start_time) {
                let end_epoch = start_epoch + duration_s as u64;
                let end_time = epoch_secs_to_iso8601(end_epoch);
                overwrite_str_dataset(&self.entry, "end_time", &end_time)?;
            }
        }

        Ok(())
    }

    /// Validate per-bank monotonicity.
    ///
    /// Monotonicity is enforced **per bank**: each bank's pulse stream must be
    /// independently non-decreasing, but different banks may be written in any
    /// order (e.g., all pulses for bank 0, then all pulses for bank 1).
    ///
    /// This is called for every pulse *before* event filtering.  The global
    /// min/max tracking is deferred to [`Self::track_written_pulse`] so that
    /// empty pulses (all events filtered) do not affect `event_time_zero` or
    /// duration metadata.
    ///
    /// # Errors
    /// Returns an error if the pulse timestamp is earlier than the previous
    /// pulse *for the same bank* (non-monotonic).
    fn validate_pulse_monotonicity(&mut self, pulse_ns: u64, bank_index: usize) -> Result<()> {
        let bank_last = self.last_pulse_ns_per_bank[bank_index];
        if pulse_ns < bank_last {
            return Err(Error::InvalidFormat(format!(
                "non-monotonic pulse timestamp for bank {bank_index}: \
                 {pulse_ns} ns < previous {bank_last} ns",
            )));
        }
        self.last_pulse_ns_per_bank[bank_index] = pulse_ns;
        Ok(())
    }

    /// Update global min/max pulse timestamps for a pulse that produced at
    /// least one written event.  Called only when `written > 0`.
    fn track_written_pulse(&mut self, pulse_ns: u64) {
        self.min_pulse_ns = Some(self.min_pulse_ns.map_or(pulse_ns, |m| m.min(pulse_ns)));
        self.max_pulse_ns = self.max_pulse_ns.max(pulse_ns);
    }
}

impl Drop for SnsEventSink {
    fn drop(&mut self) {
        let _ = self.finalize();
    }
}

// ---------------------------------------------------------------------------
// One-shot convenience functions
// ---------------------------------------------------------------------------

/// Write hit events in SNS `NXsnsevent` format (one-shot).
///
/// All batches are written to bank index 0.
///
/// # Errors
/// Returns an error if the file cannot be created or data cannot be written.
pub fn write_hits_sns<P, I>(path: P, batches: I, options: &SnsWriteOptions) -> Result<()>
where
    P: AsRef<Path>,
    I: IntoIterator<Item = EventBatch>,
{
    let mut sink = SnsEventSink::create(path, options.clone())?;
    for batch in batches {
        sink.write_hits(0, &batch)?;
    }
    sink.finalize()?;
    Ok(())
}

/// Write neutron events in SNS `NXsnsevent` format (one-shot).
///
/// All batches are written to bank index 0.
///
/// # Errors
/// Returns an error if the file cannot be created or data cannot be written.
pub fn write_neutrons_sns<P, I>(path: P, batches: I, options: &SnsWriteOptions) -> Result<()>
where
    P: AsRef<Path>,
    I: IntoIterator<Item = NeutronEventBatch>,
{
    let mut sink = SnsEventSink::create(path, options.clone())?;
    for batch in batches {
        sink.write_neutrons(0, &batch)?;
    }
    sink.finalize()?;
    Ok(())
}

// ---------------------------------------------------------------------------
// HDF5 dataset helpers
// ---------------------------------------------------------------------------

fn write_str_dataset(group: &Group, name: &str, value: &str) -> Result<()> {
    let vlu = to_var_len_unicode(value)?;
    group
        .new_dataset::<VarLenUnicode>()
        .shape(())
        .create(name)?
        .write_scalar(&vlu)?;
    Ok(())
}

fn write_f64_dataset(group: &Group, name: &str, value: f64, units: &str) -> Result<()> {
    let ds = group.new_dataset::<f64>().shape(()).create(name)?;
    ds.write_scalar(&value)?;
    set_dataset_units(&ds, units)?;
    Ok(())
}

fn write_u64_dataset(group: &Group, name: &str, value: u64) -> Result<()> {
    let ds = group.new_dataset::<u64>().shape(()).create(name)?;
    ds.write_scalar(&value)?;
    Ok(())
}

fn overwrite_u64_dataset(group: &Group, name: &str, value: u64) -> Result<()> {
    let ds = group.dataset(name)?;
    ds.write_scalar(&value)?;
    Ok(())
}

fn overwrite_f64_dataset(group: &Group, name: &str, value: f64) -> Result<()> {
    let ds = group.dataset(name)?;
    ds.write_scalar(&value)?;
    Ok(())
}

fn overwrite_str_dataset(group: &Group, name: &str, value: &str) -> Result<()> {
    // HDF5 fixed-length string datasets cannot be resized; delete and recreate.
    if group.dataset(name).is_ok() {
        group.unlink(name)?;
    }
    write_str_dataset(group, name, value)?;
    Ok(())
}

/// Convert Unix epoch seconds to an ISO 8601 UTC string.
fn epoch_secs_to_iso8601(secs: u64) -> String {
    let days = secs / 86400;
    let rem = secs % 86400;
    let hours = rem / 3600;
    let minutes = (rem % 3600) / 60;
    let seconds = rem % 60;
    let mut y = 1970i64;
    let mut d = i64::try_from(days).unwrap_or(0);
    loop {
        let year_days = if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
            366
        } else {
            365
        };
        if d < year_days {
            break;
        }
        d -= year_days;
        y += 1;
    }
    let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
    let month_days: [i64; 12] = [
        31,
        if leap { 29 } else { 28 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    let mut m = 0usize;
    for (i, &md) in month_days.iter().enumerate() {
        if d < md {
            m = i;
            break;
        }
        d -= md;
    }
    format!(
        "{y:04}-{:02}-{:02}T{hours:02}:{minutes:02}:{seconds:02}Z",
        m + 1,
        d + 1,
    )
}

/// Parse a subset of ISO 8601 strings into Unix epoch seconds (UTC).
///
/// Accepted formats: `YYYY-MM-DDThh:mm:ssZ`, `YYYY-MM-DDThh:mm:ss±hh:mm`.
/// Returns `None` for unparseable input.
fn iso8601_to_epoch_secs(s: &str) -> Option<u64> {
    // Minimum length: "2025-01-01T00:00:00" = 19 chars (no timezone suffix)
    if s.len() < 19 {
        return None;
    }
    let year: i64 = s.get(0..4)?.parse().ok()?;
    let month: u32 = s.get(5..7)?.parse().ok()?;
    let day: u32 = s.get(8..10)?.parse().ok()?;
    let hour: i64 = s.get(11..13)?.parse().ok()?;
    let min: i64 = s.get(14..16)?.parse().ok()?;
    let sec: i64 = s.get(17..19)?.parse().ok()?;

    // Timezone offset (after position 19): 'Z', ±hh:mm, or absent.
    // Reject any other suffix (e.g. fractional seconds like ".123Z",
    // lowercase "z") to avoid silently miscomputing the epoch.
    let tz_offset_s: i64 = {
        let tz = s.get(19..).unwrap_or("");
        if tz == "Z" || tz.is_empty() {
            0
        } else if tz.starts_with('+') || tz.starts_with('-') {
            let sign: i64 = if tz.starts_with('+') { 1 } else { -1 };
            let tz = &tz[1..];
            let oh: i64 = tz.get(0..2).and_then(|v| v.parse().ok())?;
            let om: i64 = tz.get(3..5).and_then(|v| v.parse().ok()).unwrap_or(0);
            sign * (oh * 3600 + om * 60)
        } else {
            return None; // unsupported suffix
        }
    };

    // Days from epoch to start of `year`
    let mut days: i64 = 0;
    for y in 1970..year {
        days += if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
            366
        } else {
            365
        };
    }
    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    let month_days: [u32; 12] = [
        31,
        if leap { 29 } else { 28 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    if month == 0 || month > 12 || day == 0 {
        return None;
    }
    for &md in &month_days[..(month as usize - 1)] {
        days += i64::from(md);
    }
    days += i64::from(day.saturating_sub(1));

    let utc_secs = days * 86400 + hour * 3600 + min * 60 + sec - tz_offset_s;
    u64::try_from(utc_secs).ok()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use rustpix_core::neutron::NeutronBatch;
    use rustpix_core::soa::HitBatch;
    use tempfile::NamedTempFile;

    fn make_test_run() -> SnsRunMetadata {
        SnsRunMetadata {
            run_number: 99999,
            experiment_identifier: "IPTS-00001".to_string(),
            start_time: "2025-01-01T00:00:00-05:00".to_string(),
            end_time: None,
            duration: None,
            proton_charge: Some(100.0),
            title: Some("test run".to_string()),
        }
    }

    fn make_test_options() -> SnsWriteOptions {
        SnsWriteOptions::venus_defaults(make_test_run())
    }

    fn make_hit_batch(tdc: u64, xs: &[u16], ys: &[u16], tofs: &[u32]) -> EventBatch {
        let n = xs.len();
        let mut hits = HitBatch::with_capacity(n);
        hits.x.extend_from_slice(xs);
        hits.y.extend_from_slice(ys);
        hits.tof.extend_from_slice(tofs);
        hits.tot.extend_from_slice(&vec![10u16; n]);
        hits.timestamp.extend_from_slice(&vec![0u32; n]);
        hits.chip_id.extend_from_slice(&vec![0u8; n]);
        hits.cluster_id.extend_from_slice(&vec![-1i32; n]);
        EventBatch {
            tdc_timestamp_25ns: tdc,
            hits,
        }
    }

    fn make_neutron_batch(tdc: u64, xs: &[f64], ys: &[f64], tofs: &[u32]) -> NeutronEventBatch {
        let n = xs.len();
        NeutronEventBatch {
            tdc_timestamp_25ns: tdc,
            neutrons: NeutronBatch {
                x: xs.to_vec(),
                y: ys.to_vec(),
                tof: tofs.to_vec(),
                tot: vec![10u16; n],
                n_hits: vec![3u16; n],
                chip_id: vec![0u8; n],
            },
        }
    }

    // --- Pixel ID tests ---

    #[test]
    fn test_pixel_id_origin() {
        // (0, 0) -> offset + 0
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[0], &[0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000u32]);
    }

    #[test]
    fn test_pixel_id_corner() {
        // 514-space (511, 511) is beyond the gap at [256, 257], so it remaps
        // to 512-space (509, 509): 511 − 2 gap positions = 509.
        // event_id = 1_000_000 + 509*512 + 509 = 1_261_117
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[511], &[511], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000 + 509 * 512 + 509]);
    }

    // --- Time conversion tests ---

    #[test]
    fn test_tof_conversion() {
        // 400 ticks * 25ns = 10_000 ns = 10.0 µs
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[0], &[0], &[400]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let tof: Vec<f32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_offset")
            .unwrap()
            .read_raw()
            .unwrap();
        assert!((tof[0] - 10.0f32).abs() < 1e-5);
    }

    #[test]
    fn test_pulse_time_relative() {
        // First pulse at tdc=40_000_000 (1 second in 25ns ticks)
        // Second pulse at tdc=40_000_000 + 666_667 (~16.67ms later)
        let opts = make_test_options();
        let batch1 = make_hit_batch(40_000_000, &[0], &[0], &[100]);
        let batch2 = make_hit_batch(40_666_667, &[1], &[1], &[200]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch1).unwrap();
        sink.write_hits(0, &batch2).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let etz: Vec<f64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(etz.len(), 2);
        assert!((etz[0] - 0.0).abs() < 1e-12); // First pulse is t=0
        let expected = 666_667.0 * 25.0 / 1_000_000_000.0; // ~16.67ms
        assert!((etz[1] - expected).abs() < 1e-9);
    }

    // --- event_index tracking ---

    #[test]
    fn test_event_index_tracking() {
        let opts = make_test_options();
        let batch1 = make_hit_batch(1000, &[0, 1, 2], &[0, 0, 0], &[100, 200, 300]);
        let batch2 = make_hit_batch(2000, &[10, 11], &[10, 10], &[400, 500]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch1).unwrap();
        sink.write_hits(0, &batch2).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let idx: Vec<u64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_index")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(idx, vec![0u64, 3u64]); // First pulse starts at 0, second at 3
    }

    // --- HDF5 structure validation ---

    #[test]
    fn test_hdf5_structure() {
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[5], &[10], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();

        // Entry attributes
        let entry = f.group("entry").unwrap();
        let nx_class: VarLenUnicode = entry.attr("NX_class").unwrap().read_scalar().unwrap();
        assert_eq!(nx_class.as_str(), "NXentry");
        let definition: VarLenUnicode = entry.attr("definition").unwrap().read_scalar().unwrap();
        assert_eq!(definition.as_str(), "NXsnsevent");

        // Bank event group exists
        let bank = f.group("entry/bank100_events").unwrap();
        let nx_class: VarLenUnicode = bank.attr("NX_class").unwrap().read_scalar().unwrap();
        assert_eq!(nx_class.as_str(), "NXevent_data");

        // Instrument group exists
        let inst = f.group("entry/instrument").unwrap();
        let nx_class: VarLenUnicode = inst.attr("NX_class").unwrap().read_scalar().unwrap();
        assert_eq!(nx_class.as_str(), "NXinstrument");

        // Hard link: instrument/bank100 should exist and contain same data
        let link = f.group("entry/instrument/bank100").unwrap();
        let link_ids: Vec<u32> = link.dataset("event_id").unwrap().read_raw().unwrap();
        let direct_ids: Vec<u32> = bank.dataset("event_id").unwrap().read_raw().unwrap();
        assert_eq!(link_ids, direct_ids);

        // DASlogs placeholder
        let daslogs = f.group("entry/DASlogs").unwrap();
        let nx_class: VarLenUnicode = daslogs.attr("NX_class").unwrap().read_scalar().unwrap();
        assert_eq!(nx_class.as_str(), "NXcollection");

        // Run metadata
        let run_num: VarLenUnicode = entry.dataset("run_number").unwrap().read_scalar().unwrap();
        assert_eq!(run_num.as_str(), "99999");
    }

    // --- Finalization ---

    #[test]
    fn test_finalization_totals() {
        let opts = make_test_options();
        let batch1 = make_hit_batch(1000, &[0, 1], &[0, 0], &[100, 200]);
        let batch2 = make_hit_batch(2000, &[2, 3, 4], &[0, 0, 0], &[300, 400, 500]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch1).unwrap();
        sink.write_hits(0, &batch2).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        // Entry-level totals
        let tc: u64 = entry
            .dataset("total_counts")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tc, 5);
        let tp: u64 = entry
            .dataset("total_pulses")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tp, 2);

        // Per-bank total
        let bank_tc: Vec<u64> = entry
            .group("bank100_events")
            .unwrap()
            .dataset("total_counts")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(bank_tc, vec![5u64]);
    }

    #[test]
    fn test_pulse_count_deduplication_across_banks() {
        // Two banks, same pulse written to both — total_pulses should be 1, not 2.
        let mut opts = make_test_options();
        opts.banks.push(SnsBankConfig {
            name: "bank200".to_string(),
            pixel_id_offset: 2_000_000,
            width: 512,
            height: 512,
            gap_columns: vec![256, 257],
            gap_rows: vec![256, 257],
        });
        let batch = make_hit_batch(1000, &[0], &[0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.write_hits(1, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        let tc: u64 = entry
            .dataset("total_counts")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tc, 2); // 1 event per bank = 2 total events

        let tp: u64 = entry
            .dataset("total_pulses")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tp, 1); // Same pulse, counted once
    }

    // --- Empty batch ---

    #[test]
    fn test_empty_batch() {
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[], &[], &[]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert!(ids.is_empty());
    }

    // --- Neutron roundtrip ---

    #[test]
    fn test_neutron_pixel_ids() {
        let mut opts = make_test_options();
        opts.super_resolution_factor = 8.0;

        // Neutron at super-res (80.0, 160.0) -> pixel (10, 20)
        // pixel_id = 1_000_000 + 20*512 + 10 = 1_010_250
        let batch = make_neutron_batch(1000, &[80.0], &[160.0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_neutrons(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000 + 20 * 512 + 10]);
    }

    // --- DASlogs ---

    #[test]
    fn test_daslogs_write() {
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_daslogs(&[DasLogEntry {
            name: "BL10:Mot:S1:X".to_string(),
            time: vec![0.0, 1.0, 2.0],
            value: vec![-212.0, -212.0, -212.0],
            units: Some("mm".to_string()),
        }])
        .unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let log = f.group("entry/DASlogs/BL10:Mot:S1:X").unwrap();
        let nx_class: VarLenUnicode = log.attr("NX_class").unwrap().read_scalar().unwrap();
        assert_eq!(nx_class.as_str(), "NXlog");

        let times: Vec<f64> = log.dataset("time").unwrap().read_raw().unwrap();
        assert_eq!(times, vec![0.0, 1.0, 2.0]);

        let values: Vec<f64> = log.dataset("value").unwrap().read_raw().unwrap();
        assert_eq!(values, vec![-212.0, -212.0, -212.0]);
    }

    #[test]
    fn test_daslogs_mismatched_lengths_rejected() {
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let sink = SnsEventSink::create(path, opts).unwrap();
        let err = sink
            .write_daslogs(&[DasLogEntry {
                name: "BL10:Mot:S1:X".to_string(),
                time: vec![0.0, 1.0],
                value: vec![-212.0],
                units: Some("mm".to_string()),
            }])
            .unwrap_err();
        assert!(
            err.to_string().contains("time length"),
            "Expected length mismatch error, got: {err}"
        );
    }

    // --- VENUS defaults ---

    #[test]
    fn test_venus_defaults() {
        let opts = SnsWriteOptions::venus_defaults(make_test_run());
        assert_eq!(opts.banks.len(), 1);
        assert_eq!(opts.banks[0].name, "bank100");
        assert_eq!(opts.banks[0].pixel_id_offset, 1_000_000);
        assert_eq!(opts.banks[0].width, 512);
        assert_eq!(opts.banks[0].height, 512);
        assert_eq!(opts.instrument.name, "VENUS");
        assert_eq!(opts.instrument.beamline, "BL10");
    }

    // --- Dataset dtype validation ---

    #[test]
    fn test_dataset_dtypes() {
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[0], &[0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let bank = f.group("entry/bank100_events").unwrap();

        // event_id should be u32
        let eid = bank.dataset("event_id").unwrap();
        assert!(eid.read_raw::<u32>().is_ok());

        // event_time_offset should be f32
        let eto = bank.dataset("event_time_offset").unwrap();
        assert!(eto.read_raw::<f32>().is_ok());

        // event_time_zero should be f64
        let etz = bank.dataset("event_time_zero").unwrap();
        assert!(etz.read_raw::<f64>().is_ok());

        // event_index should be u64
        let idx = bank.dataset("event_index").unwrap();
        assert!(idx.read_raw::<u64>().is_ok());
    }

    // --- Coordinate clamping ---

    #[test]
    fn test_hit_pixel_id_remapped_through_gap() {
        // Hit at (513, 513) is beyond the gap (256, 257) so it is remapped
        // to (513 − 2, 513 − 2) = (511, 511) for a 512×512 bank.
        // Expected: offset + 511*512 + 511 = 1_262_143
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[513], &[513], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000 + 511 * 512 + 511]);
    }

    #[test]
    fn test_neutron_pixel_id_remapped_through_gap() {
        // Neutron at super-res (4104.0, 4104.0) with factor 8.0 -> pixel (513, 513)
        // Remapped through gap to (511, 511) for a 512×512 bank.
        let mut opts = make_test_options();
        opts.super_resolution_factor = 8.0;
        let batch = make_neutron_batch(1000, &[4104.0], &[4104.0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_neutrons(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000 + 511 * 512 + 511]);
    }

    #[test]
    fn test_hit_gap_pixel_dropped() {
        // Hit at (256, 100) — column 256 is a gap pixel, should be dropped.
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[256], &[100], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert!(ids.is_empty(), "Gap pixel should have been dropped");
    }

    #[test]
    fn test_hit_edge_column_preserved() {
        // Hit at (258, 0) — first real column after the gap — should remap
        // to column 256 (258 − 2 gap positions).
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[258], &[0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        // row 0, col 256 → offset + 256
        assert_eq!(ids, vec![1_000_256]);
    }

    #[test]
    fn test_hit_no_gap_bank_passes_through() {
        // A bank with no gap columns/rows should pass coordinates unchanged.
        let mut opts = make_test_options();
        opts.banks[0].gap_columns = vec![];
        opts.banks[0].gap_rows = vec![];
        let batch = make_hit_batch(1000, &[256], &[257], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000 + 257 * 512 + 256]);
    }

    // --- Bank index bounds ---

    #[test]
    fn test_invalid_bank_index() {
        let opts = make_test_options();
        let batch = make_hit_batch(1000, &[0], &[0], &[100]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        let result = sink.write_hits(99, &batch);
        assert!(result.is_err());
    }

    // --- Non-monotonic pulse timestamps ---

    #[test]
    fn test_non_monotonic_pulse_timestamp_rejected() {
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // First pulse at timestamp 2000 (25ns ticks).
        let batch1 = make_hit_batch(2000, &[0], &[0], &[100]);
        sink.write_hits(0, &batch1).unwrap();

        // Second pulse at earlier timestamp 1000 — should fail.
        let batch2 = make_hit_batch(1000, &[1], &[1], &[200]);
        let result = sink.write_hits(0, &batch2);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("non-monotonic"),
            "Expected non-monotonic error, got: {err_msg}"
        );
    }

    #[test]
    fn test_non_monotonic_regression_intermediate_decrease() {
        // Regression: sequence 1000→2000→1500 must be rejected even though
        // 1500 > run_start (1000). The check must compare against the
        // *previous* pulse, not just run start.
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        sink.write_hits(0, &make_hit_batch(1000, &[0], &[0], &[100]))
            .unwrap();
        sink.write_hits(0, &make_hit_batch(2000, &[1], &[1], &[200]))
            .unwrap();
        // 1500 < 2000 (previous pulse) → must error.
        let result = sink.write_hits(0, &make_hit_batch(1500, &[2], &[2], &[300]));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("non-monotonic"),);
    }

    // --- Out-of-bounds coordinate filtering (Bug 2) ---

    #[test]
    fn test_hit_out_of_bounds_dropped() {
        // Bank is 512×512. A hit at remapped (5, 3) is valid, but a hit at
        // raw coordinate 520 (no gaps) remaps to 520 which is >= 512 and
        // must be dropped.
        let mut opts = make_test_options();
        opts.banks[0].gap_columns = vec![];
        opts.banks[0].gap_rows = vec![];
        // Two hits: (5, 3) valid, (520, 3) out-of-bounds
        let batch = make_hit_batch(1000, &[5, 520], &[3, 3], &[100, 200]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        // Only the in-bounds hit survives: offset + 3*512 + 5
        assert_eq!(ids, vec![1_000_000 + 3 * 512 + 5]);
    }

    #[test]
    fn test_neutron_out_of_bounds_dropped() {
        // Same as above but for neutrons. Super-resolution factor 1.0,
        // no gaps, one valid neutron and one OOB.
        let mut opts = make_test_options();
        opts.banks[0].gap_columns = vec![];
        opts.banks[0].gap_rows = vec![];
        opts.super_resolution_factor = 1.0;
        // Two neutrons: (5.0, 3.0) valid, (520.0, 3.0) out-of-bounds
        let batch = make_neutron_batch(1000, &[5.0, 520.0], &[3.0, 3.0], &[100, 200]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_neutrons(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let ids: Vec<u32> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_id")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(ids, vec![1_000_000 + 3 * 512 + 5]);
    }

    // --- Pulse metadata filtering (Bug 3) ---

    #[test]
    fn test_all_gap_pulse_no_pulse_entry() {
        // A pulse where all hits land on gap pixels should produce no pulse
        // array entries and total_pulses = 0.
        let opts = make_test_options();
        // Both hits at gap columns (256, 257)
        let batch = make_hit_batch(1000, &[256, 257], &[0, 0], &[100, 200]);
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &batch).unwrap();
        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        let tp: u64 = entry
            .dataset("total_pulses")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tp, 0, "All-gap pulse should not increment total_pulses");

        let tc: u64 = entry
            .dataset("total_counts")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tc, 0);

        // No pulse entries should have been written
        let etz: Vec<f64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert!(
            etz.is_empty(),
            "No event_time_zero entries for all-gap pulse"
        );

        let idx: Vec<u64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_index")
            .unwrap()
            .read_raw()
            .unwrap();
        assert!(idx.is_empty(), "No event_index entries for all-gap pulse");
    }

    #[test]
    fn test_mixed_gap_and_valid_pulses() {
        // First pulse: all hits on gaps → no pulse entry.
        // Second pulse: one valid hit → exactly 1 pulse entry.
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // Pulse 1: all gap hits
        let gap_batch = make_hit_batch(1000, &[256, 257], &[0, 0], &[100, 200]);
        sink.write_hits(0, &gap_batch).unwrap();

        // Pulse 2: one valid hit at (5, 3)
        let valid_batch = make_hit_batch(2000, &[5], &[3], &[300]);
        sink.write_hits(0, &valid_batch).unwrap();

        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        let tp: u64 = entry
            .dataset("total_pulses")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tp, 1, "Only the valid pulse should be counted");

        let tc: u64 = entry
            .dataset("total_counts")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tc, 1);

        let etz: Vec<f64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(etz.len(), 1, "Only one pulse entry");

        let idx: Vec<u64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_index")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(idx, vec![0u64], "Single pulse starts at event 0");
    }

    // --- Empty pulse time-origin exclusion ---

    #[test]
    fn test_empty_pulse_does_not_shift_time_origin() {
        // Empty pulse at tdc=1000, valid pulse at tdc=2000.
        // min_pulse_ns must be based on tdc=2000 (the first *written* pulse),
        // so event_time_zero[0] must be 0.0, NOT offset by the empty pulse.
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // Pulse 1 (tdc=1000): all gap-column hits → 0 events written
        let gap_batch = make_hit_batch(1000, &[256, 257], &[0, 0], &[100, 200]);
        sink.write_hits(0, &gap_batch).unwrap();

        // Pulse 2 (tdc=2000): one valid hit
        let valid_batch = make_hit_batch(2000, &[5], &[3], &[300]);
        sink.write_hits(0, &valid_batch).unwrap();

        sink.finalize().unwrap();

        let f = File::open(path).unwrap();

        let etz: Vec<f64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(etz.len(), 1, "Only the non-empty pulse gets an entry");
        assert!(
            (etz[0] - 0.0).abs() < 1e-12,
            "First written pulse must be time-origin zero, got {}",
            etz[0]
        );
    }

    #[test]
    fn test_empty_pulse_does_not_shift_duration() {
        // Empty pulse at tdc=5000, two valid pulses at tdc=1000 and tdc=2000.
        // max_pulse_ns should be based on tdc=2000 (not tdc=5000), so
        // duration should reflect only the written pulses.
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // Pulse 1 (tdc=1000): valid hit
        sink.write_hits(0, &make_hit_batch(1000, &[5], &[3], &[100]))
            .unwrap();

        // Pulse 2 (tdc=2000): valid hit
        sink.write_hits(0, &make_hit_batch(2000, &[5], &[3], &[200]))
            .unwrap();

        // Pulse 3 (tdc=5000): all gap hits → 0 written events
        sink.write_hits(0, &make_hit_batch(5000, &[256], &[0], &[300]))
            .unwrap();

        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        let duration: f64 = entry.dataset("duration").unwrap().read_scalar().unwrap();
        // Duration should be (2000 - 1000) * 25 ns = 25 µs = 25e-6 s
        let expected = f64::from(2000 - 1000) * 25e-9;
        assert!(
            (duration - expected).abs() < 1e-12,
            "Duration must reflect only written pulses: expected {expected}, got {duration}"
        );
    }

    // --- TDC rebase monotonicity (Bug 1) ---

    #[test]
    fn test_monotonic_rebased_timestamps_accepted() {
        // Simulates what the CLI rebase does: File 1 has timestamps
        // 1000→2000, File 2 has timestamps 500→1500 rebased to 2001→2501.
        // The sink should accept all four pulses without error.
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // File 1 timestamps (no offset)
        sink.write_hits(0, &make_hit_batch(1000, &[0], &[0], &[100]))
            .unwrap();
        sink.write_hits(0, &make_hit_batch(2000, &[1], &[1], &[200]))
            .unwrap();

        // File 2 timestamps rebased: 500 + 2001 = 2501, 1500 + 2001 = 3501
        let tdc_offset: u64 = 2001; // last_tdc_seen(2000) + 1
        sink.write_hits(0, &make_hit_batch(500 + tdc_offset, &[2], &[2], &[300]))
            .unwrap();
        sink.write_hits(0, &make_hit_batch(1500 + tdc_offset, &[3], &[3], &[400]))
            .unwrap();

        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        let tp: u64 = entry
            .dataset("total_pulses")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tp, 4);

        let tc: u64 = entry
            .dataset("total_counts")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tc, 4);

        // Verify pulse times are monotonically increasing
        let etz: Vec<f64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(etz.len(), 4);
        for i in 1..etz.len() {
            assert!(
                etz[i] > etz[i - 1],
                "Pulse times must be monotonically increasing: etz[{}]={} <= etz[{}]={}",
                i,
                etz[i],
                i - 1,
                etz[i - 1]
            );
        }
    }

    // --- Per-bank monotonicity ---

    #[test]
    fn test_sequential_multi_bank_writes_accepted() {
        // Write all pulses for bank 0, then all pulses for bank 1.
        // Bank 1's first pulse (tdc=1000) is less than bank 0's last (tdc=3000),
        // but per-bank ordering is valid.
        let mut opts = make_test_options();
        opts.banks.push(SnsBankConfig {
            name: "bank200".to_string(),
            pixel_id_offset: 2_000_000,
            width: 512,
            height: 512,
            gap_columns: vec![256, 257],
            gap_rows: vec![256, 257],
        });
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // Bank 0: timestamps 1000, 2000, 3000
        sink.write_hits(0, &make_hit_batch(1000, &[0], &[0], &[100]))
            .unwrap();
        sink.write_hits(0, &make_hit_batch(2000, &[1], &[1], &[200]))
            .unwrap();
        sink.write_hits(0, &make_hit_batch(3000, &[2], &[2], &[300]))
            .unwrap();

        // Bank 1: timestamps 1000, 2000, 3000 (restart from 1000 is fine)
        sink.write_hits(1, &make_hit_batch(1000, &[0], &[0], &[100]))
            .unwrap();
        sink.write_hits(1, &make_hit_batch(2000, &[1], &[1], &[200]))
            .unwrap();
        sink.write_hits(1, &make_hit_batch(3000, &[2], &[2], &[300]))
            .unwrap();

        sink.finalize().unwrap();

        let f = File::open(path).unwrap();
        let entry = f.group("entry").unwrap();

        let tc: u64 = entry
            .dataset("total_counts")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tc, 6); // 3 per bank

        let tp: u64 = entry
            .dataset("total_pulses")
            .unwrap()
            .read_scalar()
            .unwrap();
        assert_eq!(tp, 3); // 3 unique pulse timestamps, deduplicated

        // Each bank has 3 events and 3 pulse entries
        for bank_name in &["bank100_events", "bank200_events"] {
            let bank = f.group(&format!("entry/{bank_name}")).unwrap();
            let ids: Vec<u32> = bank.dataset("event_id").unwrap().read_raw().unwrap();
            assert_eq!(ids.len(), 3);
            let etz: Vec<f64> = bank.dataset("event_time_zero").unwrap().read_raw().unwrap();
            assert_eq!(etz.len(), 3);
        }
    }

    #[test]
    fn test_per_bank_non_monotonic_rejected() {
        // Within a single bank, non-monotonic timestamps must still be rejected.
        let mut opts = make_test_options();
        opts.banks.push(SnsBankConfig {
            name: "bank200".to_string(),
            pixel_id_offset: 2_000_000,
            width: 512,
            height: 512,
            gap_columns: vec![256, 257],
            gap_rows: vec![256, 257],
        });
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // Bank 1: timestamps 2000 then 1000 — non-monotonic within same bank
        sink.write_hits(1, &make_hit_batch(2000, &[0], &[0], &[100]))
            .unwrap();
        let result = sink.write_hits(1, &make_hit_batch(1000, &[1], &[1], &[200]));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("non-monotonic"));
    }

    #[test]
    fn test_later_bank_with_earlier_timestamps() {
        // Bank 0 written first with later timestamps (5000, 6000),
        // then bank 1 written with earlier timestamps (1000, 2000).
        // event_time_zero must use global min (1000*25=25000 ns) as origin,
        // so bank 0's first pulse is at (5000*25 - 1000*25)/1e9 seconds
        // and bank 1's first pulse is at 0.0.
        let mut opts = make_test_options();
        opts.banks.push(SnsBankConfig {
            name: "bank200".to_string(),
            pixel_id_offset: 2_000_000,
            width: 512,
            height: 512,
            gap_columns: vec![256, 257],
            gap_rows: vec![256, 257],
        });
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();

        // Bank 0: later timestamps
        sink.write_hits(0, &make_hit_batch(5000, &[0], &[0], &[100]))
            .unwrap();
        sink.write_hits(0, &make_hit_batch(6000, &[1], &[1], &[200]))
            .unwrap();

        // Bank 1: earlier timestamps (this used to underflow/fail)
        sink.write_hits(1, &make_hit_batch(1000, &[0], &[0], &[100]))
            .unwrap();
        sink.write_hits(1, &make_hit_batch(2000, &[1], &[1], &[200]))
            .unwrap();

        sink.finalize().unwrap();

        let f = File::open(path).unwrap();

        // Bank 1 has the global minimum (1000*25ns = 25000ns),
        // so its first pulse should be at t=0.0
        let etz1: Vec<f64> = f
            .group("entry/bank200_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(etz1.len(), 2);
        assert!(
            etz1[0].abs() < 1e-12,
            "Bank 1's first pulse should be at t=0, got {}",
            etz1[0]
        );
        // Bank 1's second pulse: (2000-1000)*25ns = 25000ns = 25µs
        let expected_1 = (2000.0 - 1000.0) * 25.0 / 1_000_000_000.0;
        assert!(
            (etz1[1] - expected_1).abs() < 1e-12,
            "Expected {expected_1}, got {}",
            etz1[1]
        );

        // Bank 0's first pulse: (5000-1000)*25ns = 100000ns = 100µs
        let etz0: Vec<f64> = f
            .group("entry/bank100_events")
            .unwrap()
            .dataset("event_time_zero")
            .unwrap()
            .read_raw()
            .unwrap();
        assert_eq!(etz0.len(), 2);
        let expected_0_first = (5000.0 - 1000.0) * 25.0 / 1_000_000_000.0;
        assert!(
            (etz0[0] - expected_0_first).abs() < 1e-12,
            "Expected {expected_0_first}, got {}",
            etz0[0]
        );

        // Duration should be from min(1000) to max(6000): 5000*25ns
        let entry = f.group("entry").unwrap();
        let duration: f64 = entry.dataset("duration").unwrap().read_scalar().unwrap();
        let expected_dur = 5000.0 * 25.0 / 1_000_000_000.0;
        assert!(
            (duration - expected_dur).abs() < 1e-12,
            "Expected duration {expected_dur}, got {duration}"
        );
    }

    // --- Post-finalization guard ---

    #[test]
    fn test_write_hits_after_finalize_rejected() {
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_hits(0, &make_hit_batch(1000, &[0], &[0], &[100]))
            .unwrap();
        sink.finalize().unwrap();

        let err = sink
            .write_hits(0, &make_hit_batch(2000, &[1], &[1], &[200]))
            .unwrap_err();
        assert!(
            err.to_string().contains("finalization"),
            "Expected finalization error, got: {err}"
        );
    }

    #[test]
    fn test_write_neutrons_after_finalize_rejected() {
        let opts = make_test_options();
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        let mut sink = SnsEventSink::create(path, opts).unwrap();
        sink.write_neutrons(0, &make_neutron_batch(1000, &[0.5], &[0.5], &[100]))
            .unwrap();
        sink.finalize().unwrap();

        let err = sink
            .write_neutrons(0, &make_neutron_batch(2000, &[1.5], &[1.5], &[200]))
            .unwrap_err();
        assert!(
            err.to_string().contains("finalization"),
            "Expected finalization error, got: {err}"
        );
    }
}