brahe 1.4.0

Brahe is a modern satellite dynamics library for research and engineering applications designed to be easy-to-learn, high-performance, and quick-to-deploy. The north-star of the development is enabling users to solve meaningful problems and answer questions quickly, easily, and correctly.
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
/*!
 * Defines the CachingEOPProvider that checks file age and downloads updates
 */

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use crate::eop::download::{download_c04_eop_file, download_standard_eop_file};
use crate::eop::eop_provider::EarthOrientationProvider;
use crate::eop::eop_types::{EOPExtrapolation, EOPType};
use crate::eop::file_provider::FileEOPProvider;
use crate::time::{Epoch, TimeSystem};
use crate::utils::BraheError;

/// Provides Earth Orientation Parameter (EOP) data with automatic cache refresh.
///
/// The `CachingEOPProvider` wraps a `FileEOPProvider` and automatically checks the age
/// of the EOP file. If the file is older than the configured maximum age, it downloads
/// an updated version before loading the data.
///
/// This is useful for applications that need to maintain current EOP data without manual
/// intervention, such as long-running services or applications that need accurate
/// reference frame transformations.
///
/// # Fields
///
/// - `filepath`: Path to the EOP file
/// - `eop_type`: Type of EOP file (C04 or StandardBulletinA)
/// - `max_age_seconds`: Maximum age of the file in seconds before triggering a download
/// - `auto_refresh`: If true, automatically check file age on each access and refresh if needed
/// - `interpolate`: Whether to interpolate between data points
/// - `extrapolate`: Behavior for out-of-bounds data access
/// - `provider`: Internal FileEOPProvider that actually loads and provides the data
/// - `file_loaded_at`: Timestamp when the file was last loaded
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use brahe::eop::{CachingEOPProvider, EOPType, EOPExtrapolation};
///
/// // Create a caching provider with explicit filepath
/// let filepath = Path::new("/tmp/finals.all.iau2000.txt");
/// let max_age_days = 7;
/// let max_age_seconds = max_age_days * 86400;
///
/// let provider = CachingEOPProvider::new(
///     Some(filepath),
///     EOPType::StandardBulletinA,
///     max_age_seconds,
///     false,
///     true,
///     EOPExtrapolation::Hold
/// ).unwrap();
///
/// // Or use default cache location
/// let provider = CachingEOPProvider::new(
///     None,
///     EOPType::StandardBulletinA,
///     max_age_seconds,
///     false,
///     true,
///     EOPExtrapolation::Hold
/// ).unwrap();
/// ```
#[derive(Clone)]
pub struct CachingEOPProvider {
    filepath: PathBuf,
    eop_type: EOPType,
    max_age_seconds: u64,
    /// Enable automatic refresh checks on each EOP data access. If true, provider verifies
    /// file age before each query and downloads updates when needed. If false, manual refresh required.
    pub auto_refresh: bool,
    interpolate: bool,
    extrapolate: EOPExtrapolation,
    provider: Arc<Mutex<FileEOPProvider>>,
    file_loaded_at: Arc<Mutex<SystemTime>>,
}

