xportrs 0.0.8

CDISC-compliant XPT file generation and parsing library for Rust
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
//! Domain dataset representation.
//!
//! This module provides the [`Dataset`] struct which represents a CDISC
//! domain dataset (table) in a columnar format.

use std::fmt;
use std::ops::Index;

use chrono::{NaiveDate, NaiveDateTime, NaiveTime};

use crate::error::{Error, Result};

use super::format::{Format, FormatParseError};
use super::iter::{ColumnNames, IntoIter, Iter, IterMut};
use super::newtypes::{DomainCode, Label, VariableName};

/// A CDISC domain dataset in columnar format.
///
/// This is the primary data structure for representing tables in xportrs.
/// Contains a [`DomainCode`], optional [`Label`], and a collection of [`Column`] items.
///
/// # Invariants
///
/// - All [`Column`] items must have exactly `nrows` elements.
/// - [`DomainCode`] should follow CDISC naming conventions (typically 2-8 characters).
///
/// # Example
///
/// ```
/// use xportrs::{Dataset, Column, ColumnData, DomainCode};
///
/// let dataset = Dataset::new(
///     DomainCode::new("AE"),
///     vec![
///         Column::new("USUBJID", ColumnData::String(vec![Some("01-001".into())])),
///         Column::new("AESER", ColumnData::String(vec![Some("Y".into())])),
///     ],
/// ).expect("valid dataset");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Dataset {
    /// The domain code (e.g., "AE", "DM", "LB").
    ///
    /// This is typically 2 characters but can be up to 8 bytes in XPT v5.
    domain_code: DomainCode,

    /// An optional label describing the dataset.
    ///
    /// Limited to 40 bytes in XPT v5.
    dataset_label: Option<Label>,

    /// The columns (variables) in the dataset.
    columns: Vec<Column>,

    /// The number of rows (observations) in the dataset.
    nrows: usize,
}

impl Dataset {
    /// Creates a new domain dataset.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ColumnLengthMismatch`] if any [`Column`] has a different length than the others.
    #[must_use = "this returns a Result that should be handled"]
    pub fn new(domain_code: impl Into<DomainCode>, columns: Vec<Column>) -> Result<Self> {
        let nrows = columns.first().map_or(0, Column::len);

        // Validate all columns have the same length
        for col in &columns {
            if col.len() != nrows {
                return Err(Error::ColumnLengthMismatch {
                    column_name: col.name().to_string(),
                    actual: col.len(),
                    expected: nrows,
                });
            }
        }

        Ok(Self {
            domain_code: domain_code.into(),
            dataset_label: None,
            columns,
            nrows,
        })
    }

    /// Creates a new domain dataset with a label.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ColumnLengthMismatch`] if any [`Column`] has a different length than the others.
    pub fn with_label(
        domain_code: impl Into<DomainCode>,
        dataset_label: impl Into<Label>,
        columns: Vec<Column>,
    ) -> Result<Self> {
        let mut dataset = Self::new(domain_code, columns)?;
        dataset.dataset_label = Some(dataset_label.into());
        Ok(dataset)
    }

    /// Returns the number of columns (variables) in the dataset.
    #[must_use]
    pub fn ncols(&self) -> usize {
        self.columns.len()
    }

