mf4-rs 1.2.0

mf4-rs is a Rust library for working with ASAM MDF 4 (Measurement Data Format) files.
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
//! Python bindings for mf4-rs using PyO3
//!
//! This module provides Python bindings for the main functionality of mf4-rs:
//! - Parsing MDF files
//! - Writing MDF files
//! - Creating and using indexes

use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use pyo3::{create_exception, wrap_pyfunction};
use numpy::{PyArray1, PyReadonlyArray1};
use std::collections::HashMap;

use crate::api::mdf::MDF;
use crate::writer::{MdfWriter, ColumnData};
use crate::index::{MdfIndex, FileRangeReader, IndexedChannel};
use crate::blocks::common::DataType;
use crate::parsing::decoder::DecodedValue;
use crate::error::MdfError;
use crate::block_layout::{BlockInfo, FileLayout, GapInfo, LinkInfo};

// Custom exception for MDF errors
create_exception!(mf4_rs, MdfException, pyo3::exceptions::PyException);

// Convert Rust MdfError to Python exception
impl From<MdfError> for PyErr {
    fn from(err: MdfError) -> PyErr {
        MdfException::new_err(format!("{:?}", err))
    }
}

// Python-friendly data type enum
#[pyclass]
#[derive(Debug, Clone)]
pub struct PyDataType {
    #[pyo3(get)]
    pub name: String,
    #[pyo3(get)]
    pub value: u8,
}

#[pymethods]
impl PyDataType {
    fn __str__(&self) -> String {
        self.name.clone()
    }
    
    fn __repr__(&self) -> String {
        format!("DataType({})", self.name)
    }
}

impl From<&DataType> for PyDataType {
    fn from(dt: &DataType) -> Self {
        let (name, value) = match dt {
            DataType::UnsignedIntegerLE => ("UnsignedIntegerLE", 0),
            DataType::UnsignedIntegerBE => ("UnsignedIntegerBE", 1),
            DataType::SignedIntegerLE => ("SignedIntegerLE", 2),
            DataType::SignedIntegerBE => ("SignedIntegerBE", 3),
            DataType::FloatLE => ("FloatLE", 4),
            DataType::FloatBE => ("FloatBE", 5),
            DataType::StringLatin1 => ("StringLatin1", 6),
            DataType::StringUtf8 => ("StringUtf8", 7),
            DataType::StringUtf16LE => ("StringUtf16LE", 8),
            DataType::StringUtf16BE => ("StringUtf16BE", 9),
            DataType::ByteArray => ("ByteArray", 10),
            DataType::MimeSample => ("MimeSample", 11),
            DataType::MimeStream => ("MimeStream", 12),
            DataType::CanOpenDate => ("CanOpenDate", 13),
            DataType::CanOpenTime => ("CanOpenTime", 14),
            DataType::ComplexLE => ("ComplexLE", 15),
            DataType::ComplexBE => ("ComplexBE", 16),
            DataType::Unknown(_) => ("Unknown", 255),
        };
        PyDataType {
            name: name.to_string(),
            value,
        }
    }
}

impl From<PyDataType> for DataType {
    fn from(py_dt: PyDataType) -> Self {
        match py_dt.value {
            0 => DataType::UnsignedIntegerLE,
            1 => DataType::UnsignedIntegerBE,
            2 => DataType::SignedIntegerLE,
            3 => DataType::SignedIntegerBE,
            4 => DataType::FloatLE,
            5 => DataType::FloatBE,
            6 => DataType::StringLatin1,
            7 => DataType::StringUtf8,
            8 => DataType::StringUtf16LE,
            9 => DataType::StringUtf16BE,
            10 => DataType::ByteArray,
            11 => DataType::MimeSample,
            12 => DataType::MimeStream,
            13 => DataType::CanOpenDate,
            14 => DataType::CanOpenTime,
            15 => DataType::ComplexLE,
            16 => DataType::ComplexBE,
            _ => DataType::Unknown(()),
        }
    }
}

// Python-friendly decoded value
#[pyclass]
#[derive(Debug, Clone)]
pub enum PyDecodedValue {
    Float { value: f64 },
    UnsignedInteger { value: u64 },
    SignedInteger { value: i64 },
    String { value: String },
    ByteArray { value: Vec<u8> },
    Unknown { },
}

#[pymethods]
impl PyDecodedValue {
    fn __str__(&self) -> String {
        match self {
            PyDecodedValue::Float { value } => format!("{}", value),
            PyDecodedValue::UnsignedInteger { value } => format!("{}", value),
            PyDecodedValue::SignedInteger { value } => format!("{}", value),
            PyDecodedValue::String { value } => value.clone(),
            PyDecodedValue::ByteArray { value } => format!("bytes[{}]", value.len()),
            PyDecodedValue::Unknown { } => "Unknown".to_string(),
        }
    }
    
    fn __repr__(&self) -> String {
        match self {
            PyDecodedValue::Float { value } => format!("Float({})", value),
            PyDecodedValue::UnsignedInteger { value } => format!("UnsignedInteger({})", value),
            PyDecodedValue::SignedInteger { value } => format!("SignedInteger({})", value),
            PyDecodedValue::String { value } => format!("String('{}')", value),
            PyDecodedValue::ByteArray { value } => format!("ByteArray({})", value.len()),
            PyDecodedValue::Unknown { } => "Unknown".to_string(),
        }
    }
    
    #[getter]
    fn value(&self, py: Python) -> PyObject {
        match self {
            PyDecodedValue::Float { value } => value.to_object(py),
            PyDecodedValue::UnsignedInteger { value } => value.to_object(py),
            PyDecodedValue::SignedInteger { value } => value.to_object(py),
            PyDecodedValue::String { value } => value.to_object(py),
            PyDecodedValue::ByteArray { value } => value.to_object(py),
            PyDecodedValue::Unknown { } => py.None(),
        }
    }
}

impl From<DecodedValue> for PyDecodedValue {
    fn from(dv: DecodedValue) -> Self {
        match dv {
            DecodedValue::Float(v) => PyDecodedValue::Float { value: v },
            DecodedValue::UnsignedInteger(v) => PyDecodedValue::UnsignedInteger { value: v },
            DecodedValue::SignedInteger(v) => PyDecodedValue::SignedInteger { value: v },
            DecodedValue::String(v) => PyDecodedValue::String { value: v },
            DecodedValue::ByteArray(v) => PyDecodedValue::ByteArray { value: v },
            DecodedValue::MimeSample(v) => PyDecodedValue::ByteArray { value: v },
            DecodedValue::MimeStream(v) => PyDecodedValue::ByteArray { value: v },
            DecodedValue::Unknown => PyDecodedValue::Unknown { },
        }
    }
}

impl From<PyDecodedValue> for DecodedValue {
    fn from(py_dv: PyDecodedValue) -> Self {
        match py_dv {
            PyDecodedValue::Float { value } => DecodedValue::Float(value),
            PyDecodedValue::UnsignedInteger { value } => DecodedValue::UnsignedInteger(value),
            PyDecodedValue::SignedInteger { value } => DecodedValue::SignedInteger(value),
            PyDecodedValue::String { value } => DecodedValue::String(value),
            PyDecodedValue::ByteArray { value } => DecodedValue::ByteArray(value),
            PyDecodedValue::Unknown { } => DecodedValue::Unknown,
        }
    }
}

