universal-date-parser 1.0.0

Universal date parser that can parse any date format into standardized output with intelligent format detection
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
//! # Universal Date Parser
//! 
//! A comprehensive date parsing library that can intelligently parse dates from virtually any format
//! into standardized output. Features automatic format detection, timezone awareness, and robust error handling.

use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc, TimeZone, FixedOffset, Datelike};
use regex::Regex;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use lazy_static::lazy_static;

/// Parse result containing the extracted date information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParsedDate {
    /// The parsed datetime in UTC
    pub datetime: DateTime<Utc>,
    /// The detected format pattern
    pub detected_format: String,
    /// Confidence score (0.0 to 1.0)
    pub confidence: f64,
    /// Original input string
    pub original_input: String,
    /// Timezone information if detected
    pub timezone: Option<String>,
    /// Additional metadata about the parsing
    pub metadata: ParseMetadata,
}

/// Additional metadata about the parsing process
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParseMetadata {
    /// Whether the date was ambiguous (e.g., could be MM/DD or DD/MM)
    pub is_ambiguous: bool,
    /// Alternative interpretations if ambiguous
    pub alternatives: Vec<DateTime<Utc>>,
    /// Components that were inferred (e.g., missing year defaulted to current)
    pub inferred_components: Vec<String>,
    /// Parsing method used
    pub parsing_method: String,
}

/// Configuration options for the date parser
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// Prefer DD/MM over MM/DD when ambiguous
    pub prefer_dmy: bool,
    /// Default year when not specified
    pub default_year: Option<i32>,
    /// Strict parsing (reject ambiguous dates)
    pub strict_mode: bool,
    /// Enable fuzzy parsing for malformed input
    pub fuzzy_parsing: bool,
    /// Custom format patterns to try first
    pub custom_patterns: Vec<String>,
    /// Timezone handling strategy
    pub timezone_strategy: TimezoneStrategy,
}

/// Strategy for handling timezones
#[derive(Debug, Clone, PartialEq)]
pub enum TimezoneStrategy {
    /// Assume UTC when no timezone specified
    AssumeUtc,
    /// Assume local timezone when no timezone specified
    AssumeLocal,
    /// Use specified default timezone
    UseDefault(FixedOffset),
    /// Reject dates without timezone information
    RequireTimezone,
}

/// Error types for date parsing
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ParseError {
    /// No recognizable date format found
    UnrecognizedFormat(String),
    /// Ambiguous date that requires disambiguation
    AmbiguousDate(String, Vec<String>),
    /// Invalid date components (e.g., February 30th)
    InvalidDate(String),
    /// Missing required timezone information
    MissingTimezone(String),
    /// Invalid timezone specification
    InvalidTimezone(String),
    /// General parsing error
    ParseError(String),
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            prefer_dmy: false,
            default_year: None,
            strict_mode: false,
            fuzzy_parsing: true,
            custom_patterns: Vec::new(),
            timezone_strategy: TimezoneStrategy::AssumeUtc,
        }
    }
}