    /// Returns `true` if the dataset has no rows.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.nrows == 0
    }

    /// Returns the domain code as a string slice.
    #[must_use]
    pub fn domain_code(&self) -> &str {
        self.domain_code.as_str()
    }

    /// Returns the dataset label, if any.
    #[must_use]
    pub fn dataset_label(&self) -> Option<&str> {
        self.dataset_label.as_ref().map(Label::as_str)
    }

    /// Sets the dataset label.
    ///
    /// This is useful when you need to conditionally set a label.
    ///
    /// # Example
    ///
    /// ```
    /// use xportrs::{Column, ColumnData, Dataset};
    ///
    /// let mut dataset = Dataset::new("AE", vec![
    ///     Column::new("AESEQ", ColumnData::F64(vec![Some(1.0)])),
    /// ])?;
    ///
    /// // Conditionally set label
    /// let label: Option<&str> = Some("Adverse Events");
    /// if let Some(lbl) = label {
    ///     dataset.set_label(lbl);
    /// }
    /// # Ok::<(), xportrs::Error>(())
    /// ```
    pub fn set_label(&mut self, label: impl Into<Label>) {
        self.dataset_label = Some(label.into());
    }

    /// Returns a reference to the columns.
    #[must_use]
    pub fn columns(&self) -> &[Column] {
        &self.columns
    }

    /// Returns the number of rows (observations) in the dataset.
    #[must_use]
    pub fn nrows(&self) -> usize {
        self.nrows
    }

    /// Returns an [`Iter`] over references to the columns.
    #[must_use]
    pub fn iter(&self) -> Iter<'_> {
        Iter::new(&self.columns)
    }

    /// Returns an [`IterMut`] over the columns.
    #[must_use]
    pub fn iter_mut(&mut self) -> IterMut<'_> {
        IterMut::new(&mut self.columns)
    }

    /// Returns a [`ColumnNames`] iterator over the column names.
    #[must_use]
    pub fn column_names(&self) -> ColumnNames<'_> {
        ColumnNames::new(&self.columns)
    }

    /// Finds a [`Column`] by name.
    #[must_use]
    pub fn column(&self, name: &str) -> Option<&Column> {
        self.columns.iter().find(|c| c.name() == name)
    }
}

impl IntoIterator for Dataset {
    type Item = Column;
    type IntoIter = IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self.columns)
    }
}

impl<'a> IntoIterator for &'a Dataset {
    type Item = &'a Column;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &'a mut Dataset {
    type Item = &'a mut Column;
    type IntoIter = IterMut<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl Index<usize> for Dataset {
    type Output = Column;

    fn index(&self, index: usize) -> &Self::Output {
        &self.columns[index]
    }
}

impl Index<&str> for Dataset {
    type Output = Column;

    /// Indexes the dataset by column name.
    ///
    /// # Panics
    ///
    /// Panics if no column with the given name exists.
    fn index(&self, name: &str) -> &Self::Output {
        self.columns
            .iter()
            .find(|c| c.name() == name)
            .unwrap_or_else(|| panic!("no column named '{}'", name))
    }
}

impl Extend<Column> for Dataset {
    /// Extends the dataset with columns from an iterator.
    ///
    /// # Panics
    ///
    /// Panics if any column has a different length than the existing dataset.
    /// If the dataset is empty (nrows == 0), the first column's length becomes
    /// the new nrows.
    fn extend<T: IntoIterator<Item = Column>>(&mut self, iter: T) {
        for col in iter {
            if self.nrows == 0 && self.columns.is_empty() {
                // Empty dataset - take length from first column
                self.nrows = col.len();
            } else if col.len() != self.nrows {
                panic!(
                    "column '{}' has length {} but dataset has {} rows",
                    col.name(),
                    col.len(),
                    self.nrows
                );
            }
            self.columns.push(col);
        }
    }
}

impl fmt::Display for Dataset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} [{} rows × {} cols]",
            self.domain_code.as_str(),
            self.nrows,
            self.columns.len()
        )
    }
}

/// A single column (variable) in a domain dataset.
///
/// Each column has a [`VariableName`], optional [`VariableRole`], and typed [`ColumnData`].
/// Columns can also have metadata: label, format, informat, and explicit length.
///
/// # CDISC/FDA Compliance
///
/// For FDA regulatory submissions, variable labels are **recommended** to help
/// reviewers understand the data. Labels are limited to 40 bytes in XPT v5.
///
/// Formats control how numeric values are displayed (e.g., `DATE9.`, `8.2`).
/// While FDA recommends avoiding custom SAS formats, standard formats should
/// still have their metadata correctly populated.
///
/// # Example
///
/// ```
/// use xportrs::{Column, ColumnData, VariableRole, Format};
///
/// // Create a simple string column
/// let col = Column::new("USUBJID", ColumnData::String(vec![
///     Some("01-001".into()),
///     Some("01-002".into()),
/// ]));
/// println!("{}", col);  // Prints: USUBJID (String)
///
/// // Create a column with full CDISC metadata
/// let col = Column::new("AESTDTC", ColumnData::String(vec![Some("2024-01-15".into())]))
///     .with_label("Start Date/Time of Adverse Event")
///     .with_format(Format::character(19));
///
/// // Create a column with a CDISC role
/// let col = Column::with_role(
///     "AESEQ",
///     VariableRole::Identifier,
///     ColumnData::I64(vec![Some(1), Some(2)]),
/// );
/// if let Some(role) = col.role() {
///     println!("{} is an {} variable", col.name(), role);
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Column {
    /// The variable name.
    ///
    /// Limited to 8 bytes in XPT v5.
    name: VariableName,

    /// The CDISC [`VariableRole`], if applicable.
    role: Option<VariableRole>,

    /// The [`ColumnData`] containing the typed values.
    data: ColumnData,

    /// The variable label (max 40 bytes in XPT v5).
    ///
    /// Labels are recommended for FDA submissions to help reviewers
    /// understand the data. Missing labels will trigger a validation warning.
    label: Option<Label>,

    /// The SAS format (controls display output).
    ///
    /// Examples: `DATE9.`, `8.2`, `$CHAR200.`
    format: Option<Format>,

    /// The SAS informat (controls data input).
    ///
    /// Typically only relevant when reading data from other sources.
    informat: Option<Format>,

    /// Explicit character length override.
    ///
    /// If not set, length is derived from the maximum value length in the data.
    /// Only applicable to character columns.
    length: Option<usize>,
}