/// Direct conversion from DecodedValue to PyObject without intermediate allocation.
/// This is more efficient than creating a PyDecodedValue and immediately extracting its value.
fn decoded_value_to_pyobject(dv: DecodedValue, py: Python) -> PyObject {
    match dv {
        DecodedValue::Float(v) => v.to_object(py),
        DecodedValue::UnsignedInteger(v) => v.to_object(py),
        DecodedValue::SignedInteger(v) => v.to_object(py),
        DecodedValue::String(v) => v.to_object(py),
        DecodedValue::ByteArray(v) | DecodedValue::MimeSample(v) | DecodedValue::MimeStream(v) => {
            v.to_object(py)
        }
        DecodedValue::Unknown => py.None(),
    }
}

// Simplified Channel info structure to avoid lifetime issues
#[pyclass]
#[derive(Debug, Clone)]
pub struct PyChannelInfo {
    #[pyo3(get)]
    pub name: Option<String>,
    #[pyo3(get)] 
    pub unit: Option<String>,
    #[pyo3(get)]
    pub comment: Option<String>,
    #[pyo3(get)]
    pub data_type: PyDataType,
    #[pyo3(get)]
    pub bit_count: u32,
}

#[pymethods]
impl PyChannelInfo {
    fn __str__(&self) -> String {
        format!("Channel(name={:?}, data_type={}, bit_count={})", 
                self.name, self.data_type.name, self.bit_count)
    }
    
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

// Simplified ChannelGroup info structure
#[pyclass]
#[derive(Debug, Clone)]
pub struct PyChannelGroupInfo {
    #[pyo3(get)]
    pub name: Option<String>,
    #[pyo3(get)]
    pub comment: Option<String>,
    #[pyo3(get)]
    pub channel_count: usize,
    #[pyo3(get)]
    pub record_count: u64,
}

#[pymethods]
impl PyChannelGroupInfo {
    fn __str__(&self) -> String {
        format!("ChannelGroup(name={:?}, channels={}, records={})", 
                self.name, self.channel_count, self.record_count)
    }
    
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

/// Helper function to check if pandas is available and import it
fn check_pandas_available(py: Python) -> PyResult<PyObject> {
    py.import_bound("pandas")
        .map(|m| m.into())
        .map_err(|_| MdfException::new_err(
            "Pandas is not installed. Please install pandas to use Series-based methods."
        ))
}

/// Helper function to find the master/time channel in a channel group
/// Returns None if no master channel is found
fn find_master_channel<'a>(channels: &Vec<crate::api::channel::Channel<'a>>) -> Option<usize> {
    for (idx, channel) in channels.iter().enumerate() {
        let block = channel.block();
        // Master channels have channel_type == 2
        if block.channel_type == 2 {
            return Some(idx);
        }
    }
    None
}

/// Helper function to find the master/time channel in indexed channels
/// Returns None if no master channel is found
fn find_master_channel_indexed(channels: &Vec<IndexedChannel>) -> Option<usize> {
    for (idx, channel) in channels.iter().enumerate() {
        // Master channels have channel_type == 2
        if channel.channel_type == 2 {
            return Some(idx);
        }
    }
    None
}

/// Helper function to create a pandas DatetimeIndex from relative time values
///
/// # Arguments
/// * `py` - Python GIL token
/// * `pd` - pandas module PyObject
/// * `relative_times` - Vector of relative time values (in seconds) as PyObjects
/// * `start_ns` - Start time in nanoseconds since epoch
///
/// # Returns
/// PyObject representing a pandas DatetimeIndex, or an error if conversion fails
///
/// # Error Handling
/// This function handles multiple edge cases:
/// - None values in master channel (converted to NaT - Not a Time)
/// - Integer time values (i64, u64) in addition to float values
/// - Negative time values that would create timestamps before epoch
/// - Overflow/underflow when adding large time deltas
fn create_datetime_index(
    py: Python,
    pd: &PyObject,
    relative_times: &[PyObject],
    start_ns: u64,
) -> PyResult<PyObject> {
    // Convert start time from nanoseconds to a pandas Timestamp
    let to_datetime = pd.getattr(py, "to_datetime")?;
    let start_timestamp = to_datetime.call(
        py,
        (start_ns,),
        Some([("unit", "ns")].into_py_dict(py))
    )?;

    // Create a Timedelta for each relative time and add to start time
    let timedelta_class = pd.getattr(py, "Timedelta")?;
    let nat = pd.getattr(py, "NaT")?;  // Not-a-Time for None values
    let mut absolute_times = Vec::with_capacity(relative_times.len());

    for rel_time in relative_times {
        // Handle None values (invalid samples) - convert to NaT
        if rel_time.is_none(py) {
            absolute_times.push(nat.clone());
            continue;
        }

        // Try to extract the time value as f64, then i64, then u64
        // Master channels can be float or integer type
        let seconds: f64 = if let Ok(f) = rel_time.extract::<f64>(py) {
            f
        } else if let Ok(i) = rel_time.extract::<i64>(py) {
            i as f64
        } else if let Ok(u) = rel_time.extract::<u64>(py) {
            u as f64
        } else {
            // If we can't extract as any numeric type, use NaT
            absolute_times.push(nat.clone());
            continue;
        };

        // Check for edge cases that might cause overflow or invalid timestamps
        // pandas datetime64[ns] has range: 1678-2262 (approximately)
        // If start_ns + seconds would overflow, pandas will raise an OutOfBoundsDatetime error
        // We'll let pandas handle this and propagate the error up

        // Create a Timedelta in seconds and add to start time
        // This can fail if the resulting timestamp is out of pandas' valid range
        let delta = timedelta_class.call(
            py,
            (seconds,),
            Some([("unit", "s")].into_py_dict(py))
        )?;

        let absolute_time = start_timestamp.call_method1(py, "__add__", (delta,))?;
        absolute_times.push(absolute_time);
    }

    // Create DatetimeIndex from the list of timestamps
    let datetime_index_class = pd.getattr(py, "DatetimeIndex")?;
    let datetime_index = datetime_index_class.call1(py, (absolute_times,))?;

    Ok(datetime_index)
}

// Python wrapper for MDF
#[pyclass]
pub struct PyMDF {
    mdf: Box<MDF>,
}

#[pymethods]
impl PyMDF {
    /// Create a new PyMDF from a file path
    #[new]
    fn new(path: &str) -> PyResult<Self> {
        let mdf = Box::new(MDF::from_file(path)?);
        Ok(PyMDF { mdf })
    }
    
    /// Get all channel groups info
    fn channel_groups(&self) -> PyResult<Vec<PyChannelGroupInfo>> {
        let mut py_groups = Vec::new();
        
        for group in self.mdf.channel_groups() {
            let name = group.name()?;
            let comment = group.comment()?;
            let channel_count = group.channels().len();
            let record_count = group.raw_channel_group().block.cycles_nr;
            
            py_groups.push(PyChannelGroupInfo {
                name,
                comment,
                channel_count,
                record_count,
            });
        }
        
        Ok(py_groups)
    }
    