impl CachingEOPProvider {
    /// Creates a new CachingEOPProvider that checks file age and downloads updates as needed.
    ///
    /// If the file doesn't exist, it will be downloaded. If the file exists but is older than
    /// `max_age_seconds`, it will be re-downloaded before loading. Otherwise, the existing file
    /// is loaded.
    ///
    /// # Arguments
    ///
    /// * `filepath` - Optional path to the EOP file. If `None`, uses default cache location:
    ///   - StandardBulletinA: `~/.cache/brahe/eop/finals.all.iau2000.txt`
    ///   - C04: `~/.cache/brahe/eop/EOP_20_C04_one_file_1962-now.txt`
    /// * `eop_type` - Type of EOP file (C04 or StandardBulletinA)
    /// * `max_age_seconds` - Maximum age of the file in seconds before triggering a download
    /// * `auto_refresh` - If true, automatically check file age on each access and refresh if needed
    /// * `interpolate` - Whether to interpolate between data points
    /// * `extrapolate` - Behavior for out-of-bounds data access
    ///
    /// # Returns
    ///
    /// * `Result<CachingEOPProvider, BraheError>` - CachingEOPProvider with loaded data, or an error
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use brahe::eop::{CachingEOPProvider, EOPType, EOPExtrapolation};
    ///
    /// // With explicit filepath
    /// let filepath = Path::new("/tmp/finals.all.iau2000.txt");
    /// let provider = CachingEOPProvider::new(
    ///     Some(filepath),
    ///     EOPType::StandardBulletinA,
    ///     7 * 86400, // 7 days
    ///     false,     // auto_refresh
    ///     true,
    ///     EOPExtrapolation::Hold
    /// ).unwrap();
    ///
    /// // With default cache location
    /// let provider = CachingEOPProvider::new(
    ///     None,
    ///     EOPType::StandardBulletinA,
    ///     7 * 86400,
    ///     false,
    ///     true,
    ///     EOPExtrapolation::Hold
    /// ).unwrap();
    /// ```
    pub fn new(
        filepath: Option<&Path>,
        eop_type: EOPType,
        max_age_seconds: u64,
        auto_refresh: bool,
        interpolate: bool,
        extrapolate: EOPExtrapolation,
    ) -> Result<Self, BraheError> {
        let filepath = if let Some(path) = filepath {
            path.to_path_buf()
        } else {
            // Use default cache location
            let cache_dir = crate::utils::cache::get_eop_cache_dir()?;
            let filename = match eop_type {
                EOPType::StandardBulletinA => "finals.all.iau2000.txt",
                EOPType::C04 => "EOP_20_C04_one_file_1962-now.txt",
                _ => {
                    return Err(BraheError::EOPError(format!(
                        "Unsupported EOP type for caching: {:?}. Only C04 and StandardBulletinA are supported.",
                        eop_type
                    )));
                }
            };
            PathBuf::from(cache_dir).join(filename)
        };

        // Check if file needs to be downloaded
        let needs_download = Self::check_file_age(&filepath, max_age_seconds)?;

        if needs_download {
            Self::download_file(&filepath, eop_type)?;
        }

        // Load the file into a FileEOPProvider
        let provider = FileEOPProvider::from_file(&filepath, interpolate, extrapolate)?;

        // Record when file was loaded
        let file_loaded_at = Arc::new(Mutex::new(SystemTime::now()));

        Ok(Self {
            filepath,
            eop_type,
            max_age_seconds,
            auto_refresh,
            interpolate,
            extrapolate,
            provider: Arc::new(Mutex::new(provider)),
            file_loaded_at,
        })
    }

    /// Checks if a file needs to be downloaded based on its age.
    ///
    /// Returns `true` if:
    /// - The file doesn't exist
    /// - The file's modification time cannot be determined
    /// - The file is older than `max_age_seconds`
    ///
    /// # Arguments
    ///
    /// * `filepath` - Path to check
    /// * `max_age_seconds` - Maximum acceptable age in seconds
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - File needs to be downloaded
    /// * `Ok(false)` - File exists and is current
    /// * `Err(BraheError)` - Error checking file
    fn check_file_age(filepath: &Path, max_age_seconds: u64) -> Result<bool, BraheError> {
        // If file doesn't exist, we need to download it
        if !filepath.exists() {
            return Ok(true);
        }

        // Get file metadata
        let metadata = fs::metadata(filepath).map_err(|e| {
            BraheError::IoError(format!(
                "Failed to get metadata for {}: {}",
                filepath.display(),
                e
            ))
        })?;

        // Get file modification time
        let modified = metadata.modified().map_err(|e| {
            BraheError::IoError(format!(
                "Failed to get modification time for {}: {}",
                filepath.display(),
                e
            ))
        })?;

        // Get current time
        let now = SystemTime::now();

        // Calculate file age in seconds
        let age = now
            .duration_since(modified)
            .map_err(|e| {
                BraheError::IoError(format!(
                    "Failed to calculate file age for {}: {}",
                    filepath.display(),
                    e
                ))
            })?
            .as_secs();

        // Return true if file is older than max age
        Ok(age > max_age_seconds)
    }