impl Column {
    /// Creates a new column with the given name and data.
    #[must_use]
    pub fn new(name: impl Into<VariableName>, data: ColumnData) -> Self {
        Self {
            name: name.into(),
            role: None,
            data,
            label: None,
            format: None,
            informat: None,
            length: None,
        }
    }

    /// Creates a new column with the given name, role, and data.
    #[must_use]
    pub fn with_role(name: impl Into<VariableName>, role: VariableRole, data: ColumnData) -> Self {
        Self {
            name: name.into(),
            role: Some(role),
            data,
            label: None,
            format: None,
            informat: None,
            length: None,
        }
    }

    /// Sets the variable label.
    ///
    /// Labels are limited to 40 bytes in XPT v5 and are **recommended** for
    /// FDA regulatory submissions.
    ///
    /// # Example
    ///
    /// ```
    /// use xportrs::{Column, ColumnData};
    ///
    /// let col = Column::new("USUBJID", ColumnData::String(vec![Some("01-001".into())]))
    ///     .with_label("Unique Subject Identifier");
    ///
    /// assert_eq!(col.label(), Some("Unique Subject Identifier"));
    /// ```
    #[must_use]
    pub fn with_label(mut self, label: impl Into<Label>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets the SAS format.
    ///
    /// Formats control how values are displayed. Common formats include:
    /// - `DATE9.` - Display as date (e.g., "15JAN2024")
    /// - `8.2` - Numeric with 8 width and 2 decimals
    /// - `$CHAR200.` - Character with 200 width
    ///
    /// # Example
    ///
    /// ```
    /// use xportrs::{Column, ColumnData, Format};
    ///
    /// let col = Column::new("AESTDT", ColumnData::F64(vec![Some(23391.0)]))
    ///     .with_format(Format::parse("DATE9.").unwrap());
    ///
    /// assert!(col.format().is_some());
    /// ```
    #[must_use]
    pub fn with_format(mut self, format: Format) -> Self {
        self.format = Some(format);
        self
    }

    /// Sets the SAS format from a format string.
    ///
    /// This is a convenience method that parses the format string.
    ///
    /// # Errors
    ///
    /// Returns [`FormatParseError`] if the format string is invalid.
    ///
    /// # Example
    ///
    /// ```
    /// use xportrs::{Column, ColumnData};
    ///
    /// let col = Column::new("AESTDT", ColumnData::F64(vec![Some(23391.0)]))
    ///     .with_format_str("DATE9.")?;
    ///
    /// assert!(col.format().is_some());
    /// # Ok::<(), xportrs::FormatParseError>(())
    /// ```
    pub fn with_format_str(mut self, format: &str) -> std::result::Result<Self, FormatParseError> {
        self.format = Some(Format::parse(format)?);
        Ok(self)
    }

    /// Sets the SAS informat.
    ///
    /// Informats control how data is read from external sources.
    /// Typically only relevant when reading data.
    #[must_use]
    pub fn with_informat(mut self, informat: Format) -> Self {
        self.informat = Some(informat);
        self
    }

    /// Sets an explicit character length.
    ///
    /// This overrides the default behavior of deriving length from the data.
    /// Only applicable to character columns; ignored for numeric columns.
    ///
    /// # Example
    ///
    /// ```
    /// use xportrs::{Column, ColumnData};
    ///
    /// // Reserve 200 bytes even though data is shorter
    /// let col = Column::new("AETERM", ColumnData::String(vec![Some("HEADACHE".into())]))
    ///     .with_length(200);
    ///
    /// assert_eq!(col.explicit_length(), Some(200));
    /// ```
    #[must_use]
    pub fn with_length(mut self, length: usize) -> Self {
        self.length = Some(length);
        self
    }

    /// Returns the number of elements in the column.
    #[must_use]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the column has no elements.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Returns the column name.
    #[must_use]
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Returns the [`VariableRole`], if any.
    #[must_use]
    pub fn role(&self) -> Option<VariableRole> {
        self.role
    }

    /// Returns the variable label, if any.
    #[must_use]
    pub fn label(&self) -> Option<&str> {
        self.label.as_ref().map(Label::as_str)
    }

    /// Returns the SAS format, if any.
    #[must_use]
    pub fn format(&self) -> Option<&Format> {
        self.format.as_ref()
    }

    /// Returns the SAS informat, if any.
    #[must_use]
    pub fn informat(&self) -> Option<&Format> {
        self.informat.as_ref()
    }

    /// Returns the explicit character length, if any.
    ///
    /// This is the length set via [`Column::with_length`], not the
    /// automatically derived length from the data.
    #[must_use]
    pub fn explicit_length(&self) -> Option<usize> {
        self.length
    }

    /// Returns a reference to the [`ColumnData`].
    #[must_use]
    pub fn data(&self) -> &ColumnData {
        &self.data
    }

    /// Returns `true` if the column contains numeric data (for XPT purposes).
    #[must_use]
    pub fn is_numeric(&self) -> bool {
        self.data.is_numeric()
    }

    /// Returns `true` if the column contains character data (for XPT purposes).
    #[must_use]
    pub fn is_character(&self) -> bool {
        self.data.is_character()
    }
}

impl fmt::Display for Column {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let type_name = match &self.data {
            ColumnData::F64(_) => "F64",
            ColumnData::I64(_) => "I64",
            ColumnData::Bool(_) => "Bool",
            ColumnData::String(_) => "String",
            ColumnData::Bytes(_) => "Bytes",
            ColumnData::Date(_) => "Date",
            ColumnData::DateTime(_) => "DateTime",
            ColumnData::Time(_) => "Time",
        };
        write!(f, "{} ({})", self.name.as_str(), type_name)
    }
}