/// Date format patterns with their regex patterns and parsing functions
lazy_static! {
    static ref DATE_PATTERNS: Vec<DatePattern> = vec![
        // ISO 8601 formats
        DatePattern::new(
            r"(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})(?:\.(\d+))?(?:Z|([+-]\d{2}):?(\d{2}))?",
            "ISO 8601 DateTime",
            1.0,
            ParseMethod::Iso8601
        ),
        DatePattern::new(
            r"(\d{4})-(\d{1,2})-(\d{1,2})",
            "ISO 8601 Date",
            0.95,
            ParseMethod::Iso8601
        ),
        
        // RFC 2822 / RFC 822 formats
        DatePattern::new(
            r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s*(\d{1,2})\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*([+-]\d{4}|\w+)",
            "RFC 2822",
            0.9,
            ParseMethod::Rfc2822
        ),
        
        // US format MM/DD/YYYY
        DatePattern::new(
            r"(\d{1,2})/(\d{1,2})/(\d{4})",
            "US Format MM/DD/YYYY",
            0.7,
            ParseMethod::UsFormat
        ),
        
        // European format DD/MM/YYYY
        DatePattern::new(
            r"(\d{1,2})/(\d{1,2})/(\d{4})",
            "European Format DD/MM/YYYY",
            0.7,
            ParseMethod::EuropeanFormat
        ),
        
        // Long format with month names
        DatePattern::new(
            r"(January|February|March|April|May|June|July|August|September|October|November|December)\s+(\d{1,2}),?\s+(\d{4})",
            "Long Format Month DD, YYYY",
            0.85,
            ParseMethod::LongFormat
        ),
        
        // Unix timestamp
        DatePattern::new(
            r"^(\d{10})$",
            "Unix Timestamp",
            0.8,
            ParseMethod::UnixTimestamp
        ),
        
        // Unix timestamp with milliseconds
        DatePattern::new(
            r"^(\d{13})$",
            "Unix Timestamp (ms)",
            0.8,
            ParseMethod::UnixTimestampMs
        ),
        
        // Relative dates
        DatePattern::new(
            r"(yesterday|today|tomorrow)",
            "Relative Date",
            0.9,
            ParseMethod::Relative
        ),
        
        // Fuzzy patterns for common malformed dates
        DatePattern::new(
            r"(\d{1,2})[-/\.](\d{1,2})[-/\.](\d{2,4})",
            "Flexible Separator Format",
            0.6,
            ParseMethod::FlexibleSeparator
        ),
    ];
}

#[derive(Debug, Clone)]
struct DatePattern {
    regex: Regex,
    name: String,
    confidence: f64,
    method: ParseMethod,
}

#[derive(Debug, Clone, PartialEq)]
enum ParseMethod {
    Iso8601,
    Rfc2822,
    UsFormat,
    EuropeanFormat,
    LongFormat,
    UnixTimestamp,
    UnixTimestampMs,
    Relative,
    FlexibleSeparator,
}

impl DatePattern {
    fn new(pattern: &str, name: &str, confidence: f64, method: ParseMethod) -> Self {
        Self {
            regex: Regex::new(pattern).unwrap(),
            name: name.to_string(),
            confidence,
            method,
        }
    }
}

/// Main universal date parser
pub struct UniversalDateParser {
    config: ParserConfig,
}

impl UniversalDateParser {
    /// Create a new parser with default configuration
    pub fn new() -> Self {
        Self {
            config: ParserConfig::default(),
        }
    }
    
    /// Create a new parser with custom configuration
    pub fn with_config(config: ParserConfig) -> Self {
        Self { config }
    }
    
    /// Parse a date string into a standardized format
    pub fn parse(&self, input: &str) -> Result<ParsedDate, ParseError> {
        let input = input.trim();
        
        if input.is_empty() {
            return Err(ParseError::ParseError("Empty input".to_string()));
        }
        
        // Try custom patterns first
        for pattern in &self.config.custom_patterns {
            if let Ok(result) = self.try_custom_pattern(input, pattern) {
                return Ok(result);
            }
        }
        
        // Try built-in patterns
        for pattern in DATE_PATTERNS.iter() {
            if let Some(captures) = pattern.regex.captures(input) {
                match self.parse_with_pattern(input, pattern, &captures) {
                    Ok(mut result) => {
                        // Apply configuration adjustments
                        if self.config.strict_mode && result.metadata.is_ambiguous {
                            return Err(ParseError::AmbiguousDate(
                                input.to_string(),
                                result.metadata.alternatives.iter()
                                    .map(|dt| dt.to_rfc3339())
                                    .collect()
                            ));
                        }
                        
                        result.original_input = input.to_string();
                        return Ok(result);
                    }
                    Err(_) => continue,
                }
            }
        }
        
        // If fuzzy parsing is enabled, try more aggressive approaches
        if self.config.fuzzy_parsing {
            if let Ok(result) = self.fuzzy_parse(input) {
                return Ok(result);
            }
        }
        
        Err(ParseError::UnrecognizedFormat(input.to_string()))
    }
    
