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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
/*!
 * Access property computation types and utilities
 *
 * This module provides types and traits for computing properties of access windows,
 * including geometric properties (azimuth, elevation, look direction) and custom
 * user-defined properties.
 */

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::time::Epoch;
use crate::utils::BraheError;

use super::constraints::{AscDsc, LookDirection};

// Import AccessWindow from windows module via parent re-export
// This works because both modules are siblings in the access module
#[allow(unused_imports)]
use crate::access::AccessWindow;

// ================================
// PropertyValue Enum
// ================================

/// Flexible value type for custom access properties.
///
/// This enum supports various data types that users might want to compute
/// and store as access properties, from simple scalars to complex time series.
///
/// # Examples
/// ```
/// use brahe::access::PropertyValue;
///
/// // Scalar property
/// let doppler_shift = PropertyValue::Scalar(2500.0);
///
/// // Vector property
/// let look_angles = PropertyValue::Vector(vec![45.0, 30.0]);
///
/// // Time series property
/// let elevation_profile = PropertyValue::TimeSeries {
///     times: vec![0.0, 10.0, 20.0],
///     values: vec![10.0, 45.0, 10.0],
///  };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PropertyValue {
    /// Single floating-point value
    Scalar(f64),

    /// Vector of floating-point values
    Vector(Vec<f64>),

    /// Time series with relative times (seconds from window_open) and values
    TimeSeries {
        /// Relative time from window_open (seconds)
        times: Vec<f64>,
        /// Values at each time
        values: Vec<f64>,
    },

    /// Boolean value
    Boolean(bool),

    /// String value
    String(String),

    /// Arbitrary JSON value for complex data
    Json(serde_json::Value),
}

// ================================
// SamplingConfig Enum
// ================================

/// Configuration for sampling satellite states during an access window.
///
/// This enum defines how property computers should sample satellite states
/// within an access window. Different sampling strategies are useful for
/// different types of properties.
///
/// # Examples
/// ```
/// use brahe::access::SamplingConfig;
///
/// // Single point at window midpoint
/// let midpoint = SamplingConfig::Midpoint;
///
/// // Sample at start, middle, and end
/// let relative = SamplingConfig::RelativePoints(vec![0.0, 0.5, 1.0]);
///
/// // Sample every 10 seconds
/// let interval = SamplingConfig::FixedInterval { interval: 10.0, offset: 0.0 };
///
/// // Sample at 10 evenly-spaced points
/// let count = SamplingConfig::FixedCount(10);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SamplingConfig {
    /// Single sample at window midpoint
    Midpoint,

    /// Sample at specific relative times (0.0 = window_open, 1.0 = window_close)
    ///
    /// # Example
    /// ```
    /// use brahe::access::SamplingConfig;
    ///
    /// // Sample at start, quarter, middle, three-quarters, and end
    /// let config = SamplingConfig::RelativePoints(vec![0.0, 0.25, 0.5, 0.75, 1.0]);
    /// ```
    RelativePoints(Vec<f64>),

    /// Sample at fixed time intervals (seconds)
    ///
    /// # Example
    /// ```
    /// use brahe::access::SamplingConfig;
    ///
    /// // Sample every 0.1 seconds starting at window open
    /// let config = SamplingConfig::FixedInterval { interval: 0.1, offset: 0.0 };
    /// ```
    FixedInterval {
        /// Time between samples (seconds)
        interval: f64,
        /// Time offset from window_open (seconds)
        offset: f64,
    },

    /// Sample at N evenly-spaced points (including endpoints)
    ///
    /// # Example
    /// ```
    /// use brahe::access::SamplingConfig;
    ///
    /// // Sample at 10 evenly-spaced points
    /// let config = SamplingConfig::FixedCount(10);
    /// ```
    FixedCount(usize),
}

impl SamplingConfig {
    /// Generate sample epochs based on the sampling configuration.
    ///
    /// # Arguments
    /// * `window_open` - Window start time
    /// * `window_close` - Window end time
    ///
    /// # Returns
    /// Vector of sample epochs
    ///
    /// # Panics
    /// - `FixedInterval`: Panics if interval ≤ 0, offset < 0, or no samples generated within window
    /// - `FixedCount`: Panics if count = 0
    /// - `RelativePoints`: Panics if empty or any value outside [0.0, 1.0]
    ///
    /// # Examples
    /// ```
    /// use brahe::access::SamplingConfig;
    /// use brahe::time::{Epoch, TimeSystem};
    ///
    /// let window_open = Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
    /// let window_close = window_open + 3600.0; // 1 hour later
    ///
    /// // Midpoint
    /// let config = SamplingConfig::Midpoint;
    /// let epochs = config.generate_sample_epochs(window_open, window_close);
    /// assert_eq!(epochs.len(), 1);
    /// assert_eq!(epochs[0], window_open + 1800.0);
    ///
    /// // Relative points
    /// let config = SamplingConfig::RelativePoints(vec![0.0, 0.5, 1.0]);
    /// let epochs = config.generate_sample_epochs(window_open, window_close);
    /// assert_eq!(epochs.len(), 3);
    /// assert_eq!(epochs[0], window_open);
    /// assert_eq!(epochs[1], window_open + 1800.0);
    /// assert_eq!(epochs[2], window_close);
    /// ```
    pub fn generate_sample_epochs(&self, window_open: Epoch, window_close: Epoch) -> Vec<Epoch> {
        let duration = window_close - window_open; // seconds

        match self {
            SamplingConfig::Midpoint => {
                vec![window_open + duration * 0.5]
            }

            SamplingConfig::RelativePoints(relative_times) => {
                if relative_times.is_empty() {
                    panic!("SamplingConfig::RelativePoints: relative_times cannot be empty");
                }

                // Validate all points are in [0.0, 1.0]
                for &t in relative_times.iter() {
                    if !(0.0..=1.0).contains(&t) {
                        panic!(
                            "SamplingConfig::RelativePoints: all relative times must be in [0.0, 1.0], got {}",
                            t
                        );
                    }
                }

                relative_times
                    .iter()
                    .map(|&t| window_open + duration * t)
                    .collect()
            }

            SamplingConfig::FixedInterval { interval, offset } => {
                if *interval <= 0.0 {
                    panic!(
                        "SamplingConfig::FixedInterval: interval must be positive, got {}",
                        interval
                    );
                }

                if *offset < 0.0 {
                    panic!(
                        "SamplingConfig::FixedInterval: offset must be non-negative, got {}",
                        offset
                    );
                }

                if *offset > duration {
                    panic!(
                        "SamplingConfig::FixedInterval: offset ({}) exceeds window duration ({})",
                        offset, duration
                    );
                }

                let mut epochs = Vec::new();
                let mut t = *offset; // seconds from window_open

                while t <= duration {
                    epochs.push(window_open + t);
                    t += interval;
                }

                if epochs.is_empty() {
                    panic!(
                        "SamplingConfig::FixedInterval: no samples generated within window (interval too large)"
                    );
                }

                epochs
            }

            SamplingConfig::FixedCount(count) => {
                if *count == 0 {
                    panic!("SamplingConfig::FixedCount: count must be positive, got 0");
                }

                if *count == 1 {
                    return vec![window_open + duration * 0.5];
                }

                // Generate N evenly-spaced points including endpoints
                (0..*count)
                    .map(|i| {
                        let fraction = i as f64 / (*count as f64 - 1.0);
                        window_open + duration * fraction
                    })
                    .collect()
            }
        }
    }
}

// ================================
// AccessProperties Struct
// ================================