/// The typed data content of a column.
///
/// XPT v5 only supports two fundamental types: Numeric (8-byte IBM float) and
/// Character (fixed-width byte string). The variants here represent common
/// Rust types that can be converted to these XPT types.
///
/// # Example
///
/// ```
/// use xportrs::ColumnData;
///
/// // Numeric types - None represents missing values
/// let ages = ColumnData::F64(vec![Some(25.0), Some(30.5), None]);
/// println!("{}", ages);  // Prints: F64(3)
///
/// // Convenience: create from plain vectors (all values present)
/// let data: ColumnData = vec![1.0, 2.0, 3.0].into();
/// let data: ColumnData = vec!["Alice", "Bob", "Carol"].into();
///
/// // Check type category
/// if data.is_character() {
///     println!("Character column with {} values", data.len());
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ColumnData {
    /// 64-bit floating-point values.
    ///
    /// Maps directly to XPT Numeric type.
    F64(Vec<Option<f64>>),

    /// 64-bit integer values.
    ///
    /// Converted to XPT Numeric type (as f64) when writing.
    I64(Vec<Option<i64>>),

    /// Boolean values.
    ///
    /// Converted to XPT Numeric type (1.0 or 0.0) when writing.
    Bool(Vec<Option<bool>>),

    /// String values.
    ///
    /// Maps directly to XPT Character type.
    String(Vec<Option<String>>),

    /// Raw byte values.
    ///
    /// Maps to XPT Character type. Strict profiles may forbid this variant.
    Bytes(Vec<Option<Vec<u8>>>),

    /// Date values (without time component).
    ///
    /// Converted to XPT Numeric (SAS date: days since 1960-01-01) when writing,
    /// unless metadata specifies character format.
    Date(Vec<Option<NaiveDate>>),

    /// `DateTime` values.
    ///
    /// Converted to XPT Numeric (SAS datetime: seconds since 1960-01-01 00:00:00)
    /// when writing, unless metadata specifies character format.
    DateTime(Vec<Option<NaiveDateTime>>),

    /// Time values (without date component).
    ///
    /// Converted to XPT Numeric (SAS time: seconds since midnight) when writing,
    /// unless metadata specifies character format.
    Time(Vec<Option<NaiveTime>>),
}