    /// Get channel info for all channels in all groups
    fn get_all_channels(&self) -> PyResult<Vec<PyChannelInfo>> {
        let mut channels = Vec::new();
        
        for group in self.mdf.channel_groups() {
            for channel in group.channels() {
                let block = channel.block();
                let info = PyChannelInfo {
                    name: channel.name()?,
                    unit: channel.unit()?,
                    comment: channel.comment()?,
                    data_type: PyDataType::from(&block.data_type),
                    bit_count: block.bit_count,
                };
                channels.push(info);
            }
        }
        
        Ok(channels)
    }
    
    /// Get channels for a specific group by index
    fn get_channels_for_group(&self, group_index: usize) -> PyResult<Vec<PyChannelInfo>> {
        let groups: Vec<_> = self.mdf.channel_groups().into_iter().collect();
        if let Some(group) = groups.get(group_index) {
            let mut channels = Vec::new();
            
            for channel in group.channels() {
                let block = channel.block();
                let info = PyChannelInfo {
                    name: channel.name()?,
                    unit: channel.unit()?,
                    comment: channel.comment()?,
                    data_type: PyDataType::from(&block.data_type),
                    bit_count: block.bit_count,
                };
                channels.push(info);
            }
            
            Ok(channels)
        } else {
            Err(MdfException::new_err("Group index out of bounds"))
        }
    }
    
    /// Get channel names from all groups
    fn get_all_channel_names(&self) -> PyResult<Vec<String>> {
        let mut names = Vec::new();
        for group in self.mdf.channel_groups() {
            for channel in group.channels() {
                if let Some(name) = channel.name()? {
                    names.push(name);
                }
            }
        }
        Ok(names)
    }
    
    /// Get channel values by name (first match) as a numpy float64 array.
    ///
    /// Returns channel data directly as a numpy ndarray. This is the fastest
    /// way to read numeric channels. Non-decodable values are returned as NaN.
    ///
    /// Returns None if the channel is not found.
    fn get_channel_values<'py>(&self, py: Python<'py>, channel_name: &str) -> PyResult<Option<PyObject>> {
        for group in self.mdf.channel_groups() {
            for channel in group.channels() {
                if let Some(name) = channel.name()? {
                    if name == channel_name {
                        let values = channel.values_as_f64()?;
                        let array = PyArray1::from_vec_bound(py, values);
                        return Ok(Some(array.into()));
                    }
                }
            }
        }
        Ok(None)
    }

    /// Get channel values by channel group name and channel name as numpy array.
    ///
    /// Returns None if either the group or channel is not found.
    fn get_channel_values_by_group_and_name<'py>(&self, py: Python<'py>, group_name: &str, channel_name: &str) -> PyResult<Option<PyObject>> {
        for group in self.mdf.channel_groups() {
            if let Some(gname) = group.name()? {
                if gname == group_name {
                    for channel in group.channels() {
                        if let Some(cname) = channel.name()? {
                            if cname == channel_name {
                                let values = channel.values_as_f64()?;
                                let array = PyArray1::from_vec_bound(py, values);
                                return Ok(Some(array.into()));
                            }
                        }
                    }
                    return Ok(None);
                }
            }
        }
        Ok(None)
    }

    /// Get channel data as a pandas Series with time/master channel as DatetimeIndex.
    ///
    /// Returns None if the channel is not found, otherwise returns a pandas Series.
    fn get_channel_as_series(&self, py: Python, channel_name: &str) -> PyResult<Option<PyObject>> {
        let pd = check_pandas_available(py)?;
        let start_time_ns = self.mdf.start_time_ns();

        for group in self.mdf.channel_groups() {
            let channels = group.channels();

            for (ch_idx, channel) in channels.iter().enumerate() {
                if let Some(name) = channel.name()? {
                    if name == channel_name {
                        let values = channel.values_as_f64()?;
                        let py_values = PyArray1::from_vec_bound(py, values);

                        let index: PyObject = if let Some(master_idx) = find_master_channel(&channels) {
                            if master_idx != ch_idx {
                                let master_values = channels[master_idx].values_as_f64()?;
                                let py_master = PyArray1::from_vec_bound(py, master_values);

                                if let Some(start_ns) = start_time_ns {
                                    // Vectorized datetime conversion using pandas
                                    let to_datetime = pd.getattr(py, "to_datetime")?;
                                    let to_timedelta = pd.getattr(py, "to_timedelta")?;
                                    let start_ts = to_datetime.call(
                                        py, (start_ns,),
                                        Some([("unit", "ns")].into_py_dict(py))
                                    )?;
                                    let deltas = to_timedelta.call(
                                        py, (py_master.clone(),),
                                        Some([("unit", "s")].into_py_dict(py))
                                    )?;
                                    match deltas.call_method1(py, "__add__", (start_ts,)) {
                                        Ok(datetime_index) => datetime_index,
                                        Err(_) => py_master.into(),
                                    }
                                } else {
                                    py_master.into()
                                }
                            } else {
                                py.None()
                            }
                        } else {
                            py.None()
                        };

                        let series_class = pd.getattr(py, "Series")?;
                        let series = if index.is_none(py) {
                            series_class.call1(py, (py_values,))?
                        } else {
                            series_class.call(py, (py_values,), Some([("index", index)].into_py_dict(py)))?
                        };

                        series.setattr(py, "name", channel_name)?;
                        return Ok(Some(series));
                    }
                }
            }
        }
        Ok(None)
    }

    /// Build a [`PyFileLayout`] describing every block in this file.
    ///
    /// Use this to inspect on-disk byte ranges, link chains and how data
    /// is stored relative to block definitions.
    fn file_layout(&self) -> PyResult<PyFileLayout> {
        let layout = self.mdf.file_layout()?;
        Ok(PyFileLayout { inner: layout })
    }
}

// Python wrapper for MdfWriter
#[pyclass(unsendable)]
pub struct PyMdfWriter {
    writer: Option<MdfWriter>,
    channel_groups: HashMap<String, String>, // Maps Python ID to Rust ID
    channels: HashMap<String, String>,       // Maps Python ID to Rust ID
    // Track the last channel added for each channel group (for automatic linking)
    last_channels: HashMap<String, String>,   // Maps channel group ID to last channel ID
    next_id: usize,
}