/// Properties of an access window.
///
/// This struct contains both core geometric properties (always computed) and
/// extensible additional properties (computed by user-defined property computers).
///
/// # Core Properties
/// - Azimuth angles at window open/close
/// - Min/max elevation angles
/// - Elevation angles at window open/close
/// - Min/max off-nadir angles
/// - Local solar time at midtime
/// - Look direction (left/right)
/// - Ascending/descending pass indicator
/// - Location center coordinates (lon, lat, alt, ECEF)
///
/// # Additional Properties
/// Custom properties can be added via the `additional` HashMap using the
/// `PropertyValue` enum.
///
/// # Examples
/// ```
/// use brahe::access::{AccessProperties, PropertyValue};
/// use brahe::access::LookDirection;
/// use brahe::access::AscDsc;
///
/// let mut props = AccessProperties::new(
///     45.0,   // azimuth_open
///     135.0,  // azimuth_close
///     10.0,   // elevation_min
///     85.0,   // elevation_max
///     12.0,   // elevation_open
///     10.5,   // elevation_close
///     5.0,    // off_nadir_min
///     80.0,   // off_nadir_max
///     43200.0, // local_time (noon)
///     LookDirection::Right,
///     AscDsc::Ascending,
///     0.0,    // center_lon (degrees)
///     45.0,   // center_lat (degrees)
///     0.0,    // center_alt (meters)
///     [4517.59e3, 4517.59e3, 0.0], // center_ecef
/// );
///
/// // Add custom property
/// props.add_property("doppler_shift".to_string(), PropertyValue::Scalar(2500.0));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessProperties {
    // ===== Core geometric properties (always present) =====
    /// Azimuth at window open (degrees, 0-360, measured clockwise from North)
    pub azimuth_open: f64,

    /// Azimuth at window close (degrees, 0-360)
    pub azimuth_close: f64,

    /// Minimum elevation angle during access (degrees, above horizon)
    pub elevation_min: f64,

    /// Maximum elevation angle during access (degrees, typically at midtime)
    pub elevation_max: f64,

    /// Elevation angle at window open (degrees, above horizon)
    pub elevation_open: f64,

    /// Elevation angle at window close (degrees, above horizon)
    pub elevation_close: f64,

    /// Minimum off-nadir angle during access (degrees, typically at midtime)
    pub off_nadir_min: f64,

    /// Maximum off-nadir angle during access (degrees, typically at endpoints)
    pub off_nadir_max: f64,

    /// Local solar time at window midtime (seconds since midnight, 0-86400)
    pub local_time: f64,

    /// Look direction (Left or Right)
    pub look_direction: LookDirection,

    /// Ascending or descending pass
    pub asc_dsc: AscDsc,

    // ===== Location coordinates (for plotting and analysis) =====
    /// Location center longitude (degrees, -180 to 180)
    pub center_lon: f64,

    /// Location center latitude (degrees, -90 to 90)
    pub center_lat: f64,

    /// Location center altitude (meters above WGS84 ellipsoid)
    pub center_alt: f64,

    /// Location center ECEF coordinates [x, y, z] (meters)
    pub center_ecef: [f64; 3],

    // ===== Extensible properties (user-defined) =====
    /// Additional custom properties
    #[serde(default)]
    pub additional: HashMap<String, PropertyValue>,
}

impl AccessProperties {
    /// Create AccessProperties with core properties only.
    ///
    /// # Arguments
    /// * `azimuth_open` - Azimuth at window open (degrees, 0-360)
    /// * `azimuth_close` - Azimuth at window close (degrees, 0-360)
    /// * `elevation_min` - Minimum elevation angle (degrees)
    /// * `elevation_max` - Maximum elevation angle (degrees)
    /// * `elevation_open` - Elevation at window open (degrees)
    /// * `elevation_close` - Elevation at window close (degrees)
    /// * `off_nadir_min` - Minimum off-nadir angle (degrees)
    /// * `off_nadir_max` - Maximum off-nadir angle (degrees)
    /// * `local_time` - Local solar time at midtime (seconds since midnight)
    /// * `look_direction` - Look direction (Left or Right)
    /// * `asc_dsc` - Ascending or descending pass
    /// * `center_lon` - Location longitude (degrees)
    /// * `center_lat` - Location latitude (degrees)
    /// * `center_alt` - Location altitude (meters)
    /// * `center_ecef` - Location ECEF coordinates [x, y, z] (meters)
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        azimuth_open: f64,
        azimuth_close: f64,
        elevation_min: f64,
        elevation_max: f64,
        elevation_open: f64,
        elevation_close: f64,
        off_nadir_min: f64,
        off_nadir_max: f64,
        local_time: f64,
        look_direction: LookDirection,
        asc_dsc: AscDsc,
        center_lon: f64,
        center_lat: f64,
        center_alt: f64,
        center_ecef: [f64; 3],
    ) -> Self {
        Self {
            azimuth_open,
            azimuth_close,
            elevation_min,
            elevation_max,
            elevation_open,
            elevation_close,
            off_nadir_min,
            off_nadir_max,
            local_time,
            look_direction,
            asc_dsc,
            center_lon,
            center_lat,
            center_alt,
            center_ecef,
            additional: HashMap::new(),
        }
    }

    /// Add a custom property.
    ///
    /// # Arguments
    /// * `key` - Property name
    /// * `value` - Property value
    pub fn add_property(&mut self, key: String, value: PropertyValue) {
        self.additional.insert(key, value);
    }

    /// Get a custom property.
    ///
    /// # Arguments
    /// * `key` - Property name
    ///
    /// # Returns
    /// Reference to property value if it exists, None otherwise
    pub fn get_property(&self, key: &str) -> Option<&PropertyValue> {
        self.additional.get(key)
    }
}

// ================================
// AccessPropertyComputer Trait
// ================================

/// Trait for computing additional access properties.
///
/// Implement this trait to add custom property calculations to access windows.
/// The compute method is called once per access window after core properties
/// are calculated. The sampling configuration determines how many satellite
/// states are provided to the compute method.
///
/// # Examples
/// ```no_run
/// use brahe::access::{AccessPropertyComputer, AccessWindow, PropertyValue, SamplingConfig};
/// use brahe::utils::BraheError;
/// use std::collections::HashMap;
/// use nalgebra::Vector3;
///
/// struct DopplerComputer;
///
/// impl AccessPropertyComputer for DopplerComputer {
///     fn sampling_config(&self) -> SamplingConfig {
///         // Sample every 0.1 seconds
///         SamplingConfig::FixedInterval { interval: 0.1 / 86400.0, offset: 0.0 }
///     }
///
///     fn compute(
///         &self,
///         window: &AccessWindow,
///         sample_epochs: &[f64],
///         sample_states_ecef: &[nalgebra::SVector<f64, 6>],
///         location_ecef: &Vector3<f64>,
///         location_geodetic: &Vector3<f64>,
///     ) -> Result<HashMap<String, PropertyValue>, BraheError> {
///         let mut props = HashMap::new();
///
///         // Compute Doppler shift at each sample point
///         let doppler_values: Vec<f64> = sample_states_ecef.iter().map(|state| {
///             // ... compute Doppler shift from state and location ...
///             2500.0  // Example value
///         }).collect();
///
///         // Convert to relative times (seconds from window open)
///         let relative_times: Vec<f64> = sample_epochs.iter()
///             .map(|&epoch| (epoch - window.window_open.mjd()) * 86400.0)
///             .collect();
///
///         props.insert("doppler_shift".to_string(), PropertyValue::TimeSeries {
///             times: relative_times,
///             values: doppler_values,
///         });
///         Ok(props)
///     }
///
///     fn property_names(&self) -> Vec<String> {
///         vec!["doppler_shift".to_string()]
///     }
/// }
/// ```
pub trait AccessPropertyComputer: Send + Sync {
    /// Return the sampling configuration for this property computer.
    ///
    /// The sampling configuration determines how satellite states are sampled
    /// during the access window. The sampled states are then provided to the
    /// compute method.
    ///
    /// # Returns
    /// The sampling configuration to use for this property computer
    fn sampling_config(&self) -> SamplingConfig;