    /// Downloads an EOP file to the specified path.
    ///
    /// # Arguments
    ///
    /// * `filepath` - Path where the file should be saved
    /// * `eop_type` - Type of EOP file to download (C04 or StandardBulletinA)
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Download succeeded
    /// * `Err(BraheError)` - Download failed
    fn download_file(filepath: &Path, eop_type: EOPType) -> Result<(), BraheError> {
        let filepath_str = filepath
            .to_str()
            .ok_or_else(|| BraheError::IoError("Invalid file path".to_string()))?;

        match eop_type {
            EOPType::C04 => download_c04_eop_file(filepath_str),
            EOPType::StandardBulletinA => download_standard_eop_file(filepath_str),
            _ => Err(BraheError::EOPError(format!(
                "Unsupported EOP type for download: {:?}",
                eop_type
            ))),
        }
    }

    /// Refreshes the cached EOP data by re-checking the file age and reloading if necessary.
    ///
    /// This method allows manual refresh of the cache without creating a new provider instance.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Refresh succeeded (or wasn't needed)
    /// * `Err(BraheError)` - Refresh failed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use brahe::eop::{CachingEOPProvider, EOPType, EOPExtrapolation};
    ///
    /// let filepath = Path::new("/tmp/finals.all.iau2000.txt");
    /// let mut provider = CachingEOPProvider::new(
    ///     Some(filepath),
    ///     EOPType::StandardBulletinA,
    ///     7 * 86400,
    ///     false,
    ///     true,
    ///     EOPExtrapolation::Hold
    /// ).unwrap();
    ///
    /// // Later, force a refresh check
    /// provider.refresh().unwrap();
    /// ```
    pub fn refresh(&self) -> Result<(), BraheError> {
        let needs_download = Self::check_file_age(&self.filepath, self.max_age_seconds)?;

        if needs_download {
            Self::download_file(&self.filepath, self.eop_type)?;
            let new_provider =
                FileEOPProvider::from_file(&self.filepath, self.interpolate, self.extrapolate)?;
            *self.provider.lock().unwrap() = new_provider;
            *self.file_loaded_at.lock().unwrap() = SystemTime::now();
        }

        Ok(())
    }

    /// Returns the Epoch when the EOP file was last loaded into memory, in UTC.
    ///
    /// This represents the timestamp when the file was last loaded into memory.
    ///
    /// # Returns
    ///
    /// * `Epoch` - Epoch representing when the file was loaded, in UTC time system
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use brahe::eop::{CachingEOPProvider, EOPType, EOPExtrapolation};
    ///
    /// let filepath = Path::new("/tmp/finals.all.iau2000.txt");
    /// let provider = CachingEOPProvider::new(
    ///     Some(filepath),
    ///     EOPType::StandardBulletinA,
    ///     7 * 86400,
    ///     false,
    ///     true,
    ///     EOPExtrapolation::Hold
    /// ).unwrap();
    ///
    /// let file_epoch = provider.file_epoch();
    /// println!("EOP file loaded at: {}", file_epoch);
    /// ```
    pub fn file_epoch(&self) -> Epoch {
        let system_time = *self.file_loaded_at.lock().unwrap();

        // Convert SystemTime to Epoch
        // SystemTime is based on UNIX epoch (1970-01-01 00:00:00 UTC)
        let duration_since_unix_epoch = system_time
            .duration_since(SystemTime::UNIX_EPOCH)
            .expect("System time is before UNIX epoch");

        let seconds_since_unix = duration_since_unix_epoch.as_secs_f64();

        // UNIX epoch in MJD: 1970-01-01 00:00:00 UTC = MJD 40587.0
        const UNIX_EPOCH_MJD: f64 = 40587.0;
        let mjd = UNIX_EPOCH_MJD + seconds_since_unix / 86400.0;

        Epoch::from_mjd(mjd, TimeSystem::UTC)
    }