    /// Parse multiple date formats and return all possible interpretations
    pub fn parse_all_possibilities(&self, input: &str) -> Vec<Result<ParsedDate, ParseError>> {
        let mut results = Vec::new();
        let input = input.trim();
        
        for pattern in DATE_PATTERNS.iter() {
            if let Some(captures) = pattern.regex.captures(input) {
                let result = self.parse_with_pattern(input, pattern, &captures);
                results.push(result);
            }
        }
        
        results
    }
    
    fn parse_with_pattern(
        &self,
        input: &str,
        pattern: &DatePattern,
        captures: &regex::Captures,
    ) -> Result<ParsedDate, ParseError> {
        match pattern.method {
            ParseMethod::Iso8601 => self.parse_iso8601(input, captures, pattern),
            ParseMethod::Rfc2822 => self.parse_rfc2822(input, captures, pattern),
            ParseMethod::UsFormat => self.parse_us_format(input, captures, pattern),
            ParseMethod::EuropeanFormat => self.parse_european_format(input, captures, pattern),
            ParseMethod::LongFormat => self.parse_long_format(input, captures, pattern),
            ParseMethod::UnixTimestamp => self.parse_unix_timestamp(input, captures, pattern),
            ParseMethod::UnixTimestampMs => self.parse_unix_timestamp_ms(input, captures, pattern),
            ParseMethod::Relative => self.parse_relative(input, captures, pattern),
            ParseMethod::FlexibleSeparator => self.parse_flexible_separator(input, captures, pattern),
        }
    }
    
    fn parse_iso8601(
        &self,
        input: &str,
        captures: &regex::Captures,
        pattern: &DatePattern,
    ) -> Result<ParsedDate, ParseError> {
        let year: i32 = captures.get(1).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid year".to_string()))?;
        let month: u32 = captures.get(2).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid month".to_string()))?;
        let day: u32 = captures.get(3).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid day".to_string()))?;
        
        if captures.get(4).is_some() {
            // Full datetime
            let hour: u32 = captures.get(4).unwrap().as_str().parse()
                .map_err(|_| ParseError::InvalidDate("Invalid hour".to_string()))?;
            let minute: u32 = captures.get(5).unwrap().as_str().parse()
                .map_err(|_| ParseError::InvalidDate("Invalid minute".to_string()))?;
            let second: u32 = captures.get(6).unwrap().as_str().parse()
                .map_err(|_| ParseError::InvalidDate("Invalid second".to_string()))?;
            
            let naive_dt = NaiveDate::from_ymd_opt(year, month, day)
                .and_then(|d| d.and_hms_opt(hour, minute, second))
                .ok_or_else(|| ParseError::InvalidDate("Invalid date components".to_string()))?;
            
            // Handle timezone
            let datetime = if let Some(tz_match) = captures.get(8) {
                // Has timezone offset
                let tz_str = tz_match.as_str();
                let offset = parse_timezone_offset(tz_str)?;
                offset.from_local_datetime(&naive_dt)
                    .single()
                    .ok_or_else(|| ParseError::InvalidTimezone("Ambiguous local time".to_string()))?
                    .with_timezone(&Utc)
            } else if input.ends_with('Z') {
                // UTC timezone
                Utc.from_local_datetime(&naive_dt)
                    .single()
                    .ok_or_else(|| ParseError::InvalidDate("Invalid UTC time".to_string()))?
            } else {
                // No timezone specified, use strategy
                self.apply_timezone_strategy(naive_dt)?
            };
            
            Ok(ParsedDate {
                datetime,
                detected_format: pattern.name.clone(),
                confidence: pattern.confidence,
                original_input: input.to_string(),
                timezone: if input.ends_with('Z') { Some("UTC".to_string()) } else { None },
                metadata: ParseMetadata {
                    is_ambiguous: false,
                    alternatives: Vec::new(),
                    inferred_components: Vec::new(),
                    parsing_method: "ISO8601".to_string(),
                },
            })
        } else {
            // Date only
            let naive_date = NaiveDate::from_ymd_opt(year, month, day)
                .ok_or_else(|| ParseError::InvalidDate("Invalid date components".to_string()))?;
            let naive_dt = naive_date.and_hms_opt(0, 0, 0).unwrap();
            let datetime = self.apply_timezone_strategy(naive_dt)?;
            
            Ok(ParsedDate {
                datetime,
                detected_format: pattern.name.clone(),
                confidence: pattern.confidence,
                original_input: input.to_string(),
                timezone: None,
                metadata: ParseMetadata {
                    is_ambiguous: false,
                    alternatives: Vec::new(),
                    inferred_components: vec!["time".to_string()],
                    parsing_method: "ISO8601".to_string(),
                },
            })
        }
    }
    