    /// Compute additional properties for an access window.
    ///
    /// This method receives pre-sampled satellite states based on the sampling
    /// configuration returned by `sampling_config()`. The number of samples
    /// corresponds to the sampling strategy used.
    ///
    /// # Arguments
    /// * `window` - The access window (contains times and core properties)
    /// * `sample_epochs` - Sample epochs in MJD (Modified Julian Date)
    /// * `sample_states_ecef` - ECEF states [x,y,z,vx,vy,vz] at each sample epoch (m, m/s)
    /// * `location_ecef` - Location ECEF position [x, y, z] (meters)
    /// * `location_geodetic` - Location geodetic coordinates [lon, lat, alt] (radians, meters)
    ///
    /// # Returns
    /// HashMap of property name -> PropertyValue
    ///
    /// # Notes
    /// - For single-point sampling (e.g., Midpoint), arrays will have length 1
    /// - For time-series sampling, use PropertyValue::TimeSeries with relative times
    /// - Relative times should be in seconds from window_open: (epoch - window_open.mjd()) * 86400.0
    /// - The return type is automatically detected: single sample -> Scalar/Vector, multiple -> TimeSeries
    fn compute(
        &self,
        window: &AccessWindow,
        sample_epochs: &[f64],
        sample_states_ecef: &[nalgebra::SVector<f64, 6>],
        location_ecef: &nalgebra::Vector3<f64>,
        location_geodetic: &nalgebra::Vector3<f64>,
    ) -> Result<HashMap<String, PropertyValue>, BraheError>;

    /// Names of properties this computer will produce.
    ///
    /// Used for documentation and validation.
    fn property_names(&self) -> Vec<String>;
}

// Core property computation functions are now in the geometry module
// and are re-exported from the access module for convenience.

// ================================
// Built-in Property Computers
// ================================

/// Computes Doppler shift for uplink and/or downlink communications.
///
/// This property computer calculates Doppler frequency shifts caused by relative
/// motion between the satellite and ground station. It supports separate uplink
/// and downlink frequency configurations.
///
/// # Physics
///
/// - **Uplink Doppler**: Δf = f₀ × v_los / (c - v_los)
///   - Ground station pre-compensates transmit frequency so satellite receives design frequency
/// - **Downlink Doppler**: Δf = -f₀ × v_los / c
///   - Ground station adjusts receive frequency to match Doppler-shifted spacecraft transmission
///
/// where v_los is the line-of-sight velocity (positive = receding, negative = approaching)
///
/// # Examples
///
/// ```
/// use brahe::access::{DopplerComputer, SamplingConfig};
///
/// // S-band uplink (2.2 GHz) and X-band downlink (8.4 GHz)
/// let computer = DopplerComputer::new(
///     Some(2.2e9),  // uplink frequency (Hz)
///     Some(8.4e9),  // downlink frequency (Hz)
///     SamplingConfig::FixedInterval { interval: 0.1 / 86400.0, offset: 0.0 }
/// );
///
/// // Downlink only
/// let downlink_only = DopplerComputer::new(
///     None,
///     Some(8.4e9),
///     SamplingConfig::Midpoint
/// );
/// ```
#[derive(Clone)]
pub struct DopplerComputer {
    /// Uplink frequency in Hz (optional)
    pub uplink_frequency: Option<f64>,
    /// Downlink frequency in Hz (optional)
    pub downlink_frequency: Option<f64>,
    /// Sampling configuration for time-series computation
    pub sampling_config: SamplingConfig,
}

impl DopplerComputer {
    /// Create a new Doppler computer.
    ///
    /// # Arguments
    ///
    /// * `uplink_frequency` - Optional uplink frequency in Hz
    /// * `downlink_frequency` - Optional downlink frequency in Hz
    /// * `sampling_config` - Sampling configuration for the access window
    ///
    /// # Returns
    ///
    /// New DopplerComputer instance
    ///
    /// # Notes
    ///
    /// At least one frequency (uplink or downlink) must be specified.
    pub fn new(
        uplink_frequency: Option<f64>,
        downlink_frequency: Option<f64>,
        sampling_config: SamplingConfig,
    ) -> Self {
        Self {
            uplink_frequency,
            downlink_frequency,
            sampling_config,
        }
    }
}

impl AccessPropertyComputer for DopplerComputer {
    fn sampling_config(&self) -> SamplingConfig {
        self.sampling_config.clone()
    }

    fn compute(
        &self,
        window: &AccessWindow,
        sample_epochs: &[f64],
        sample_states_ecef: &[nalgebra::SVector<f64, 6>],
        location_ecef: &nalgebra::Vector3<f64>,
        _location_geodetic: &nalgebra::Vector3<f64>,
    ) -> Result<HashMap<String, PropertyValue>, BraheError> {
        let mut props = HashMap::new();

        // Compute line-of-sight velocities at each sample
        let v_los_values: Vec<f64> = sample_states_ecef
            .iter()
            .map(|state| {
                let sat_pos = state.fixed_rows::<3>(0);
                let sat_vel = state.fixed_rows::<3>(3);

                // Line-of-sight vector (from ground station to satellite)
                let los_vec = sat_pos - location_ecef;
                let los_unit = los_vec.normalize();

                // Line-of-sight velocity (positive = receding, negative = approaching)
                sat_vel.dot(&los_unit)
            })
            .collect();

        // Convert to relative times (seconds from window open)
        let relative_times: Vec<f64> = sample_epochs
            .iter()
            .map(|&epoch| (epoch - window.window_open.mjd()) * 86400.0)
            .collect();

        // Compute uplink Doppler if frequency specified
        if let Some(f_uplink) = self.uplink_frequency {
            let doppler_uplink: Vec<f64> = v_los_values
                .iter()
                .map(|&v_los| f_uplink * v_los / (crate::constants::C_LIGHT - v_los))
                .collect();

            let value = if doppler_uplink.len() == 1 {
                PropertyValue::Scalar(doppler_uplink[0])
            } else {
                PropertyValue::TimeSeries {
                    times: relative_times.clone(),
                    values: doppler_uplink,
                }
            };

            props.insert("doppler_uplink".to_string(), value);
        }

        // Compute downlink Doppler if frequency specified
        if let Some(f_downlink) = self.downlink_frequency {
            let doppler_downlink: Vec<f64> = v_los_values
                .iter()
                .map(|&v_los| -f_downlink * v_los / crate::constants::C_LIGHT)
                .collect();

            let value = if doppler_downlink.len() == 1 {
                PropertyValue::Scalar(doppler_downlink[0])
            } else {
                PropertyValue::TimeSeries {
                    times: relative_times,
                    values: doppler_downlink,
                }
            };

            props.insert("doppler_downlink".to_string(), value);
        }

        Ok(props)
    }

    fn property_names(&self) -> Vec<String> {
        let mut names = Vec::new();
        if self.uplink_frequency.is_some() {
            names.push("doppler_uplink".to_string());
        }
        if self.downlink_frequency.is_some() {
            names.push("doppler_downlink".to_string());
        }
        names
    }
}