    /// Returns the age of the currently loaded EOP file in seconds.
    ///
    /// Calculates how many seconds have elapsed since the file was loaded.
    ///
    /// # Returns
    ///
    /// * `f64` - Age of the loaded file in seconds
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use brahe::eop::{CachingEOPProvider, EOPType, EOPExtrapolation};
    ///
    /// let filepath = Path::new("/tmp/finals.all.iau2000.txt");
    /// let provider = CachingEOPProvider::new(
    ///     Some(filepath),
    ///     EOPType::StandardBulletinA,
    ///     7 * 86400,
    ///     false,
    ///     true,
    ///     EOPExtrapolation::Hold
    /// ).unwrap();
    ///
    /// let age_seconds = provider.file_age();
    /// println!("EOP file age: {:.2} seconds", age_seconds);
    /// ```
    pub fn file_age(&self) -> f64 {
        let system_time = *self.file_loaded_at.lock().unwrap();
        let now = SystemTime::now();

        let duration = now
            .duration_since(system_time)
            .expect("System time went backwards");

        duration.as_secs_f64()
    }

    /// Checks if auto-refresh is needed and performs it if necessary.
    ///
    /// This is an internal method called by EarthOrientationProvider trait methods
    /// when auto_refresh is enabled.
    fn check_auto_refresh(&self) -> Result<(), BraheError> {
        if self.auto_refresh {
            self.refresh()?;
        }
        Ok(())
    }
}

impl EarthOrientationProvider for CachingEOPProvider {
    fn is_initialized(&self) -> bool {
        self.provider.lock().unwrap().is_initialized()
    }

    fn len(&self) -> usize {
        self.provider.lock().unwrap().len()
    }

    fn eop_type(&self) -> EOPType {
        self.provider.lock().unwrap().eop_type()
    }

    fn extrapolation(&self) -> EOPExtrapolation {
        self.provider.lock().unwrap().extrapolation()
    }

    fn interpolation(&self) -> bool {
        self.provider.lock().unwrap().interpolation()
    }

    fn mjd_min(&self) -> f64 {
        self.provider.lock().unwrap().mjd_min()
    }

    fn mjd_max(&self) -> f64 {
        self.provider.lock().unwrap().mjd_max()
    }

    fn mjd_last_lod(&self) -> f64 {
        self.provider.lock().unwrap().mjd_last_lod()
    }

    fn mjd_last_dxdy(&self) -> f64 {
        self.provider.lock().unwrap().mjd_last_dxdy()
    }

    fn get_ut1_utc(&self, mjd: f64) -> Result<f64, BraheError> {
        self.check_auto_refresh()?;
        self.provider.lock().unwrap().get_ut1_utc(mjd)
    }

    fn get_pm(&self, mjd: f64) -> Result<(f64, f64), BraheError> {
        self.check_auto_refresh()?;
        self.provider.lock().unwrap().get_pm(mjd)
    }

    fn get_dxdy(&self, mjd: f64) -> Result<(f64, f64), BraheError> {
        self.check_auto_refresh()?;
        self.provider.lock().unwrap().get_dxdy(mjd)
    }

    fn get_lod(&self, mjd: f64) -> Result<f64, BraheError> {
        self.check_auto_refresh()?;
        self.provider.lock().unwrap().get_lod(mjd)
    }