    fn parse_us_format(
        &self,
        input: &str,
        captures: &regex::Captures,
        pattern: &DatePattern,
    ) -> Result<ParsedDate, ParseError> {
        let month: u32 = captures.get(1).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid month".to_string()))?;
        let day: u32 = captures.get(2).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid day".to_string()))?;
        let year: i32 = captures.get(3).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid year".to_string()))?;
        
        self.create_date_result(year, month, day, pattern, "US Format", input)
    }
    
    fn parse_european_format(
        &self,
        input: &str,
        captures: &regex::Captures,
        pattern: &DatePattern,
    ) -> Result<ParsedDate, ParseError> {
        let day: u32 = captures.get(1).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid day".to_string()))?;
        let month: u32 = captures.get(2).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid month".to_string()))?;
        let year: i32 = captures.get(3).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid year".to_string()))?;
        
        self.create_date_result(year, month, day, pattern, "European Format", input)
    }
    
    fn parse_unix_timestamp(
        &self,
        input: &str,
        captures: &regex::Captures,
        pattern: &DatePattern,
    ) -> Result<ParsedDate, ParseError> {
        let timestamp: i64 = captures.get(1).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid timestamp".to_string()))?;
        
        let datetime = DateTime::from_timestamp(timestamp, 0)
            .ok_or_else(|| ParseError::InvalidDate("Invalid timestamp value".to_string()))?;
        
        Ok(ParsedDate {
            datetime,
            detected_format: pattern.name.clone(),
            confidence: pattern.confidence,
            original_input: input.to_string(),
            timezone: Some("UTC".to_string()),
            metadata: ParseMetadata {
                is_ambiguous: false,
                alternatives: Vec::new(),
                inferred_components: Vec::new(),
                parsing_method: "Unix Timestamp".to_string(),
            },
        })
    }
    
    fn parse_unix_timestamp_ms(
        &self,
        input: &str,
        captures: &regex::Captures,
        pattern: &DatePattern,
    ) -> Result<ParsedDate, ParseError> {
        let timestamp_ms: i64 = captures.get(1).unwrap().as_str().parse()
            .map_err(|_| ParseError::InvalidDate("Invalid timestamp".to_string()))?;
        
        let secs = timestamp_ms / 1000;
        let nsecs = ((timestamp_ms % 1000) * 1_000_000) as u32;
        
        let datetime = DateTime::from_timestamp(secs, nsecs)
            .ok_or_else(|| ParseError::InvalidDate("Invalid timestamp value".to_string()))?;
        
        Ok(ParsedDate {
            datetime,
            detected_format: pattern.name.clone(),
            confidence: pattern.confidence,
            original_input: input.to_string(),
            timezone: Some("UTC".to_string()),
            metadata: ParseMetadata {
                is_ambiguous: false,
                alternatives: Vec::new(),
                inferred_components: Vec::new(),
                parsing_method: "Unix Timestamp (ms)".to_string(),
            },
        })
    }
    