/// Computes range (distance) between satellite and ground station.
///
/// This property computer calculates the instantaneous slant range from the
/// ground station to the satellite at each sample point.
///
/// # Examples
///
/// ```
/// use brahe::access::{RangeComputer, SamplingConfig};
///
/// // Compute range every second
/// let computer = RangeComputer::new(
///     SamplingConfig::FixedInterval { interval: 1.0 / 86400.0, offset: 0.0 }
/// );
/// ```
#[derive(Clone)]
pub struct RangeComputer {
    /// Sampling configuration for time-series computation
    pub sampling_config: SamplingConfig,
}

impl RangeComputer {
    /// Create a new range computer.
    ///
    /// # Arguments
    ///
    /// * `sampling_config` - Sampling configuration for the access window
    ///
    /// # Returns
    ///
    /// New RangeComputer instance
    pub fn new(sampling_config: SamplingConfig) -> Self {
        Self { sampling_config }
    }
}

impl AccessPropertyComputer for RangeComputer {
    fn sampling_config(&self) -> SamplingConfig {
        self.sampling_config.clone()
    }

    fn compute(
        &self,
        window: &AccessWindow,
        sample_epochs: &[f64],
        sample_states_ecef: &[nalgebra::SVector<f64, 6>],
        location_ecef: &nalgebra::Vector3<f64>,
        _location_geodetic: &nalgebra::Vector3<f64>,
    ) -> Result<HashMap<String, PropertyValue>, BraheError> {
        let mut props = HashMap::new();

        // Compute range at each sample
        let range_values: Vec<f64> = sample_states_ecef
            .iter()
            .map(|state| {
                let sat_pos = state.fixed_rows::<3>(0);
                (sat_pos - location_ecef).norm()
            })
            .collect();

        // Convert to relative times (seconds from window open)
        let relative_times: Vec<f64> = sample_epochs
            .iter()
            .map(|&epoch| (epoch - window.window_open.mjd()) * 86400.0)
            .collect();

        let value = if range_values.len() == 1 {
            PropertyValue::Scalar(range_values[0])
        } else {
            PropertyValue::TimeSeries {
                times: relative_times,
                values: range_values,
            }
        };

        props.insert("range".to_string(), value);

        Ok(props)
    }

    fn property_names(&self) -> Vec<String> {
        vec!["range".to_string()]
    }
}

/// Computes range rate (line-of-sight velocity) between satellite and ground station.
///
/// This property computer calculates the instantaneous rate of change of range
/// (also known as radial velocity or line-of-sight velocity) at each sample point.
///
/// # Sign Convention
///
/// - Positive range rate: satellite moving away from ground station (receding)
/// - Negative range rate: satellite moving toward ground station (approaching)
///
/// # Examples
///
/// ```
/// use brahe::access::{RangeRateComputer, SamplingConfig};
///
/// // Compute range rate at midpoint
/// let computer = RangeRateComputer::new(SamplingConfig::Midpoint);
///
/// // Compute range rate time series
/// let computer = RangeRateComputer::new(
///     SamplingConfig::FixedCount(50)  // 50 evenly-spaced points
/// );
/// ```
#[derive(Clone)]
pub struct RangeRateComputer {
    /// Sampling configuration for time-series computation
    pub sampling_config: SamplingConfig,
}

impl RangeRateComputer {
    /// Create a new range rate computer.
    ///
    /// # Arguments
    ///
    /// * `sampling_config` - Sampling configuration for the access window
    ///
    /// # Returns
    ///
    /// New RangeRateComputer instance
    pub fn new(sampling_config: SamplingConfig) -> Self {
        Self { sampling_config }
    }
}

impl AccessPropertyComputer for RangeRateComputer {
    fn sampling_config(&self) -> SamplingConfig {
        self.sampling_config.clone()
    }

    fn compute(
        &self,
        window: &AccessWindow,
        sample_epochs: &[f64],
        sample_states_ecef: &[nalgebra::SVector<f64, 6>],
        location_ecef: &nalgebra::Vector3<f64>,
        _location_geodetic: &nalgebra::Vector3<f64>,
    ) -> Result<HashMap<String, PropertyValue>, BraheError> {
        let mut props = HashMap::new();

        // Compute range rate at each sample
        let range_rate_values: Vec<f64> = sample_states_ecef
            .iter()
            .map(|state| {
                let sat_pos = state.fixed_rows::<3>(0);
                let sat_vel = state.fixed_rows::<3>(3);

                // Line-of-sight vector (from ground station to satellite)
                let los_vec = sat_pos - location_ecef;
                let los_unit = los_vec.normalize();

                // Range rate (line-of-sight velocity)
                sat_vel.dot(&los_unit)
            })
            .collect();

        // Convert to relative times (seconds from window open)
        let relative_times: Vec<f64> = sample_epochs
            .iter()
            .map(|&epoch| (epoch - window.window_open.mjd()) * 86400.0)
            .collect();

        let value = if range_rate_values.len() == 1 {
            PropertyValue::Scalar(range_rate_values[0])
        } else {
            PropertyValue::TimeSeries {
                times: relative_times,
                values: range_rate_values,
            }
        };

        props.insert("range_rate".to_string(), value);

        Ok(props)
    }

    fn property_names(&self) -> Vec<String> {
        vec!["range_rate".to_string()]
    }
}