    fn get_eop(&self, mjd: f64) -> Result<(f64, f64, f64, f64, f64, f64), BraheError> {
        self.check_auto_refresh()?;
        self.provider.lock().unwrap().get_eop(mjd)
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use std::env;
    use std::fs::File;
    use std::thread;
    use std::time::Duration;
    use tempfile::tempdir;

    #[test]
    fn test_check_file_age_nonexistent() {
        let dir = tempdir().unwrap();
        let filepath = dir.path().join("nonexistent.txt");

        // Non-existent file should need download
        assert!(CachingEOPProvider::check_file_age(&filepath, 86400).unwrap());
    }

    #[test]
    fn test_check_file_age_current() {
        let dir = tempdir().unwrap();
        let filepath = dir.path().join("current.txt");

        // Create a new file
        File::create(&filepath).unwrap();

        // File should be current (less than 1 day old)
        assert!(!CachingEOPProvider::check_file_age(&filepath, 86400).unwrap());
    }

    #[test]
    #[cfg_attr(not(feature = "ci"), ignore)]
    fn test_check_file_age_stale() {
        let dir = tempdir().unwrap();
        let filepath = dir.path().join("stale.txt");

        // Create a file
        File::create(&filepath).unwrap();

        // Sleep briefly to ensure some time passes
        // Some file systems have 1-second resolution, so we need to sleep at least 1 second
        thread::sleep(Duration::from_secs(2));

        // Check with a very small max age (file should be stale)
        assert!(CachingEOPProvider::check_file_age(&filepath, 1).unwrap());
    }

    #[test]
    fn test_new_with_existing_file() {
        // Copy test EOP file to temporary location
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        // Create provider with large max age (file should be used as-is)
        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            365 * 86400, // 1 year
            false,       // auto_refresh
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        assert!(provider.is_initialized());
        assert_eq!(provider.eop_type(), EOPType::StandardBulletinA);
        assert!(provider.len() > 0);
    }

    #[test]
    #[cfg_attr(not(feature = "ci"), ignore)]
    fn test_new_creates_missing_file() {
        // This test requires network access and is marked to skip in normal test runs
        // Uncomment the line below to run it manually
        let dir = tempdir().unwrap();
        let filepath = dir.path().join("downloaded_eop.txt");

        let provider = CachingEOPProvider::new(
            Some(&filepath),
            EOPType::StandardBulletinA,
            7 * 86400,
            true,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        assert!(filepath.exists());
        assert!(provider.is_initialized());
    }

    #[test]
    #[cfg_attr(not(feature = "ci"), ignore)]
    fn test_new_with_default_path() {
        // This test requires network access and writes to default cache directory
        let provider = CachingEOPProvider::new(
            None,
            EOPType::StandardBulletinA,
            7 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        assert!(provider.is_initialized());
        assert_eq!(provider.eop_type(), EOPType::StandardBulletinA);
        assert!(provider.len() > 0);

        // Verify the file was created in the cache directory
        let cache_dir = crate::utils::cache::get_eop_cache_dir().unwrap();
        let expected_path = PathBuf::from(cache_dir).join("finals.all.iau2000.txt");
        assert!(expected_path.exists());
    }

    #[test]
    fn test_refresh() {
        // Copy test EOP file to temporary location
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop_refresh.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        // Create provider
        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            365 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        let original_len = provider.len();

        // Refresh should succeed (no download needed)
        provider.refresh().unwrap();

        // Length should be unchanged
        assert_eq!(provider.len(), original_len);
    }

    #[test]
    fn test_eop_provider_delegation() {
        // Test that EarthOrientationProvider methods are properly delegated
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop_delegation.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            100 * 365 * 86400, // 100 years - prevent download
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        // Test basic properties
        assert!(provider.is_initialized());
        assert_eq!(provider.eop_type(), EOPType::StandardBulletinA);
        assert_eq!(provider.extrapolation(), EOPExtrapolation::Hold);
        assert!(provider.interpolation());
        assert_eq!(provider.mjd_min(), 41684.0);
        // The max mjd may change as the packaged EOP file is updated
        assert!(provider.mjd_max() >= 60672.0);

        // Test data retrieval
        let ut1_utc = provider.get_ut1_utc(59569.0).unwrap();
        assert_eq!(ut1_utc, -0.1079939);

        let (pm_x, pm_y) = provider.get_pm(59569.0).unwrap();
        assert!(pm_x > 0.0);
        assert!(pm_y > 0.0);

        let (dx, dy) = provider.get_dxdy(59569.0).unwrap();
        assert!(dx != 0.0 || dy != 0.0);

        let lod = provider.get_lod(59569.0).unwrap();
        assert!(lod != 0.0);
    }

    #[test]
    fn test_new_with_c04_type() {
        // Test creating provider with C04 type
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("EOP_20_C04_one_file_1962-now.txt");
        let dest_path = dir.path().join("test_eop_c04.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::C04,
            365 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        assert!(provider.is_initialized());
        assert_eq!(provider.eop_type(), EOPType::C04);
        assert!(provider.len() > 0);
    }

    #[test]
    fn test_new_with_unknown_type_error() {
        // Test that creating provider with Unknown type returns error
        let dir = tempdir().unwrap();
        let dest_path = dir.path().join("test_eop_unknown.txt");

        let result = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::Unknown,
            365 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        );

        assert!(result.is_err());
    }

    #[test]
    fn test_file_epoch() {
        // Test file_epoch returns correct timestamp
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop_epoch.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            365 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        let epoch = provider.file_epoch();
        assert_eq!(epoch.time_system, TimeSystem::UTC);

        // The epoch should be recent (within the last year for this test)
        // Use abs() to handle potential clock skew
        let now = Epoch::now();
        let diff_seconds = (now.mjd() - epoch.mjd()) * 86400.0;
        assert!(diff_seconds.abs() < 365.0 * 86400.0);
    }

    #[test]
    fn test_file_age() {
        // Test file_age returns correct age
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop_age.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            365 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        // Age should be very small (just created)
        let age = provider.file_age();
        assert!(age < 10.0); // Less than 10 seconds

        // Sleep briefly and check age increased
        thread::sleep(Duration::from_secs(1));
        let age2 = provider.file_age();
        assert!(age2 >= 1.0);
        assert!(age2 > age);
    }

    #[test]
    fn test_mjd_last_lod_delegation() {
        // Test that mjd_last_lod delegates to FileEOPProvider
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop_last_lod.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            100 * 365 * 86400, // 100 years - prevent download
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        let mjd_last_lod = provider.mjd_last_lod();
        assert_eq!(mjd_last_lod, 60298.0);
    }

    #[test]
    fn test_mjd_last_dxdy_delegation() {
        // Test that mjd_last_dxdy delegates to FileEOPProvider
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_eop_last_dxdy.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            100 * 365 * 86400, // 100 years - prevent download
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        let mjd_last_dxdy = provider.mjd_last_dxdy();
        assert_eq!(mjd_last_dxdy, 60373.0);
    }

    #[test]
    fn test_get_eop_method() {
        // Test that get_eop works correctly with auto_refresh
        let dir = tempdir().unwrap();
        let src_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("test_assets")
            .join("finals.all.iau2000.txt");
        let dest_path = dir.path().join("test_get_eop.txt");

        fs::copy(&src_path, &dest_path).unwrap();

        let provider = CachingEOPProvider::new(
            Some(&dest_path),
            EOPType::StandardBulletinA,
            365 * 86400,
            false,
            true,
            EOPExtrapolation::Hold,
        )
        .unwrap();

        // Test get_eop returns correct data
        let eop_data = provider.get_eop(59569.0).unwrap();
        assert_eq!(eop_data.2, -0.1079939); // ut1_utc
        assert!(eop_data.0 > 0.0); // pm_x
        assert!(eop_data.1 > 0.0); // pm_y
    }
}