    fn create_date_result(
        &self,
        year: i32,
        month: u32,
        day: u32,
        pattern: &DatePattern,
        method: &str,
        input: &str,
    ) -> Result<ParsedDate, ParseError> {
        let naive_date = NaiveDate::from_ymd_opt(year, month, day)
            .ok_or_else(|| ParseError::InvalidDate("Invalid date components".to_string()))?;
        let naive_dt = naive_date.and_hms_opt(0, 0, 0).unwrap();
        let datetime = self.apply_timezone_strategy(naive_dt)?;
        
        // Check for ambiguity (same numbers could be interpreted differently)
        let is_ambiguous = day <= 12 && month <= 12 && day != month;
        let mut alternatives = Vec::new();
        
        if is_ambiguous && !self.config.prefer_dmy {
            // Also try the alternative interpretation
            if let Some(alt_date) = NaiveDate::from_ymd_opt(year, day, month) {
                if let Some(alt_dt) = alt_date.and_hms_opt(0, 0, 0) {
                    if let Ok(alt_datetime) = self.apply_timezone_strategy(alt_dt) {
                        alternatives.push(alt_datetime);
                    }
                }
            }
        }
        
        Ok(ParsedDate {
            datetime,
            detected_format: pattern.name.clone(),
            confidence: if is_ambiguous { pattern.confidence * 0.8 } else { pattern.confidence },
            original_input: input.to_string(),
            timezone: None,
            metadata: ParseMetadata {
                is_ambiguous,
                alternatives,
                inferred_components: vec!["time".to_string()],
                parsing_method: method.to_string(),
            },
        })
    }
    
    fn apply_timezone_strategy(&self, naive_dt: NaiveDateTime) -> Result<DateTime<Utc>, ParseError> {
        match &self.config.timezone_strategy {
            TimezoneStrategy::AssumeUtc => {
                Ok(Utc.from_local_datetime(&naive_dt)
                    .single()
                    .ok_or_else(|| ParseError::InvalidDate("Invalid UTC time".to_string()))?)
            }
            TimezoneStrategy::UseDefault(offset) => {
                Ok(offset.from_local_datetime(&naive_dt)
                    .single()
                    .ok_or_else(|| ParseError::InvalidTimezone("Ambiguous local time".to_string()))?
                    .with_timezone(&Utc))
            }
            TimezoneStrategy::RequireTimezone => {
                Err(ParseError::MissingTimezone("Timezone required but not specified".to_string()))
            }
            TimezoneStrategy::AssumeLocal => {
                // For simplicity, assume UTC for now
                // In a real implementation, you'd use the system's local timezone
                Ok(Utc.from_local_datetime(&naive_dt)
                    .single()
                    .ok_or_else(|| ParseError::InvalidDate("Invalid local time".to_string()))?)
            }
        }
    }
    
    // Placeholder implementations for other parsing methods
    fn parse_rfc2822(&self, _input: &str, _captures: &regex::Captures, _pattern: &DatePattern) -> Result<ParsedDate, ParseError> {
        Err(ParseError::ParseError("RFC2822 parsing not implemented".to_string()))
    }
    
    fn parse_long_format(&self, _input: &str, _captures: &regex::Captures, _pattern: &DatePattern) -> Result<ParsedDate, ParseError> {
        Err(ParseError::ParseError("Long format parsing not implemented".to_string()))
    }
    
    fn parse_relative(&self, _input: &str, _captures: &regex::Captures, _pattern: &DatePattern) -> Result<ParsedDate, ParseError> {
        Err(ParseError::ParseError("Relative parsing not implemented".to_string()))
    }
    
    fn parse_flexible_separator(&self, _input: &str, _captures: &regex::Captures, _pattern: &DatePattern) -> Result<ParsedDate, ParseError> {
        Err(ParseError::ParseError("Flexible separator parsing not implemented".to_string()))
    }
    
    fn try_custom_pattern(&self, _input: &str, _pattern: &str) -> Result<ParsedDate, ParseError> {
        Err(ParseError::ParseError("Custom pattern parsing not implemented".to_string()))
    }
    
    fn fuzzy_parse(&self, _input: &str) -> Result<ParsedDate, ParseError> {
        Err(ParseError::ParseError("Fuzzy parsing not implemented".to_string()))
    }
}

impl Default for UniversalDateParser {
    fn default() -> Self {
        Self::new()
    }
}