impl ColumnData {
    /// Returns the number of elements in the data.
    #[must_use]
    pub fn len(&self) -> usize {
        match self {
            Self::F64(v) => v.len(),
            Self::I64(v) => v.len(),
            Self::Bool(v) => v.len(),
            Self::String(v) => v.len(),
            Self::Bytes(v) => v.len(),
            Self::Date(v) => v.len(),
            Self::DateTime(v) => v.len(),
            Self::Time(v) => v.len(),
        }
    }

    /// Returns `true` if the data has no elements.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns `true` if this data type maps to XPT Numeric.
    #[must_use]
    pub fn is_numeric(&self) -> bool {
        matches!(
            self,
            Self::F64(_)
                | Self::I64(_)
                | Self::Bool(_)
                | Self::Date(_)
                | Self::DateTime(_)
                | Self::Time(_)
        )
    }

    /// Returns `true` if this data type maps to XPT Character.
    #[must_use]
    pub fn is_character(&self) -> bool {
        matches!(self, Self::String(_) | Self::Bytes(_))
    }
}

impl fmt::Display for ColumnData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (type_name, len) = match self {
            Self::F64(v) => ("F64", v.len()),
            Self::I64(v) => ("I64", v.len()),
            Self::Bool(v) => ("Bool", v.len()),
            Self::String(v) => ("String", v.len()),
            Self::Bytes(v) => ("Bytes", v.len()),
            Self::Date(v) => ("Date", v.len()),
            Self::DateTime(v) => ("DateTime", v.len()),
            Self::Time(v) => ("Time", v.len()),
        };
        write!(f, "{}({})", type_name, len)
    }
}

// Convenience From implementations for ColumnData.
// These allow creating columns without wrapping values in Option.

impl From<Vec<f64>> for ColumnData {
    fn from(values: Vec<f64>) -> Self {
        Self::F64(values.into_iter().map(Some).collect())
    }
}

impl From<Vec<i64>> for ColumnData {
    fn from(values: Vec<i64>) -> Self {
        Self::I64(values.into_iter().map(Some).collect())
    }
}

impl From<Vec<i32>> for ColumnData {
    fn from(values: Vec<i32>) -> Self {
        Self::I64(values.into_iter().map(|v| Some(i64::from(v))).collect())
    }
}

impl From<Vec<bool>> for ColumnData {
    fn from(values: Vec<bool>) -> Self {
        Self::Bool(values.into_iter().map(Some).collect())
    }
}

impl From<Vec<String>> for ColumnData {
    fn from(values: Vec<String>) -> Self {
        Self::String(values.into_iter().map(Some).collect())
    }
}

impl From<Vec<&str>> for ColumnData {
    fn from(values: Vec<&str>) -> Self {
        Self::String(values.into_iter().map(|s| Some(s.to_string())).collect())
    }
}

impl From<Vec<NaiveDate>> for ColumnData {
    fn from(values: Vec<NaiveDate>) -> Self {
        Self::Date(values.into_iter().map(Some).collect())
    }
}

impl From<Vec<NaiveDateTime>> for ColumnData {
    fn from(values: Vec<NaiveDateTime>) -> Self {
        Self::DateTime(values.into_iter().map(Some).collect())
    }
}

impl From<Vec<NaiveTime>> for ColumnData {
    fn from(values: Vec<NaiveTime>) -> Self {
        Self::Time(values.into_iter().map(Some).collect())
    }
}