impl PyMdfWriter {
    fn add_channel_with_bits(&mut self, group_id: &str, name: &str, data_type: PyDataType, bit_count: u32) -> PyResult<String> {
        if let Some(ref mut writer) = self.writer {
            let cg_id = self.channel_groups.get(group_id)
                .ok_or_else(|| MdfException::new_err("Channel group not found"))?;
            let prev_channel_id = self.last_channels.get(group_id)
                .and_then(|py_id| self.channels.get(py_id))
                .cloned();
            let rust_data_type = DataType::from(data_type);
            let ch_id = writer.add_channel(cg_id, prev_channel_id.as_ref().map(|s| s.as_str()), |ch| {
                ch.data_type = rust_data_type.clone();
                ch.name = Some(name.to_string());
                ch.bit_count = bit_count;
            })?;
            let py_id = format!("ch_{}", self.next_id);
            self.next_id += 1;
            self.channels.insert(py_id.clone(), ch_id);
            self.last_channels.insert(group_id.to_string(), py_id.clone());
            Ok(py_id)
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
}

#[pymethods]
impl PyMdfWriter {
    /// Create a new MdfWriter
    #[new]
    fn new(path: &str) -> PyResult<Self> {
        let writer = MdfWriter::new(path)?;
        Ok(PyMdfWriter {
            writer: Some(writer),
            channel_groups: HashMap::new(),
            channels: HashMap::new(),
            last_channels: HashMap::new(),
            next_id: 0,
        })
    }
    
    /// Initialize the MDF file
    fn init_mdf_file(&mut self) -> PyResult<()> {
        if let Some(ref mut writer) = self.writer {
            writer.init_mdf_file()?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
    
    /// Add a channel group
    fn add_channel_group(&mut self, name: Option<String>) -> PyResult<String> {
        if let Some(ref mut writer) = self.writer {
            let cg_id = writer.add_channel_group(None, |_cg| {
                // Could set channel group properties here
            })?;
            
            let py_id = format!("cg_{}", self.next_id);
            self.next_id += 1;
            self.channel_groups.insert(py_id.clone(), cg_id);
            
            Ok(py_id)
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
    
    /// Add a channel to a channel group with automatic linking and bit count
    fn add_channel(&mut self,
                   group_id: &str,
                   name: &str,
                   data_type: PyDataType) -> PyResult<String> {
        let bits = {
            let rust_dt = DataType::from(data_type.clone());
            rust_dt.default_bits()
        };
        self.add_channel_with_bits(group_id, name, data_type, bits)
    }
    
    /// Add a time channel (float64, commonly used as master channel)
    fn add_time_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
        let ch_id = self.add_channel_with_bits(group_id, name, PyDataType { name: "FloatLE".to_string(), value: 4 }, 64)?;
        self.set_time_channel(&ch_id)?;
        Ok(ch_id)
    }

    /// Add a float64 data channel (default for scientific data)
    fn add_float_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
        self.add_channel_with_bits(group_id, name, PyDataType { name: "FloatLE".to_string(), value: 4 }, 64)
    }

    /// Add a float32 data channel
    fn add_float32_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
        self.add_channel_with_bits(group_id, name, PyDataType { name: "FloatLE".to_string(), value: 4 }, 32)
    }

    /// Add an integer data channel (64-bit unsigned)
    fn add_int_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
        self.add_channel_with_bits(group_id, name, PyDataType { name: "UnsignedIntegerLE".to_string(), value: 0 }, 64)
    }
    
    /// Set a channel as time/master channel
    fn set_time_channel(&mut self, channel_id: &str) -> PyResult<()> {
        if let Some(ref mut writer) = self.writer {
            let ch_id = self.channels.get(channel_id)
                .ok_or_else(|| MdfException::new_err("Channel not found"))?;
            writer.set_time_channel(ch_id)?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
    
    /// Start data block for a channel group
    fn start_data_block(&mut self, group_id: &str) -> PyResult<()> {
        if let Some(ref mut writer) = self.writer {
            let cg_id = self.channel_groups.get(group_id)
                .ok_or_else(|| MdfException::new_err("Channel group not found"))?;
            writer.start_data_block_for_cg(cg_id, 0)?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
    
    /// Write a record to a channel group
    fn write_record(&mut self, group_id: &str, values: Vec<PyDecodedValue>) -> PyResult<()> {
        if let Some(ref mut writer) = self.writer {
            let cg_id = self.channel_groups.get(group_id)
                .ok_or_else(|| MdfException::new_err("Channel group not found"))?;
            
            let rust_values: Vec<DecodedValue> = values.into_iter().map(DecodedValue::from).collect();
            writer.write_record(cg_id, &rust_values)?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
    
    /// Finish data block for a channel group
    fn finish_data_block(&mut self, group_id: &str) -> PyResult<()> {
        if let Some(ref mut writer) = self.writer {
            let cg_id = self.channel_groups.get(group_id)
                .ok_or_else(|| MdfException::new_err("Channel group not found"))?;
            writer.finish_data_block(cg_id)?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }
    
    /// Write multiple channels at once using numpy float64 arrays (one array per channel).
    ///
    /// `columns` must be a list of 1-D numpy float64 arrays all of the same length.
    /// This is significantly faster than calling `write_record` in a loop.
    fn write_columns_f64(&mut self, _py: Python<'_>, group_id: &str, columns: Vec<Bound<'_, PyAny>>) -> PyResult<()> {
        if let Some(ref mut writer) = self.writer {
            let cg_id = self.channel_groups.get(group_id)
                .ok_or_else(|| MdfException::new_err("Channel group not found"))?
                .clone();

            let arrays: Vec<PyReadonlyArray1<f64>> = columns.iter()
                .map(|c| c.extract::<PyReadonlyArray1<f64>>())
                .collect::<PyResult<Vec<_>>>()?;
            let slices: Vec<&[f64]> = arrays.iter()
                .map(|a| a.as_slice().map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))))
                .collect::<PyResult<Vec<_>>>()?;

            writer.write_columns_f64(&cg_id, &slices)?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }

    /// Write multiple channels at once using numpy arrays with explicit dtype strings.
    ///
    /// `columns` is a list of 1-D numpy arrays (all the same length).
    /// `dtypes` is a list of strings matching each column: `"f64"`, `"f32"`, `"u64"`, or `"i64"`.
    /// This is significantly faster than calling `write_record` in a loop.
    fn write_columns(&mut self, _py: Python<'_>, group_id: &str, columns: Vec<Bound<'_, PyAny>>, dtypes: Vec<String>) -> PyResult<()> {
        if columns.len() != dtypes.len() {
            return Err(MdfException::new_err(format!(
                "columns length ({}) must match dtypes length ({})",
                columns.len(), dtypes.len()
            )));
        }

        if let Some(ref mut writer) = self.writer {
            let cg_id = self.channel_groups.get(group_id)
                .ok_or_else(|| MdfException::new_err("Channel group not found"))?
                .clone();

            // We need to keep the extracted arrays alive for the duration of the call.
            // Use an enum to hold each typed array so lifetimes work out.
            enum OwnedArray<'py> {
                F64(PyReadonlyArray1<'py, f64>),
                F32(PyReadonlyArray1<'py, f32>),
                U64(PyReadonlyArray1<'py, u64>),
                I64(PyReadonlyArray1<'py, i64>),
            }

            let owned: Vec<OwnedArray<'_>> = columns.iter().zip(dtypes.iter())
                .map(|(col, dtype)| match dtype.as_str() {
                    "f64" => col.extract::<PyReadonlyArray1<f64>>().map(OwnedArray::F64),
                    "f32" => col.extract::<PyReadonlyArray1<f32>>().map(OwnedArray::F32),
                    "u64" => col.extract::<PyReadonlyArray1<u64>>().map(OwnedArray::U64),
                    "i64" => col.extract::<PyReadonlyArray1<i64>>().map(OwnedArray::I64),
                    other => Err(MdfException::new_err(format!(
                        "Unknown dtype '{}'; expected one of: f64, f32, u64, i64", other
                    ))),
                })
                .collect::<PyResult<Vec<_>>>()?;

            let column_data: Vec<ColumnData<'_>> = owned.iter()
                .map(|arr| match arr {
                    OwnedArray::F64(a) => a.as_slice()
                        .map(ColumnData::F64)
                        .map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
                    OwnedArray::F32(a) => a.as_slice()
                        .map(ColumnData::F32)
                        .map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
                    OwnedArray::U64(a) => a.as_slice()
                        .map(ColumnData::U64)
                        .map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
                    OwnedArray::I64(a) => a.as_slice()
                        .map(ColumnData::I64)
                        .map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
                })
                .collect::<PyResult<Vec<_>>>()?;

            writer.write_columns(&cg_id, &column_data)?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer has been finalized"))
        }
    }

    /// Finalize the writer and close the file
    fn finalize(&mut self) -> PyResult<()> {
        if let Some(writer) = self.writer.take() {
            writer.finalize()?;
            Ok(())
        } else {
            Err(MdfException::new_err("Writer already finalized"))
        }
    }
}

// Python wrapper for MdfIndex
#[pyclass]
pub struct PyMdfIndex {
    index: MdfIndex,
}

#[pymethods]
impl PyMdfIndex {
    /// Create index from MDF file
    #[staticmethod]
    fn from_file(path: &str) -> PyResult<Self> {
        let index = MdfIndex::from_file(path)?;
        Ok(PyMdfIndex { index })
    }
    
    /// Load index from JSON file
    #[staticmethod]
    fn load_from_file(path: &str) -> PyResult<Self> {
        let index = MdfIndex::load_from_file(path)?;
        Ok(PyMdfIndex { index })
    }
    
    /// Save index to JSON file
    fn save_to_file(&self, path: &str) -> PyResult<()> {
        self.index.save_to_file(path)?;
        Ok(())
    }
    
    /// List all channel groups
    fn list_channel_groups(&self) -> Vec<(usize, String, usize)> {
        self.index.list_channel_groups()
            .into_iter()
            .map(|(idx, name, count)| (idx, name.to_string(), count))
            .collect()
    }
    
    /// List channels in a specific group
    fn list_channels(&self, group_index: usize) -> Option<Vec<(usize, String, PyDataType)>> {
        self.index.list_channels(group_index)
            .map(|channels| {
                channels.into_iter()
                    .map(|(idx, name, data_type)| (idx, name.to_string(), PyDataType::from(data_type)))
                    .collect()
            })
    }
    
    /// Read channel values by index.
    ///
    /// Returns an error if indices are invalid.
    /// Option in Vec represents invalid/missing samples: None = invalid, Some = valid value.
    /// Returns a list of native Python values (float, int, str, bytes).
    fn read_channel_values(&self, py: Python, group_index: usize, channel_index: usize, file_path: &str) -> PyResult<Vec<Option<PyObject>>> {
        let mut reader = FileRangeReader::new(file_path)?;
        let values = self.index.read_channel_values(group_index, channel_index, &mut reader)?;
        Ok(values.into_iter().map(|opt_val| {
            opt_val.map(|dv| decoded_value_to_pyobject(dv, py))
        }).collect())
    }
    
    /// Read channel values by name.
    ///
    /// Returns an error if the channel is not found.
    /// Option in Vec represents invalid/missing samples: None = invalid, Some = valid value.
    /// Returns a list of native Python values (float, int, str, bytes).
    fn read_channel_values_by_name(&self, py: Python, channel_name: &str, file_path: &str) -> PyResult<Vec<Option<PyObject>>> {
        let mut reader = FileRangeReader::new(file_path)?;
        let values = self.index.read_channel_values_by_name(channel_name, &mut reader)?;
        Ok(values.into_iter().map(|opt_val| {
            opt_val.map(|dv| decoded_value_to_pyobject(dv, py))
        }).collect())
    }
    
    /// Fast path: read channel values as f64 list by index.
    ///
    /// Significantly faster than `read_channel_values` for numeric channels.
    /// Uses zero-copy mmap access and bypasses DecodedValue enum boxing.
    /// Invalid samples are represented as float('nan').
    fn read_channel_values_as_f64(&self, group_index: usize, channel_index: usize, file_path: &str) -> PyResult<Vec<f64>> {
        let file = std::fs::File::open(file_path).map_err(|e| MdfError::IOError(e))?;
        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|e| MdfError::IOError(e))?;
        Ok(self.index.read_channel_values_from_slice_as_f64(group_index, channel_index, &mmap)?)
    }

    /// Fast path: read channel values as f64 list by name.
    ///
    /// Significantly faster than `read_channel_values_by_name` for numeric channels.
    /// Uses zero-copy mmap access and bypasses DecodedValue enum boxing.
    /// Invalid samples are represented as float('nan').
    fn read_channel_values_by_name_as_f64(&self, channel_name: &str, file_path: &str) -> PyResult<Vec<f64>> {
        let (group_index, channel_index) = self.index.find_channel_by_name_global(channel_name)
            .ok_or_else(|| MdfError::BlockSerializationError(
                format!("Channel '{}' not found", channel_name)
            ))?;
        let file = std::fs::File::open(file_path).map_err(|e| MdfError::IOError(e))?;
        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|e| MdfError::IOError(e))?;
        Ok(self.index.read_channel_values_from_slice_as_f64(group_index, channel_index, &mmap)?)
    }

    /// Find channel by name
    fn find_channel_by_name(&self, channel_name: &str) -> Option<(usize, usize)> {
        self.index.find_channel_by_name_global(channel_name)
    }
    
    /// Get byte ranges for a channel
    fn get_channel_byte_ranges(&self, group_index: usize, channel_index: usize) -> PyResult<Vec<(u64, u64)>> {
        Ok(self.index.get_channel_byte_ranges(group_index, channel_index)?)
    }
    
    /// Get byte ranges for a specific record range of a channel
    fn get_channel_byte_ranges_for_records(&self, group_index: usize, channel_index: usize, start_record: u64, record_count: u64) -> PyResult<Vec<(u64, u64)>> {
        Ok(self.index.get_channel_byte_ranges_for_records(group_index, channel_index, start_record, record_count)?)
    }
    
    /// Get byte range summary for a channel (total bytes, number of ranges)
    fn get_channel_byte_summary(&self, group_index: usize, channel_index: usize) -> PyResult<(u64, usize)> {
        Ok(self.index.get_channel_byte_summary(group_index, channel_index)?)
    }
    
    /// Get byte ranges for a channel by name
    fn get_channel_byte_ranges_by_name(&self, channel_name: &str) -> PyResult<Vec<(u64, u64)>> {
        Ok(self.index.get_channel_byte_ranges_by_name(channel_name)?)
    }
    
    /// Get channel info by name (returns group_index, channel_index, and channel info)
    fn get_channel_info_by_name(&self, channel_name: &str) -> Option<(usize, usize, PyChannelInfo)> {
        self.index.get_channel_info_by_name(channel_name).map(|(group_idx, channel_idx, channel)| {
            let info = PyChannelInfo {
                name: channel.name.clone(),
                unit: channel.unit.clone(),
                comment: None, // IndexedChannel doesn't store comment
                data_type: PyDataType::from(&channel.data_type),
                bit_count: channel.bit_count,
            };
            (group_idx, channel_idx, info)
        })
    }
    
    /// Find all channels with a given name across all groups
    fn find_all_channels_by_name(&self, channel_name: &str) -> Vec<(usize, usize)> {
        self.index.find_all_channels_by_name(channel_name)
    }
    
    /// Get file size from the index
    fn get_file_size(&self) -> u64 {
        self.index.file_size
    }
    
    /// Check if the index has resolved conversion data (enhanced index)
    fn has_resolved_conversions(&self) -> bool {
        // Check if any channel has resolved conversion data
        for group in &self.index.channel_groups {
            for channel in &group.channels {
                if let Some(conversion) = &channel.conversion {
                    if conversion.resolved_texts.is_some() || conversion.resolved_conversions.is_some() {
                        return true;
                    }
                }
            }
        }
        false
    }
    
    /// Get conversion info for a specific channel
    fn get_conversion_info(&self, group_index: usize, channel_index: usize) -> PyResult<Option<HashMap<String, PyObject>>> {
        use pyo3::Python;

        let group = self.index.channel_groups.get(group_index)
            .ok_or_else(|| MdfException::new_err("Invalid group index"))?;

        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfException::new_err("Invalid channel index"))?;

        if let Some(conversion) = &channel.conversion {
            Python::with_gil(|py| {
                let mut info = HashMap::new();

                info.insert("conversion_type".to_string(), format!("{:?}", conversion.cc_type).to_object(py));
                info.insert("precision".to_string(), conversion.cc_precision.to_object(py));
                info.insert("flags".to_string(), conversion.cc_flags.to_object(py));
                info.insert("values_count".to_string(), conversion.cc_val_count.to_object(py));
                info.insert("values".to_string(), conversion.cc_val.to_object(py));

                // Include resolved data info if available
                if let Some(resolved_texts) = &conversion.resolved_texts {
                    let texts: HashMap<usize, String> = resolved_texts.clone();
                    info.insert("resolved_texts".to_string(), texts.to_object(py));
                }

                if let Some(_) = &conversion.resolved_conversions {
                    info.insert("has_resolved_conversions".to_string(), true.to_object(py));
                }

                if let Some(formula) = &conversion.formula {
                    info.insert("formula".to_string(), formula.to_object(py));
                }

                Ok(Some(info))
            })
        } else {
            Ok(None)
        }
    }

    /// Read channel values by channel group name and channel name.
    ///
    /// This method looks up the channel group by name first, then finds the channel
    /// within that specific group. Returns an error if either the group or channel is not found.
    /// Option in Vec represents invalid/missing samples: None = invalid, Some = valid value.
    /// Returns a list of native Python values (float, int, str, bytes).
    fn read_channel_values_by_group_and_name(&self, py: Python, group_name: &str, channel_name: &str, file_path: &str) -> PyResult<Vec<Option<PyObject>>> {
        // Find the group by name
        let mut group_index = None;
        for (idx, group) in self.index.channel_groups.iter().enumerate() {
            if let Some(ref gname) = group.name {
                if gname == group_name {
                    group_index = Some(idx);
                    break;
                }
            }
        }

        let group_idx = group_index.ok_or_else(||
            MdfException::new_err(format!("Channel group '{}' not found", group_name))
        )?;

        // Find the channel by name within the group
        let group = &self.index.channel_groups[group_idx];
        let mut channel_index = None;
        for (idx, channel) in group.channels.iter().enumerate() {
            if let Some(ref cname) = channel.name {
                if cname == channel_name {
                    channel_index = Some(idx);
                    break;
                }
            }
        }

        let channel_idx = channel_index.ok_or_else(||
            MdfException::new_err(format!("Channel '{}' not found in group '{}'", channel_name, group_name))
        )?;

        // Read the channel values using the found indices
        let mut reader = FileRangeReader::new(file_path)?;
        let values = self.index.read_channel_values(group_idx, channel_idx, &mut reader)?;
        Ok(values.into_iter().map(|opt_val| {
            opt_val.map(|dv| decoded_value_to_pyobject(dv, py))
        }).collect())
    }

    /// Read channel data as a pandas Series with time/master channel as DatetimeIndex.
    ///
    /// This method reads a channel's values from the index and returns them as a pandas Series
    /// with the time/master channel values converted to absolute timestamps as a DatetimeIndex.
    /// The timestamps are created by adding the relative time values to the MDF start time
    /// stored in the index. If no master channel is found, or if the queried channel IS the
    /// master channel, a default integer index is used. If the MDF file has no start time,
    /// falls back to numeric index.
    ///
    /// Requires pandas to be installed.
    ///
    /// # Arguments
    /// * `channel_name` - Name of the channel to read
    /// * `file_path` - Path to the MDF file
    ///
    /// # Returns
    /// Returns an error if the channel is not found, otherwise returns a pandas Series.
    ///
    /// # Errors
    /// Returns an error if:
    /// - pandas is not installed
    /// - the channel is not found
    /// - the master channel has a different number of values than the data channel
    fn read_channel_as_series(&self, py: Python, channel_name: &str, file_path: &str) -> PyResult<PyObject> {
        // Check if pandas is available
        let pd = check_pandas_available(py)?;

        // Get the MDF start time from the index for datetime conversion
        let start_time_ns = self.index.start_time_ns;

        // Find the channel
        let (group_idx, channel_idx) = self.find_channel_by_name(channel_name)
            .ok_or_else(|| MdfException::new_err(format!("Channel '{}' not found", channel_name)))?;

        // Read the channel values
        let mut reader = FileRangeReader::new(file_path)?;
        let values = self.index.read_channel_values(group_idx, channel_idx, &mut reader)?;
        let py_values: Vec<PyObject> = values.into_iter().map(|opt_val| {
            opt_val.map(|dv| decoded_value_to_pyobject(dv, py)).unwrap_or_else(|| py.None())
        }).collect();

        // Find the master/time channel for this group
        let group = &self.index.channel_groups[group_idx];
        let index: PyObject = if let Some(master_idx) = find_master_channel_indexed(&group.channels) {
            if master_idx != channel_idx {
                // Use the master channel values as index
                let master_values = self.index.read_channel_values(group_idx, master_idx, &mut reader)?;
                let py_master_values: Vec<PyObject> = master_values.into_iter().map(|opt_val| {
                    opt_val.map(|dv| decoded_value_to_pyobject(dv, py)).unwrap_or_else(|| py.None())
                }).collect();

                // Validate that lengths match
                if py_master_values.len() != py_values.len() {
                    return Err(MdfException::new_err(format!(
                        "Master channel length ({}) does not match data channel length ({}) for channel '{}'",
                        py_master_values.len(), py_values.len(), channel_name
                    )));
                }

                // Try to convert to DatetimeIndex if we have a start time
                if let Some(start_ns) = start_time_ns {
                    // Attempt to create DatetimeIndex from absolute timestamps
                    match create_datetime_index(py, &pd, &py_master_values, start_ns) {
                        Ok(datetime_index) => datetime_index,
                        Err(_) => {
                            // Fall back to numeric index if datetime conversion fails
                            py_master_values.to_object(py)
                        }
                    }
                } else {
                    // No start time, use numeric index
                    py_master_values.to_object(py)
                }
            } else {
                // This channel IS the master channel, use default index
                py.None()
            }
        } else {
            // No master channel found, use default index
            py.None()
        };

        // Create pandas Series
        let series_class = pd.getattr(py, "Series")?;
        let series = if index.is_none(py) {
            // No index specified, pandas will use default integer index
            series_class.call1(py, (py_values,))?
        } else {
            // Use the master channel values as index
            series_class.call(py, (py_values,), Some([("index", index)].into_py_dict(py)))?
        };

        // Set the series name to the channel name
        series.setattr(py, "name", channel_name)?;

        Ok(series)
    }
}

// ---------------------------------------------------------------------------
// Block layout visualization
// ---------------------------------------------------------------------------

/// A named link inside a block (wraps [`LinkInfo`]).
#[pyclass]
#[derive(Clone)]
pub struct PyLinkInfo {
    #[pyo3(get)]
    pub name: String,
    #[pyo3(get)]
    pub target: u64,
    #[pyo3(get)]
    pub target_type: Option<String>,
}

#[pymethods]
impl PyLinkInfo {
    fn __repr__(&self) -> String {
        if self.target == 0 {
            format!("Link({} -> null)", self.name)
        } else {
            format!(
                "Link({} -> 0x{:010x} [{}])",
                self.name,
                self.target,
                self.target_type.as_deref().unwrap_or("?")
            )
        }
    }
}

impl From<LinkInfo> for PyLinkInfo {
    fn from(l: LinkInfo) -> Self {
        PyLinkInfo {
            name: l.name,
            target: l.target,
            target_type: l.target_type,
        }
    }
}

/// A block visited while walking the file (wraps [`BlockInfo`]).
#[pyclass]
#[derive(Clone)]
pub struct PyBlockInfo {
    #[pyo3(get)]
    pub offset: u64,
    #[pyo3(get)]
    pub end_offset: u64,
    #[pyo3(get)]
    pub size: u64,
    #[pyo3(get)]
    pub block_type: String,
    #[pyo3(get)]
    pub description: String,
    #[pyo3(get)]
    pub links: Vec<PyLinkInfo>,
    #[pyo3(get)]
    pub extra: Option<String>,
}

#[pymethods]
impl PyBlockInfo {
    fn __repr__(&self) -> String {
        format!(
            "Block({} @ 0x{:010x}..0x{:010x}, size={}, {})",
            self.block_type, self.offset, self.end_offset, self.size, self.description
        )
    }
}

impl From<BlockInfo> for PyBlockInfo {
    fn from(b: BlockInfo) -> Self {
        PyBlockInfo {
            offset: b.offset,
            end_offset: b.end_offset,
            size: b.size,
            block_type: b.block_type,
            description: b.description,
            links: b.links.into_iter().map(Into::into).collect(),
            extra: b.extra,
        }
    }
}

/// An unreferenced range of bytes in the file (wraps [`GapInfo`]).
#[pyclass]
#[derive(Clone)]
pub struct PyGapInfo {
    #[pyo3(get)]
    pub start: u64,
    #[pyo3(get)]
    pub end: u64,
    #[pyo3(get)]
    pub size: u64,
}

#[pymethods]
impl PyGapInfo {
    fn __repr__(&self) -> String {
        format!(
            "Gap(0x{:010x}..0x{:010x}, size={})",
            self.start, self.end, self.size
        )
    }
}

impl From<GapInfo> for PyGapInfo {
    fn from(g: GapInfo) -> Self {
        PyGapInfo {
            start: g.start,
            end: g.end,
            size: g.size,
        }
    }
}

/// Full layout of an MDF file (wraps [`FileLayout`]).
#[pyclass]
pub struct PyFileLayout {
    pub(crate) inner: FileLayout,
}

#[pymethods]
impl PyFileLayout {
    /// Build a layout by parsing an MDF file on disk.
    #[staticmethod]
    fn from_file(path: &str) -> PyResult<Self> {
        let inner = FileLayout::from_file(path)?;
        Ok(PyFileLayout { inner })
    }

    /// Total size of the file in bytes.
    #[getter]
    fn file_size(&self) -> u64 {
        self.inner.file_size
    }

    /// List of all discovered blocks, sorted by offset.
    #[getter]
    fn blocks(&self) -> Vec<PyBlockInfo> {
        self.inner.blocks.iter().cloned().map(Into::into).collect()
    }

    /// Byte ranges not covered by any visited block.
    #[getter]
    fn gaps(&self) -> Vec<PyGapInfo> {
        self.inner.gaps.iter().cloned().map(Into::into).collect()
    }

    /// Render the layout as a flat, sorted listing with link details.
    fn to_text(&self) -> String {
        self.inner.to_text()
    }

    /// Render the link graph as an indented tree starting at the ID block.
    fn to_tree(&self) -> String {
        self.inner.to_tree()
    }

    /// Serialize the layout to a pretty JSON string.
    fn to_json(&self) -> PyResult<String> {
        Ok(self.inner.to_json()?)
    }

    /// Write the flat text listing to `path`.
    fn write_text_to_file(&self, path: &str) -> PyResult<()> {
        self.inner.write_text_to_file(path)?;
        Ok(())
    }

    /// Write the indented tree view to `path`.
    fn write_tree_to_file(&self, path: &str) -> PyResult<()> {
        self.inner.write_tree_to_file(path)?;
        Ok(())
    }

    /// Write the JSON representation to `path`.
    fn write_json_to_file(&self, path: &str) -> PyResult<()> {
        self.inner.write_json_to_file(path)?;
        Ok(())
    }

    fn __repr__(&self) -> String {
        format!(
            "FileLayout(file_size={}, blocks={}, gaps={})",
            self.inner.file_size,
            self.inner.blocks.len(),
            self.inner.gaps.len()
        )
    }
}

/// Build a [`PyFileLayout`] directly from a file path (free function helper).
#[pyfunction]
fn file_layout_from_file(path: &str) -> PyResult<PyFileLayout> {
    PyFileLayout::from_file(path)
}

/// Cut an MDF file by time, copying only records whose master channel value
/// falls within the inclusive `[start_time, end_time]` window.
///
/// The output preserves fixed-length numeric, string, and byte-array
/// channels, per-record invalidation bytes, and VLSD ("signal-based")
/// channels (a fresh ##SD chain is written for each kept VLSD channel).
/// Per-channel conversion / source / metadata blocks are not re-emitted, so
/// the output channels read as raw values.
///
/// Parameters
/// ----------
/// input_path : str
///     Path to the source MF4 file.
/// output_path : str
///     Destination path for the trimmed file.
/// start_time : float
///     Start of the window in seconds (inclusive).
/// end_time : float
///     End of the window in seconds (inclusive).
#[pyfunction]
#[pyo3(signature = (input_path, output_path, start_time, end_time))]
fn cut_mdf_by_time(
    input_path: &str,
    output_path: &str,
    start_time: f64,
    end_time: f64,
) -> PyResult<()> {
    crate::cut::cut_mdf_by_time(input_path, output_path, start_time, end_time)?;
    Ok(())
}

/// Convert a Python `datetime`, an ISO 8601 string, or a numeric UNIX
/// timestamp (seconds, with fractional part) into UNIX-epoch nanoseconds.
fn coerce_to_unix_ns(py: Python<'_>, value: &Bound<'_, PyAny>) -> PyResult<i64> {
    let datetime_mod = py.import_bound("datetime")?;
    let datetime_cls = datetime_mod.getattr("datetime")?;

    // datetime.datetime — call .timestamp() to get seconds since epoch.
    if value.is_instance(&datetime_cls)? {
        let dt = ensure_utc_aware(py, value, &datetime_mod)?;
        let ts: f64 = dt.call_method0("timestamp")?.extract()?;
        return Ok((ts * 1.0e9).round() as i64);
    }

    // String: try datetime.fromisoformat (Python ≥ 3.7).
    if let Ok(s) = value.extract::<String>() {
        // datetime.fromisoformat in Python 3.11+ accepts trailing 'Z'; for
        // earlier versions we normalise it to '+00:00' before parsing.
        let normalized = if s.ends_with('Z') || s.ends_with('z') {
            format!("{}+00:00", &s[..s.len() - 1])
        } else {
            s
        };
        let parsed = datetime_cls.call_method1("fromisoformat", (normalized,))?;
        let dt = ensure_utc_aware(py, &parsed, &datetime_mod)?;
        let ts: f64 = dt.call_method0("timestamp")?.extract()?;
        return Ok((ts * 1.0e9).round() as i64);
    }

    // Numeric timestamp (int or float seconds since epoch). Tried last so a
    // `datetime` (which is also coercible to a number via __float__ in some
    // shims) hits the dedicated path above.
    if let Ok(secs) = value.extract::<f64>() {
        if !secs.is_finite() {
            return Err(MdfException::new_err("timestamp is not a finite number"));
        }
        return Ok((secs * 1.0e9).round() as i64);
    }

    Err(MdfException::new_err(
        "expected datetime.datetime, ISO 8601 string, or numeric UNIX timestamp",
    ))
}

/// If `dt` is timezone-naive, attach UTC; otherwise return it unchanged.
fn ensure_utc_aware<'py>(
    py: Python<'py>,
    dt: &Bound<'py, PyAny>,
    datetime_mod: &Bound<'py, PyModule>,
) -> PyResult<Bound<'py, PyAny>> {
    let tzinfo = dt.getattr("tzinfo")?;
    if !tzinfo.is_none() {
        return Ok(dt.clone());
    }
    let timezone = datetime_mod.getattr("timezone")?;
    let utc = timezone.getattr("utc")?;
    let kwargs = [("tzinfo", utc)].into_py_dict_bound(py);
    dt.call_method("replace", (), Some(&kwargs))
}

/// Cut an MDF file by absolute UTC time. Accepts ISO 8601 strings (e.g.
/// `"2024-01-15T12:34:56Z"`), `datetime.datetime` objects (naive values are
/// assumed to be UTC), or numeric UNIX timestamps in seconds.
///
/// The window is inclusive on both ends. The source file must record a
/// non-zero `HD.abs_time` (set by the writer / asammdf when creating the
/// file) — without it the relative offset cannot be computed and an
/// `MdfException` is raised.
///
/// Other behaviour matches [`cut_mdf_by_time`]: VLSD payloads, byte-array
/// channels, and per-record invalidation bytes are preserved verbatim.
#[pyfunction]
#[pyo3(signature = (input_path, output_path, start_utc, end_utc))]
fn cut_mdf_by_utc(
    py: Python<'_>,
    input_path: &str,
    output_path: &str,
    start_utc: &Bound<'_, PyAny>,
    end_utc: &Bound<'_, PyAny>,
) -> PyResult<()> {
    let start_ns = coerce_to_unix_ns(py, start_utc)?;
    let end_ns = coerce_to_unix_ns(py, end_utc)?;
    crate::cut::cut_mdf_by_utc_ns(input_path, output_path, start_ns, end_ns)?;
    Ok(())
}

// Helper functions

/// Create a float decoded value
#[pyfunction]
fn create_float_value(value: f64) -> PyDecodedValue {
    PyDecodedValue::Float { value }
}

/// Create an unsigned integer decoded value  
#[pyfunction]
fn create_uint_value(value: u64) -> PyDecodedValue {
    PyDecodedValue::UnsignedInteger { value }
}

/// Create a signed integer decoded value
#[pyfunction]
fn create_int_value(value: i64) -> PyDecodedValue {
    PyDecodedValue::SignedInteger { value }
}

/// Create a string decoded value
#[pyfunction]
fn create_string_value(value: String) -> PyDecodedValue {
    PyDecodedValue::String { value }
}

/// Create data types
#[pyfunction]
fn create_data_type_uint_le() -> PyDataType {
    PyDataType { name: "UnsignedIntegerLE".to_string(), value: 0 }
}

#[pyfunction]
fn create_data_type_float_le() -> PyDataType {
    PyDataType { name: "FloatLE".to_string(), value: 4 }
}

#[pyfunction]
fn create_data_type_string_utf8() -> PyDataType {
    PyDataType { name: "StringUtf8".to_string(), value: 7 }
}

/// The main Python module initialization function
pub fn init_mf4_rs_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add("MdfException", m.py().get_type_bound::<MdfException>())?;
    
    // Classes
    m.add_class::<PyMDF>()?;
    m.add_class::<PyMdfWriter>()?;
    m.add_class::<PyMdfIndex>()?;
    m.add_class::<PyChannelGroupInfo>()?;
    m.add_class::<PyChannelInfo>()?;
    m.add_class::<PyDecodedValue>()?;
    m.add_class::<PyDataType>()?;
    m.add_class::<PyFileLayout>()?;
    m.add_class::<PyBlockInfo>()?;
    m.add_class::<PyLinkInfo>()?;
    m.add_class::<PyGapInfo>()?;

    // Helper functions
    m.add_function(wrap_pyfunction!(create_float_value, m)?)?;
    m.add_function(wrap_pyfunction!(create_uint_value, m)?)?;
    m.add_function(wrap_pyfunction!(create_int_value, m)?)?;
    m.add_function(wrap_pyfunction!(create_string_value, m)?)?;
    m.add_function(wrap_pyfunction!(create_data_type_uint_le, m)?)?;
    m.add_function(wrap_pyfunction!(create_data_type_float_le, m)?)?;
    m.add_function(wrap_pyfunction!(create_data_type_string_utf8, m)?)?;
    m.add_function(wrap_pyfunction!(file_layout_from_file, m)?)?;
    m.add_function(wrap_pyfunction!(cut_mdf_by_time, m)?)?;
    m.add_function(wrap_pyfunction!(cut_mdf_by_utc, m)?)?;

    Ok(())
}