fn parse_timezone_offset(tz_str: &str) -> Result<FixedOffset, ParseError> {
    if tz_str.len() >= 5 {
        let sign = if tz_str.starts_with('+') { 1 } else { -1 };
        let hours: i32 = tz_str[1..3].parse()
            .map_err(|_| ParseError::InvalidTimezone("Invalid timezone hours".to_string()))?;
        let minutes: i32 = tz_str[3..5].parse()
            .map_err(|_| ParseError::InvalidTimezone("Invalid timezone minutes".to_string()))?;
        
        let total_seconds = sign * (hours * 3600 + minutes * 60);
        FixedOffset::east_opt(total_seconds)
            .ok_or_else(|| ParseError::InvalidTimezone("Invalid timezone offset".to_string()))
    } else {
        Err(ParseError::InvalidTimezone("Invalid timezone format".to_string()))
    }
}

// C FFI exports
#[no_mangle]
pub extern "C" fn parse_date_c(input: *const std::os::raw::c_char) -> *mut std::os::raw::c_char {
    if input.is_null() {
        return std::ptr::null_mut();
    }
    
    let c_str = unsafe { std::ffi::CStr::from_ptr(input) };
    let input_str = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let parser = UniversalDateParser::new();
    match parser.parse(input_str) {
        Ok(result) => {
            let json = serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string());
            let c_string = std::ffi::CString::new(json).unwrap_or_else(|_| std::ffi::CString::new("{}").unwrap());
            c_string.into_raw()
        }
        Err(_) => std::ptr::null_mut(),
    }
}

#[no_mangle]
pub extern "C" fn free_string_c(ptr: *mut std::os::raw::c_char) {
    if !ptr.is_null() {
        unsafe { let _ = std::ffi::CString::from_raw(ptr); }
    }
}

// WebAssembly exports
#[wasm_bindgen]
pub fn parse_date_wasm(input: &str) -> String {
    let parser = UniversalDateParser::new();
    match parser.parse(input) {
        Ok(result) => serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string()),
        Err(err) => serde_json::to_string(&err).unwrap_or_else(|_| r#"{"error":"Unknown error"}"#.to_string()),
    }
}

#[wasm_bindgen]
pub fn parse_all_possibilities_wasm(input: &str) -> String {
    let parser = UniversalDateParser::new();
    let results = parser.parse_all_possibilities(input);
    serde_json::to_string(&results).unwrap_or_else(|_| "[]".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_iso8601_parsing() {
        let parser = UniversalDateParser::new();
        
        let result = parser.parse("2023-12-25T15:30:45Z").unwrap();
        assert_eq!(result.detected_format, "ISO 8601 DateTime");
        assert!(result.confidence > 0.9);
        
        let result = parser.parse("2023-12-25").unwrap();
        assert_eq!(result.detected_format, "ISO 8601 Date");
    }
    
    #[test]
    fn test_us_format_parsing() {
        let parser = UniversalDateParser::new();
        
        let result = parser.parse("12/25/2023").unwrap();
        assert_eq!(result.detected_format, "US Format MM/DD/YYYY");
        assert_eq!(result.datetime.month(), 12);
        assert_eq!(result.datetime.day(), 25);
    }
    
    #[test]
    fn test_unix_timestamp_parsing() {
        let parser = UniversalDateParser::new();
        
        let result = parser.parse("1703520645").unwrap();
        assert_eq!(result.detected_format, "Unix Timestamp");
        
        let result = parser.parse("1703520645000").unwrap();
        assert_eq!(result.detected_format, "Unix Timestamp (ms)");
    }
    
    #[test]
    fn test_ambiguous_dates() {
        let parser = UniversalDateParser::new();
        
        let result = parser.parse("01/02/2023").unwrap();
        assert!(result.metadata.is_ambiguous);
        assert!(!result.metadata.alternatives.is_empty());
    }
    
    #[test]
    fn test_invalid_dates() {
        let parser = UniversalDateParser::new();
        
        assert!(parser.parse("").is_err());
        assert!(parser.parse("not a date").is_err());
        assert!(parser.parse("13/32/2023").is_err());
    }
    
    #[test]
    fn test_strict_mode() {
        let config = ParserConfig {
            strict_mode: true,
            ..Default::default()
        };
        let parser = UniversalDateParser::with_config(config);
        
        // Should reject ambiguous dates in strict mode
        assert!(parser.parse("01/02/2023").is_err());
    }
}