/// CDISC variable roles.
///
/// These roles are metadata that help classify variables according to CDISC SDTM
/// terminology. They do not affect XPT binary encoding.
///
/// # Roles
///
/// - [`VariableRole::Identifier`] - Uniquely identifies observations (e.g., STUDYID, USUBJID)
/// - [`VariableRole::Topic`] - The focus of the observation (e.g., AEDECOD, LBTESTCD)
/// - [`VariableRole::Timing`] - When the observation occurred (e.g., AESTDTC, VISITNUM)
/// - [`VariableRole::Qualifier`] - Additional context (e.g., AESER, AESEV)
/// - [`VariableRole::Rule`] - Derived or algorithmic values (e.g., EPOCH)
///
/// # Example
///
/// ```
/// use xportrs::{Column, ColumnData, VariableRole};
///
/// // Assign roles to clinical data variables
/// let usubjid = Column::with_role(
///     "USUBJID",
///     VariableRole::Identifier,
///     ColumnData::String(vec![Some("01-001".into())]),
/// );
///
/// let aedecod = Column::with_role(
///     "AEDECOD",
///     VariableRole::Topic,
///     ColumnData::String(vec![Some("HEADACHE".into())]),
/// );
///
/// println!("{} role: {}", usubjid.name(), usubjid.role().unwrap());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum VariableRole {
    /// Identifier variables (e.g., STUDYID, USUBJID, DOMAIN).
    Identifier,
    /// Topic variables (e.g., AEDECOD, LBTESTCD).
    Topic,
    /// Timing variables (e.g., AESTDTC, VISITNUM).
    Timing,
    /// Qualifier variables (e.g., AESER, AESEV).
    Qualifier,
    /// Rule variables (e.g., EPOCH derived from other data).
    Rule,
}

impl VariableRole {
    /// Returns the role as a string.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Identifier => "Identifier",
            Self::Topic => "Topic",
            Self::Timing => "Timing",
            Self::Qualifier => "Qualifier",
            Self::Rule => "Rule",
        }
    }
}

impl std::fmt::Display for VariableRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

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

    #[test]
    fn test_domain_dataset_new() {
        let cols = vec![
            Column::new("A", ColumnData::F64(vec![Some(1.0), Some(2.0)])),
            Column::new(
                "B",
                ColumnData::String(vec![Some("x".into()), Some("y".into())]),
            ),
        ];
        let ds = Dataset::new("AE", cols).unwrap();
        assert_eq!(ds.nrows(), 2);
        assert_eq!(ds.ncols(), 2);
    }

    #[test]
    fn test_column_length_mismatch() {
        let cols = vec![
            Column::new("A", ColumnData::F64(vec![Some(1.0)])),
            Column::new(
                "B",
                ColumnData::String(vec![Some("x".into()), Some("y".into())]),
            ),
        ];
        let result = Dataset::new("AE", cols);
        assert!(result.is_err());
    }

    #[test]
    fn test_column_data_types() {
        assert!(ColumnData::F64(vec![]).is_numeric());
        assert!(ColumnData::I64(vec![]).is_numeric());
        assert!(ColumnData::Bool(vec![]).is_numeric());
        assert!(ColumnData::Date(vec![]).is_numeric());
        assert!(ColumnData::DateTime(vec![]).is_numeric());
        assert!(ColumnData::Time(vec![]).is_numeric());
        assert!(ColumnData::String(vec![]).is_character());
        assert!(ColumnData::Bytes(vec![]).is_character());
    }

    #[test]
    fn test_column_data_from_conversions() {
        // Test From<Vec<f64>>
        let data: ColumnData = vec![1.0, 2.0, 3.0].into();
        assert_eq!(data.len(), 3);
        assert!(data.is_numeric());

        // Test From<Vec<i64>>
        let data: ColumnData = vec![1i64, 2, 3].into();
        assert_eq!(data.len(), 3);
        assert!(data.is_numeric());

        // Test From<Vec<i32>>
        let data: ColumnData = vec![1i32, 2, 3].into();
        assert_eq!(data.len(), 3);
        assert!(data.is_numeric());

        // Test From<Vec<bool>>
        let data: ColumnData = vec![true, false, true].into();
        assert_eq!(data.len(), 3);
        assert!(data.is_numeric());

        // Test From<Vec<String>>
        let data: ColumnData = vec!["a".to_string(), "b".to_string()].into();
        assert_eq!(data.len(), 2);
        assert!(data.is_character());

        // Test From<Vec<&str>>
        let data: ColumnData = vec!["a", "b", "c"].into();
        assert_eq!(data.len(), 3);
        assert!(data.is_character());
    }
}