// ================================
// Tests
// ================================

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use nalgebra::{Vector3, Vector6};

    use crate::constants::AngleFormat;
    use crate::coordinates::position_geodetic_to_ecef;
    use crate::propagators::KeplerianPropagator;
    use crate::propagators::traits::SOrbitStateProvider;
    use crate::time::{Epoch, TimeSystem};
    use crate::utils::state_providers::DOrbitStateProvider;
    use crate::utils::testing::setup_global_test_eop;

    use super::super::geometry::{
        compute_asc_dsc, compute_azimuth, compute_elevation, compute_local_time,
        compute_look_direction, compute_off_nadir,
    };

    #[test]
    fn test_property_value_serialization() {
        // Scalar
        let scalar = PropertyValue::Scalar(42.0);
        let json = serde_json::to_string(&scalar).unwrap();
        let deserialized: PropertyValue = serde_json::from_str(&json).unwrap();
        assert_eq!(scalar, deserialized);

        // Vector
        let vector = PropertyValue::Vector(vec![1.0, 2.0, 3.0]);
        let json = serde_json::to_string(&vector).unwrap();
        let deserialized: PropertyValue = serde_json::from_str(&json).unwrap();
        assert_eq!(vector, deserialized);

        // TimeSeries
        let ts = PropertyValue::TimeSeries {
            times: vec![0.0, 10.0, 20.0],
            values: vec![1.0, 2.0, 3.0],
        };
        let json = serde_json::to_string(&ts).unwrap();
        let deserialized: PropertyValue = serde_json::from_str(&json).unwrap();
        assert_eq!(ts, deserialized);

        // Boolean
        let boolean = PropertyValue::Boolean(true);
        let json = serde_json::to_string(&boolean).unwrap();
        let deserialized: PropertyValue = serde_json::from_str(&json).unwrap();
        assert_eq!(boolean, deserialized);

        // String
        let string = PropertyValue::String("test".to_string());
        let json = serde_json::to_string(&string).unwrap();
        let deserialized: PropertyValue = serde_json::from_str(&json).unwrap();
        assert_eq!(string, deserialized);
    }

    #[test]
    fn test_state_provider_propagator() {
        use crate::trajectories::traits::{OrbitFrame, OrbitRepresentation};

        // Initialize EOP for frame conversions
        setup_global_test_eop();

        // Create a Keplerian propagator
        let epoch = Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let elements = Vector6::new(
            7000e3, // a (m)
            0.001,  // e
            0.9,    // i (rad)
            0.0,    // RAAN (rad)
            0.0,    // arg periapsis (rad)
            0.0,    // mean anomaly (rad)
        );
        let prop = KeplerianPropagator::new(
            epoch,
            elements,
            OrbitFrame::ECI,
            OrbitRepresentation::Keplerian,
            Some(AngleFormat::Radians),
            60.0,
        );

        // Use StateProvider trait directly
        let state = prop.state_ecef(epoch).unwrap();
        assert_eq!(state.len(), 6);

        // State should be non-zero
        assert!(state.norm() > 0.0);
    }

    #[test]
    fn test_state_provider_orbit_trajectory() {
        use crate::trajectories::sorbit_trajectory::SOrbitTrajectory;
        use crate::trajectories::traits::{OrbitFrame, OrbitRepresentation, Trajectory};

        // Initialize EOP for frame conversions
        setup_global_test_eop();

        // Create a trajectory in ECI
        let epoch1 = Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let epoch2 = epoch1 + 60.0;

        let state1 = Vector6::new(7000e3, 0.0, 0.0, 0.0, 7500.0, 0.0);
        let state2 = Vector6::new(7000e3, 100e3, 10e3, 10.0, 7500.0, 100.0);

        let mut traj = SOrbitTrajectory::new(OrbitFrame::ECI, OrbitRepresentation::Cartesian, None);
        traj.add(epoch1, state1);
        traj.add(epoch2, state2);

        // Use StateProvider trait directly (now implemented by SOrbitTrajectory)
        let mid_epoch = epoch1 + 30.0;
        let state = traj.state_ecef(mid_epoch).unwrap();
        assert_eq!(state.len(), 6);
    }

    #[test]
    fn test_access_properties_creation() {
        let props = AccessProperties::new(
            45.0,
            135.0,
            10.0,
            85.0,
            12.0,
            10.5,
            5.0,
            80.0,
            43200.0,
            LookDirection::Right,
            AscDsc::Ascending,
            0.0,
            45.0,
            0.0,
            [4517.59e3, 4517.59e3, 0.0],
        );

        assert_eq!(props.azimuth_open, 45.0);
        assert_eq!(props.azimuth_close, 135.0);
        assert_eq!(props.elevation_min, 10.0);
        assert_eq!(props.elevation_max, 85.0);
        assert_eq!(props.elevation_open, 12.0);
        assert_eq!(props.elevation_close, 10.5);
        assert_eq!(props.off_nadir_min, 5.0);
        assert_eq!(props.off_nadir_max, 80.0);
        assert_eq!(props.local_time, 43200.0);
        assert_eq!(props.look_direction, LookDirection::Right);
        assert_eq!(props.asc_dsc, AscDsc::Ascending);
        assert_eq!(props.center_lon, 0.0);
        assert_eq!(props.center_lat, 45.0);
        assert_eq!(props.center_alt, 0.0);
        assert_eq!(props.center_ecef, [4517.59e3, 4517.59e3, 0.0]);
        assert!(props.additional.is_empty());
    }

    #[test]
    fn test_access_properties_additional() {
        let mut props = AccessProperties::new(
            45.0,
            135.0,
            10.0,
            85.0,
            12.0,
            10.5,
            5.0,
            80.0,
            43200.0,
            LookDirection::Right,
            AscDsc::Ascending,
            0.0,
            45.0,
            0.0,
            [4517.59e3, 4517.59e3, 0.0],
        );

        // Add property
        props.add_property("doppler".to_string(), PropertyValue::Scalar(2500.0));

        // Get property
        let doppler = props.get_property("doppler").unwrap();
        match doppler {
            PropertyValue::Scalar(val) => assert_eq!(*val, 2500.0),
            _ => panic!("Expected Scalar"),
        }

        // Non-existent property
        assert!(props.get_property("nonexistent").is_none());
    }

    #[test]
    fn test_compute_azimuth_elevation() {
        use crate::coordinates::position_geodetic_to_ecef;

        // Location: (0° lon, 45° lat, 0 alt)
        let loc_geodetic = Vector3::new(0.0, 45.0_f64.to_radians(), 0.0);
        let loc_ecef = position_geodetic_to_ecef(loc_geodetic, AngleFormat::Radians).unwrap();

        // Satellite at high altitude (not directly north, just higher than location)
        let sat_ecef = loc_ecef + Vector3::new(0.0, 500e3, 500e3);

        let azimuth = compute_azimuth(&sat_ecef, &loc_ecef);
        let elevation = compute_elevation(&sat_ecef, &loc_ecef);

        // Just verify azimuth is in valid range
        assert!((0.0..=360.0).contains(&azimuth));

        // Elevation should be positive (satellite is above location)
        assert!(elevation > 0.0);
        assert!(elevation < 90.0);
    }

    #[test]
    fn test_compute_off_nadir() {
        // Satellite at altitude
        let sat_ecef = Vector3::new(7000e3, 0.0, 0.0);

        // Location on Earth surface
        let loc_geodetic = Vector3::new(0.0, 0.0, 0.0);
        let loc_ecef = position_geodetic_to_ecef(loc_geodetic, AngleFormat::Radians).unwrap();

        let off_nadir = compute_off_nadir(&sat_ecef, &loc_ecef);

        // Off-nadir should be reasonable (0-90 degrees for visible targets)
        assert!(off_nadir >= 0.0);
        assert!(off_nadir <= 180.0);
    }

    #[test]
    fn test_compute_local_time() {
        // Initialize EOP for UT1 time conversions
        setup_global_test_eop();

        // Location at 0° longitude
        let loc_geodetic = Vector3::new(0.0, 0.0, 0.0);

        let epoch = Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);

        let local_time = compute_local_time(&epoch, &loc_geodetic);

        // Should be in range 0-86400 seconds
        assert!(local_time >= 0.0);
        assert!(local_time <= 86400.0);
    }

    #[test]
    fn test_compute_asc_dsc() {
        // Ascending: positive z-velocity in inertial frame
        let state_ascending = Vector6::new(
            7000e3, 0.0, 0.0, // position
            0.0, 7500.0, 100.0, // velocity (positive z)
        );

        let asc_dsc = compute_asc_dsc(&state_ascending);
        assert_eq!(asc_dsc, AscDsc::Ascending);

        // Descending: negative z-velocity
        let state_descending = Vector6::new(
            7000e3, 0.0, 0.0, // position
            0.0, 7500.0, -100.0, // velocity (negative z)
        );

        let asc_dsc = compute_asc_dsc(&state_descending);
        assert_eq!(asc_dsc, AscDsc::Descending);
    }

    #[test]
    fn test_compute_look_direction() {
        // Satellite state
        let sat_state = Vector6::new(
            7000e3, 0.0, 0.0, // position
            0.0, 7500.0, 0.0, // velocity (moving in +y direction)
        );

        // Location to the right (negative x)
        let loc_right = Vector3::new(6000e3, 0.0, 0.0);
        let look_dir = compute_look_direction(&sat_state, &loc_right);
        // This test is geometry-dependent; just check it returns a value
        assert!(look_dir == LookDirection::Left || look_dir == LookDirection::Right);
    }

    // Example property computer implementation
    struct TestPropertyComputer;

    impl AccessPropertyComputer for TestPropertyComputer {
        fn sampling_config(&self) -> SamplingConfig {
            SamplingConfig::Midpoint
        }

        fn compute(
            &self,
            _window: &AccessWindow,
            _sample_epochs: &[f64],
            sample_states_ecef: &[nalgebra::SVector<f64, 6>],
            _location_ecef: &nalgebra::Vector3<f64>,
            _location_geodetic: &nalgebra::Vector3<f64>,
        ) -> Result<HashMap<String, PropertyValue>, BraheError> {
            let mut props = HashMap::new();

            // Use first (and only) sample for midpoint configuration
            let state = &sample_states_ecef[0];

            // Compute a simple property (altitude)
            let altitude = state.fixed_rows::<3>(0).norm() - 6371e3;
            props.insert(
                "altitude_km".to_string(),
                PropertyValue::Scalar(altitude / 1e3),
            );

            Ok(props)
        }

        fn property_names(&self) -> Vec<String> {
            vec!["altitude_km".to_string()]
        }
    }

    #[test]
    fn test_property_computer() {
        use crate::access::{AccessibleLocation, PointLocation};
        use crate::trajectories::traits::{OrbitFrame, OrbitRepresentation};

        // Initialize EOP for frame conversions
        setup_global_test_eop();

        // Create test data
        let epoch1 = Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let epoch2 = epoch1 + 120.0;

        // Create a minimal AccessWindow for testing
        let window = crate::access::AccessWindow {
            window_open: epoch1,
            window_close: epoch2,
            location_name: None,
            location_id: None,
            location_uuid: None,
            satellite_name: None,
            satellite_id: None,
            satellite_uuid: None,
            name: None,
            id: None,
            uuid: None,
            properties: crate::access::AccessProperties::new(
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                crate::access::LookDirection::Either,
                crate::access::AscDsc::Either,
                0.0,
                45.0,
                0.0,
                [4517.59e3, 4517.59e3, 0.0],
            ),
        };

        let elements = Vector6::new(7000e3, 0.001, 0.9, 0.0, 0.0, 0.0);
        let prop = KeplerianPropagator::new(
            epoch1,
            elements,
            OrbitFrame::ECI,
            OrbitRepresentation::Keplerian,
            Some(AngleFormat::Radians),
            60.0,
        );

        let location = PointLocation::new(0.0, 45.0, 0.0);
        let location_ecef = location.center_ecef();
        let location_geodetic = Vector3::new(0.0_f64.to_radians(), 45.0_f64.to_radians(), 0.0);

        // Get sampling configuration and generate sample epochs
        let computer = TestPropertyComputer;
        let sampling_config = computer.sampling_config();
        let sample_epochs =
            sampling_config.generate_sample_epochs(window.window_open, window.window_close);

        // Get states at sample epochs using StateProvider trait
        let sample_states: Vec<nalgebra::SVector<f64, 6>> = sample_epochs
            .iter()
            .map(|&epoch| prop.state_ecef(epoch).unwrap())
            .collect();

        // Convert epochs to MJD for property computer interface
        let sample_epochs_mjd: Vec<f64> = sample_epochs.iter().map(|e| e.mjd()).collect();

        // Compute properties with sampled states
        let props = computer
            .compute(
                &window,
                &sample_epochs_mjd,
                &sample_states,
                &location_ecef,
                &location_geodetic,
            )
            .unwrap();

        // Check property exists
        assert!(props.contains_key("altitude_km"));

        // Check property names
        assert_eq!(computer.property_names(), vec!["altitude_km"]);
    }

    // ================================
    // SamplingConfig Tests
    // ================================

    #[test]
    fn test_sampling_config_midpoint() {
        let config = SamplingConfig::Midpoint;
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0; // 1 hour later

        let epochs = config.generate_sample_epochs(window_open, window_close);

        assert_eq!(epochs.len(), 1);
        assert_eq!(epochs[0], window_open + 1800.0); // Midpoint
    }

    #[test]
    fn test_sampling_config_relative_points() {
        let config = SamplingConfig::RelativePoints(vec![0.0, 0.5, 1.0]);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0; // 1 hour later

        let epochs = config.generate_sample_epochs(window_open, window_close);

        assert_eq!(epochs.len(), 3);
        assert_eq!(epochs[0], window_open); // Start
        assert_eq!(epochs[1], window_open + 1800.0); // Middle
        assert_eq!(epochs[2], window_close); // End
    }

    #[test]
    #[should_panic(expected = "all relative times must be in [0.0, 1.0]")]
    fn test_sampling_config_relative_points_out_of_bounds_negative() {
        // Values outside [0, 1] should panic
        let config = SamplingConfig::RelativePoints(vec![-0.5, 0.0, 0.5]);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    #[should_panic(expected = "all relative times must be in [0.0, 1.0]")]
    fn test_sampling_config_relative_points_out_of_bounds_positive() {
        // Values outside [0, 1] should panic
        let config = SamplingConfig::RelativePoints(vec![0.0, 0.5, 1.5]);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    #[should_panic(expected = "relative_times cannot be empty")]
    fn test_sampling_config_relative_points_empty() {
        // Empty vector should panic
        let config = SamplingConfig::RelativePoints(vec![]);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    fn test_sampling_config_fixed_interval() {
        let config = SamplingConfig::FixedInterval {
            interval: 600.0, // 10 minutes in seconds
            offset: 0.0,
        };
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3000.0; // 50 minutes later

        let epochs = config.generate_sample_epochs(window_open, window_close);

        // Should have samples at 0, 600, 1200, 1800, 2400, 3000 seconds from open
        assert_eq!(epochs.len(), 6);
        assert_eq!(epochs[0], window_open);
        assert_eq!(epochs[1], window_open + 600.0);
        assert_eq!(epochs[2], window_open + 1200.0);
        assert_eq!(epochs[3], window_open + 1800.0);
        assert_eq!(epochs[4], window_open + 2400.0);
        assert_eq!(epochs[5], window_open + 3000.0);
    }

    #[test]
    fn test_sampling_config_fixed_interval_with_offset() {
        let config = SamplingConfig::FixedInterval {
            interval: 1200.0, // 20 minutes in seconds
            offset: 600.0,    // Start at 10 minutes
        };
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3000.0; // 50 minutes later

        let epochs = config.generate_sample_epochs(window_open, window_close);

        // Should have samples at 600, 1800, 3000 seconds from open
        assert_eq!(epochs.len(), 3);
        assert_eq!(epochs[0], window_open + 600.0);
        assert_eq!(epochs[1], window_open + 1800.0);
        assert_eq!(epochs[2], window_open + 3000.0);
    }

    #[test]
    #[should_panic(expected = "interval must be positive")]
    fn test_sampling_config_fixed_interval_zero() {
        // Zero interval should panic
        let config = SamplingConfig::FixedInterval {
            interval: 0.0,
            offset: 0.0,
        };
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    #[should_panic(expected = "interval must be positive")]
    fn test_sampling_config_fixed_interval_negative() {
        // Negative interval should panic
        let config = SamplingConfig::FixedInterval {
            interval: -0.1,
            offset: 0.0,
        };
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    #[should_panic(expected = "offset must be non-negative")]
    fn test_sampling_config_fixed_interval_negative_offset() {
        // Negative offset should panic
        let config = SamplingConfig::FixedInterval {
            interval: 600.0,
            offset: -100.0,
        };
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    #[should_panic(expected = "offset")]
    fn test_sampling_config_fixed_interval_offset_beyond_window() {
        // If offset is beyond window duration, should panic
        let config = SamplingConfig::FixedInterval {
            interval: 600.0,
            offset: 4000.0, // Offset beyond window duration
        };
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0; // 1 hour = 3600 seconds

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    fn test_sampling_config_fixed_count() {
        let config = SamplingConfig::FixedCount(5);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 2400.0; // 40 minutes

        let epochs = config.generate_sample_epochs(window_open, window_close);

        // 5 evenly-spaced points: 0, 600, 1200, 1800, 2400 seconds
        assert_eq!(epochs.len(), 5);
        assert_eq!(epochs[0], window_open);
        assert_eq!(epochs[1], window_open + 600.0);
        assert_eq!(epochs[2], window_open + 1200.0);
        assert_eq!(epochs[3], window_open + 1800.0);
        assert_eq!(epochs[4], window_open + 2400.0);
    }

    #[test]
    fn test_sampling_config_fixed_count_single() {
        let config = SamplingConfig::FixedCount(1);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        let epochs = config.generate_sample_epochs(window_open, window_close);

        // Single point should be at midpoint
        assert_eq!(epochs.len(), 1);
        assert_eq!(epochs[0], window_open + 1800.0);
    }

    #[test]
    fn test_sampling_config_fixed_count_two() {
        let config = SamplingConfig::FixedCount(2);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        let epochs = config.generate_sample_epochs(window_open, window_close);

        // Two points: start and end
        assert_eq!(epochs.len(), 2);
        assert_eq!(epochs[0], window_open);
        assert_eq!(epochs[1], window_close);
    }

    #[test]
    #[should_panic(expected = "count must be positive")]
    fn test_sampling_config_fixed_count_zero() {
        // Zero count should panic
        let config = SamplingConfig::FixedCount(0);
        let window_open =
            crate::time::Epoch::from_datetime(2024, 1, 1, 12, 0, 0.0, 0.0, TimeSystem::UTC);
        let window_close = window_open + 3600.0;

        config.generate_sample_epochs(window_open, window_close);
    }

    #[test]
    fn test_sampling_config_serialization() {
        // Midpoint
        let config = SamplingConfig::Midpoint;
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: SamplingConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, deserialized);

        // RelativePoints
        let config = SamplingConfig::RelativePoints(vec![0.0, 0.5, 1.0]);
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: SamplingConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, deserialized);

        // FixedInterval
        let config = SamplingConfig::FixedInterval {
            interval: 0.1,
            offset: 0.05,
        };
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: SamplingConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, deserialized);

        // FixedCount
        let config = SamplingConfig::FixedCount(10);
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: SamplingConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, deserialized);
    }

    #[test]
    fn test_doppler_computer_downlink() {
        setup_global_test_eop();

        let computer = DopplerComputer::new(
            None,
            Some(2.2e9), // S-band downlink
            SamplingConfig::Midpoint,
        );

        // Create a simple access window
        let window_open = crate::time::Epoch::from_datetime(
            2024,
            1,
            1,
            0,
            0,
            0.0,
            0.0,
            crate::time::TimeSystem::UTC,
        );
        let window_close = window_open + 60.0; // 1 minute window

        // Satellite approaching station (negative range rate = approaching)
        let sample_epochs = vec![window_open.mjd() + 30.0 / 86400.0]; // midpoint

        let location_ecef = nalgebra::Vector3::new(4000000.0, 1000000.0, 4500000.0);
        let sat_pos = nalgebra::Vector3::new(1000000.0, 2000000.0, 3000000.0);

        // Velocity toward station (approaching)
        let to_station = (location_ecef - sat_pos).normalize();
        let approaching_velocity = to_station * 1000.0; // 1000 m/s toward station

        let sample_states = vec![nalgebra::SVector::<f64, 6>::new(
            sat_pos[0],
            sat_pos[1],
            sat_pos[2],
            approaching_velocity[0],
            approaching_velocity[1],
            approaching_velocity[2],
        )];
        let location_geodetic = nalgebra::Vector3::new(0.0, 0.0, 0.0); // not used

        let temp_window = crate::access::AccessWindow {
            window_open,
            window_close,
            location_name: None,
            location_id: None,
            location_uuid: None,
            satellite_name: None,
            satellite_id: None,
            satellite_uuid: None,
            name: None,
            id: None,
            uuid: None,
            properties: crate::access::AccessProperties::new(
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                crate::access::LookDirection::Either,
                crate::access::AscDsc::Either,
                0.0,
                0.0,
                0.0,
                [0.0, 0.0, 0.0],
            ),
        };

        let result = computer
            .compute(
                &temp_window,
                &sample_epochs,
                &sample_states,
                &location_ecef,
                &location_geodetic,
            )
            .unwrap();

        // Check that doppler_downlink property exists
        assert!(result.contains_key("doppler_downlink"));

        // Verify it's a scalar value (single sample)
        if let PropertyValue::Scalar(doppler) = result.get("doppler_downlink").unwrap() {
            // For approaching satellite, doppler should be positive (frequency increase)
            // Basic sanity check: doppler should be reasonable for typical satellite velocities
            assert!(
                *doppler > 0.0,
                "Doppler should be positive for approaching satellite"
            );
            assert!(
                *doppler < 100000.0,
                "Doppler should be reasonable (<100 kHz)"
            );
        } else {
            panic!("Expected scalar value");
        }
    }

    #[test]
    fn test_doppler_computer_uplink() {
        setup_global_test_eop();

        let computer = DopplerComputer::new(
            Some(2.0e9), // S-band uplink
            None,
            SamplingConfig::Midpoint,
        );

        let window_open = crate::time::Epoch::from_datetime(
            2024,
            1,
            1,
            0,
            0,
            0.0,
            0.0,
            crate::time::TimeSystem::UTC,
        );
        let window_close = window_open + 60.0;

        // Satellite receding from station (positive range rate = receding)
        let sample_epochs = vec![window_open.mjd() + 30.0 / 86400.0];

        let location_ecef = nalgebra::Vector3::new(4000000.0, 1000000.0, 4500000.0);
        let sat_pos = nalgebra::Vector3::new(1000000.0, 2000000.0, 3000000.0);

        // Velocity away from station (receding)
        let from_station = (sat_pos - location_ecef).normalize();
        let receding_velocity = from_station * 1000.0; // 1000 m/s away from station

        let sample_states = vec![nalgebra::SVector::<f64, 6>::new(
            sat_pos[0],
            sat_pos[1],
            sat_pos[2],
            receding_velocity[0],
            receding_velocity[1],
            receding_velocity[2],
        )];
        let location_geodetic = nalgebra::Vector3::new(0.0, 0.0, 0.0);

        let temp_window = crate::access::AccessWindow {
            window_open,
            window_close,
            location_name: None,
            location_id: None,
            location_uuid: None,
            satellite_name: None,
            satellite_id: None,
            satellite_uuid: None,
            name: None,
            id: None,
            uuid: None,
            properties: crate::access::AccessProperties::new(
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                crate::access::LookDirection::Either,
                crate::access::AscDsc::Either,
                0.0,
                0.0,
                0.0,
                [0.0, 0.0, 0.0],
            ),
        };

        let result = computer
            .compute(
                &temp_window,
                &sample_epochs,
                &sample_states,
                &location_ecef,
                &location_geodetic,
            )
            .unwrap();

        assert!(result.contains_key("doppler_uplink"));

        if let PropertyValue::Scalar(doppler) = result.get("doppler_uplink").unwrap() {
            // For receding satellite, uplink pre-compensation should be positive
            assert!(
                *doppler > 0.0,
                "Uplink doppler should be positive for receding satellite"
            );
            assert!(*doppler < 100000.0, "Doppler should be reasonable");
        } else {
            panic!("Expected scalar value");
        }
    }

    #[test]
    fn test_doppler_computer_both_frequencies() {
        setup_global_test_eop();

        let computer = DopplerComputer::new(
            Some(2.0e9), // uplink
            Some(2.2e9), // downlink
            SamplingConfig::FixedCount(3),
        );

        let window_open = crate::time::Epoch::from_datetime(
            2024,
            1,
            1,
            0,
            0,
            0.0,
            0.0,
            crate::time::TimeSystem::UTC,
        );
        let window_close: crate::time::Epoch = window_open + 120.0; // 2 minutes

        let config = SamplingConfig::FixedCount(3);
        let sample_epochs = config.generate_sample_epochs(window_open, window_close);

        let sample_states = vec![
            nalgebra::SVector::<f64, 6>::new(
                1000000.0, 2000000.0, 3000000.0, -1000.0, -500.0, -200.0,
            ),
            nalgebra::SVector::<f64, 6>::new(
                1010000.0, 2005000.0, 3002000.0, -800.0, -400.0, -150.0,
            ),
            nalgebra::SVector::<f64, 6>::new(
                1020000.0, 2010000.0, 3004000.0, -600.0, -300.0, -100.0,
            ),
        ];

        let location_ecef = nalgebra::Vector3::new(4000000.0, 1000000.0, 4500000.0);
        let location_geodetic = nalgebra::Vector3::new(0.0, 0.0, 0.0);

        // Convert epochs to MJD for property computer interface
        let sample_epochs_mjd: Vec<f64> = sample_epochs.iter().map(|e| e.mjd()).collect();

        let temp_window = crate::access::AccessWindow {
            window_open,
            window_close,
            location_name: None,
            location_id: None,
            location_uuid: None,
            satellite_name: None,
            satellite_id: None,
            satellite_uuid: None,
            name: None,
            id: None,
            uuid: None,
            properties: crate::access::AccessProperties::new(
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                crate::access::LookDirection::Either,
                crate::access::AscDsc::Either,
                0.0,
                0.0,
                0.0,
                [0.0, 0.0, 0.0],
            ),
        };

        let result = computer
            .compute(
                &temp_window,
                &sample_epochs_mjd,
                &sample_states,
                &location_ecef,
                &location_geodetic,
            )
            .unwrap();

        // Should have both uplink and downlink
        assert!(result.contains_key("doppler_uplink"));
        assert!(result.contains_key("doppler_downlink"));

        // Both should be time series (3 samples)
        match result.get("doppler_uplink").unwrap() {
            PropertyValue::TimeSeries { times, values } => {
                assert_eq!(times.len(), 3);
                assert_eq!(values.len(), 3);
            }
            _ => panic!("Expected time series value"),
        }

        match result.get("doppler_downlink").unwrap() {
            PropertyValue::TimeSeries { times, values } => {
                assert_eq!(times.len(), 3);
                assert_eq!(values.len(), 3);
            }
            _ => panic!("Expected time series value"),
        }
    }

    #[test]
    fn test_range_computer() {
        setup_global_test_eop();

        let computer = RangeComputer::new(SamplingConfig::FixedCount(2));

        let window_open = crate::time::Epoch::from_datetime(
            2024,
            1,
            1,
            0,
            0,
            0.0,
            0.0,
            crate::time::TimeSystem::UTC,
        );
        let window_close: crate::time::Epoch = window_open + 60.0;

        let config = SamplingConfig::FixedCount(2);
        let sample_epochs = config.generate_sample_epochs(window_open, window_close);

        let location_ecef = nalgebra::Vector3::new(4000000.0, 1000000.0, 4500000.0);

        // Two satellite positions at different distances
        let sample_states = vec![
            nalgebra::SVector::<f64, 6>::new(
                location_ecef[0] + 1000000.0,
                location_ecef[1],
                location_ecef[2],
                0.0,
                0.0,
                0.0,
            ),
            nalgebra::SVector::<f64, 6>::new(
                location_ecef[0] + 2000000.0,
                location_ecef[1],
                location_ecef[2],
                0.0,
                0.0,
                0.0,
            ),
        ];

        let location_geodetic = nalgebra::Vector3::new(0.0, 0.0, 0.0);

        // Convert epochs to MJD for property computer interface
        let sample_epochs_mjd: Vec<f64> = sample_epochs.iter().map(|e| e.mjd()).collect();

        let temp_window = crate::access::AccessWindow {
            window_open,
            window_close,
            location_name: None,
            location_id: None,
            location_uuid: None,
            satellite_name: None,
            satellite_id: None,
            satellite_uuid: None,
            name: None,
            id: None,
            uuid: None,
            properties: crate::access::AccessProperties::new(
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                crate::access::LookDirection::Either,
                crate::access::AscDsc::Either,
                0.0,
                0.0,
                0.0,
                [0.0, 0.0, 0.0],
            ),
        };

        let result = computer
            .compute(
                &temp_window,
                &sample_epochs_mjd,
                &sample_states,
                &location_ecef,
                &location_geodetic,
            )
            .unwrap();

        assert!(result.contains_key("range"));

        match result.get("range").unwrap() {
            PropertyValue::TimeSeries { times, values } => {
                assert_eq!(times.len(), 2);
                assert_eq!(values.len(), 2);

                // First range should be ~1000 km
                assert!(
                    (values[0] - 1000000.0).abs() < 1.0,
                    "First range should be ~1000 km"
                );

                // Second range should be ~2000 km
                assert!(
                    (values[1] - 2000000.0).abs() < 1.0,
                    "Second range should be ~2000 km"
                );
            }
            _ => panic!("Expected time series value"),
        }
    }

    #[test]
    fn test_range_rate_computer() {
        setup_global_test_eop();

        let computer = RangeRateComputer::new(SamplingConfig::Midpoint);

        let window_open = crate::time::Epoch::from_datetime(
            2024,
            1,
            1,
            0,
            0,
            0.0,
            0.0,
            crate::time::TimeSystem::UTC,
        );
        let window_close = window_open + 60.0;

        let sample_epochs = vec![window_open.mjd() + 30.0 / 86400.0];

        let location_ecef = nalgebra::Vector3::new(4000000.0, 1000000.0, 4500000.0);

        // Satellite moving directly away from station
        let sat_to_station =
            location_ecef - nalgebra::Vector3::new(1000000.0, 2000000.0, 3000000.0);
        let los_direction = sat_to_station.normalize();

        // Velocity of 1000 m/s in line-of-sight direction (receding)
        let velocity = -los_direction * 1000.0;

        let sample_states = vec![nalgebra::SVector::<f64, 6>::new(
            1000000.0,
            2000000.0,
            3000000.0,
            velocity[0],
            velocity[1],
            velocity[2],
        )];

        let location_geodetic = nalgebra::Vector3::new(0.0, 0.0, 0.0);

        let temp_window = crate::access::AccessWindow {
            window_open,
            window_close,
            location_name: None,
            location_id: None,
            location_uuid: None,
            satellite_name: None,
            satellite_id: None,
            satellite_uuid: None,
            name: None,
            id: None,
            uuid: None,
            properties: crate::access::AccessProperties::new(
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                crate::access::LookDirection::Either,
                crate::access::AscDsc::Either,
                0.0,
                0.0,
                0.0,
                [0.0, 0.0, 0.0],
            ),
        };

        let result = computer
            .compute(
                &temp_window,
                &sample_epochs,
                &sample_states,
                &location_ecef,
                &location_geodetic,
            )
            .unwrap();

        assert!(result.contains_key("range_rate"));

        if let PropertyValue::Scalar(range_rate) = result.get("range_rate").unwrap() {
            // Should be ~1000 m/s (receding is positive)
            assert!(
                (*range_rate - 1000.0).abs() < 1.0,
                "Range rate should be ~1000 m/s, got {}",
                range_rate
            );
        } else {
            panic!("Expected scalar value");
        }
    }
}