lox-space 0.1.0-alpha.48

The Lox toolbox for space mission analysis and design
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
// SPDX-FileCopyrightText: 2026 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0

use std::collections::{HashMap, HashSet};

use crate::analysis::assets::{AssetId, ConstellationId, DynScenario, GroundStation, Spacecraft};
use crate::analysis::imaging::{
    AccessError, Aoi, AoiId, LookSide, OpticalAccessAnalysis, OpticalPayload, SarAccessAnalysis,
    SarPayload,
};
use crate::analysis::power::{
    PowerBudgetAnalysis, PowerBudgetResults, PowerError, SpacecraftFilter,
};
use crate::analysis::sun::AnalyticalSunEphemeris;
use crate::analysis::visibility::{
    DynPass, ElevationMask, ElevationMaskError, PairType, Pass, VisibilityAnalysis,
    VisibilityError, VisibilityResults,
};
use crate::bodies::DynOrigin;
use crate::bodies::python::PyOrigin;
use crate::comms::python::PyCommunicationSystem;
use crate::ephem::python::PySpk;
use crate::frames::python::PyFrame;
use crate::orbits::ground::Observables;
use crate::orbits::python::{
    PyGroundLocation, PyInterval, PyJ2Propagator, PyJ4Propagator, PyNumericalPropagator, PySgp4,
    PyTrajectory, PyVallado,
};
use crate::time::deltas::TimeDelta;
use crate::time::python::deltas::PyTimeDelta;
use crate::time::python::time::PyTime;
use crate::time::python::time_series::PyTimeSeries;
use crate::units::python::{PyAngle, PyAngularRate, PyDistance, PyVelocity};
use lox_frames::DynFrame;
use lox_frames::providers::DefaultRotationProvider;
use lox_orbits::orbits::Ensemble;
use lox_orbits::propagators::OrbitSource;
use lox_time::intervals::TimeInterval;
use lox_time::series::TimeSeries;
use lox_time::time_scales::Tai;
use lox_units::{Angle, Distance, Velocity};

use numpy::{PyArray1, PyArrayMethods};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyType;

struct PyVisibilityError(VisibilityError);

impl From<PyVisibilityError> for PyErr {
    fn from(err: PyVisibilityError) -> Self {
        PyValueError::new_err(err.0.to_string())
    }
}

/// Error wrapper converting `ElevationMaskError` into a Python `ValueError`.
pub struct PyElevationMaskError(pub ElevationMaskError);

impl From<PyElevationMaskError> for PyErr {
    fn from(err: PyElevationMaskError) -> Self {
        PyValueError::new_err(err.0.to_string())
    }
}

/// A named ground station for visibility analysis.
///
/// Wraps a ground location and elevation mask with an identifier.
///
/// Args:
///     id: Unique identifier for this ground station.
///     location: Ground station location.
///     mask: Elevation mask defining minimum elevation constraints.
///     communication_systems: Optional list of communication systems.
#[pyclass(name = "GroundStation", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PyGroundStation(pub GroundStation);

#[pymethods]
impl PyGroundStation {
    #[new]
    #[pyo3(signature = (id, location, mask, body_fixed_frame=None, network_id=None, communication_systems=None))]
    fn new(
        id: String,
        location: PyGroundLocation,
        mask: PyElevationMask,
        body_fixed_frame: Option<PyFrame>,
        network_id: Option<String>,
        communication_systems: Option<Vec<PyCommunicationSystem>>,
    ) -> Self {
        let mut gs = GroundStation::new(id, location.0, mask.0);
        if let Some(frame) = body_fixed_frame {
            gs = gs.with_body_fixed_frame(frame.0);
        }
        if let Some(nid) = network_id {
            gs = gs.with_network_id(nid);
        }
        if let Some(systems) = communication_systems {
            for system in systems {
                gs = gs.with_communication_system(system.0);
            }
        }
        PyGroundStation(gs)
    }

    /// Return the asset identifier.
    fn id(&self) -> String {
        self.0.id().as_str().to_string()
    }

    /// Return the ground location.
    fn location(&self) -> PyGroundLocation {
        PyGroundLocation(self.0.location().clone())
    }

    /// Return the elevation mask.
    fn mask(&self) -> PyElevationMask {
        PyElevationMask(self.0.mask().clone())
    }

    /// Return the network identifier, if assigned.
    fn network_id(&self) -> Option<String> {
        self.0.network_id().map(|id| id.as_str().to_string())
    }

    /// Return the body-fixed frame.
    fn body_fixed_frame(&self) -> PyFrame {
        PyFrame(self.0.body_fixed_frame())
    }

    /// Return the communication systems.
    fn communication_systems(&self) -> Vec<PyCommunicationSystem> {
        self.0
            .communication_systems()
            .iter()
            .map(|s| PyCommunicationSystem(s.clone()))
            .collect()
    }

    fn __repr__(&self) -> String {
        format!(
            "GroundStation(\"{}\", {}, {})",
            self.id(),
            self.location().__repr__(),
            self.mask().__repr__(),
        )
    }
}

/// Extract an OrbitSource from a Python object (SGP4, Vallado, J2, or Trajectory).
fn extract_orbit_source(obj: &Bound<'_, PyAny>) -> PyResult<OrbitSource> {
    if let Ok(sgp4) = obj.extract::<PySgp4>() {
        return Ok(OrbitSource::Sgp4(sgp4.inner));
    }
    if let Ok(vallado) = obj.extract::<PyVallado>() {
        return Ok(OrbitSource::Vallado(vallado.0));
    }
    if let Ok(n) = obj.extract::<PyNumericalPropagator>() {
        return Ok(OrbitSource::Numerical(n.0));
    }
    if let Ok(p) = obj.extract::<PyJ2Propagator>() {
        return Ok(OrbitSource::J2(p.0));
    }
    if let Ok(p) = obj.extract::<PyJ4Propagator>() {
        return Ok(OrbitSource::J4(p.0));
    }
    if let Ok(traj) = obj.extract::<PyTrajectory>() {
        return Ok(OrbitSource::Trajectory(traj.0));
    }
    Err(PyValueError::new_err(
        "expected a propagator (SGP4, Vallado, Numerical, J2, J4) or Trajectory object",
    ))
}

/// A named spacecraft for visibility analysis.
///
/// Wraps an orbit source (propagator or pre-computed trajectory) with an
/// identifier.
///
/// Args:
///     id: Unique identifier for this spacecraft.
///     orbit: Orbit source — an SGP4, Vallado, J2 propagator, or a
///         pre-computed Trajectory.
///     max_slew_rate: Optional maximum slew rate (angular rate) for this
///         spacecraft's antenna/gimbal.
///     communication_systems: Optional list of communication systems.
#[pyclass(name = "Spacecraft", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PySpacecraft(pub Spacecraft);

#[pymethods]
impl PySpacecraft {
    #[new]
    #[pyo3(signature = (id, orbit, max_slew_rate=None, constellation_id=None, optical_payload=None, sar_payload=None, communication_systems=None))]
    #[allow(clippy::too_many_arguments)]
    fn new(
        id: String,
        orbit: &Bound<'_, PyAny>,
        max_slew_rate: Option<PyAngularRate>,
        constellation_id: Option<String>,
        optical_payload: Option<PyOpticalPayload>,
        sar_payload: Option<PySarPayload>,
        communication_systems: Option<Vec<PyCommunicationSystem>>,
    ) -> PyResult<Self> {
        let orbit_source = extract_orbit_source(orbit)?;
        let mut asset = Spacecraft::new(id, orbit_source);
        if let Some(rate) = max_slew_rate {
            asset = asset.with_max_slew_rate(rate.0);
        }
        if let Some(cid) = constellation_id {
            asset = asset.with_constellation_id(cid);
        }
        if let Some(payload) = optical_payload {
            asset = asset.with_optical_payload(payload.0);
        }
        if let Some(payload) = sar_payload {
            asset = asset.with_sar_payload(payload.0);
        }
        if let Some(systems) = communication_systems {
            for system in systems {
                asset = asset.with_communication_system(system.0);
            }
        }
        Ok(PySpacecraft(asset))
    }

    /// Return the asset identifier.
    fn id(&self) -> String {
        self.0.id().as_str().to_string()
    }

    /// Return the constellation identifier, if assigned.
    fn constellation_id(&self) -> Option<String> {
        self.0.constellation_id().map(|id| id.as_str().to_string())
    }

    /// Return the maximum slew rate, if set.
    fn max_slew_rate(&self) -> Option<PyAngularRate> {
        self.0.max_slew_rate().map(PyAngularRate)
    }

    /// Return the optical payload, if set.
    fn optical_payload(&self) -> Option<PyOpticalPayload> {
        self.0.optical_payload().map(PyOpticalPayload)
    }

    /// Return the SAR payload, if set.
    fn sar_payload(&self) -> Option<PySarPayload> {
        self.0.sar_payload().map(PySarPayload)
    }

    /// Return the communication systems.
    fn communication_systems(&self) -> Vec<PyCommunicationSystem> {
        self.0
            .communication_systems()
            .iter()
            .map(|s| PyCommunicationSystem(s.clone()))
            .collect()
    }

    fn __repr__(&self) -> String {
        format!("Spacecraft(\"{}\")", self.id())
    }
}

/// A scenario grouping spacecraft, ground stations, and a time interval.
///
/// Args:
///     start: Start time of the scenario.
///     end: End time of the scenario.
///     spacecraft: List of Spacecraft objects.
///     ground_stations: List of GroundStation objects.
#[pyclass(name = "Scenario", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PyScenario(pub DynScenario);

#[pymethods]
impl PyScenario {
    #[new]
    #[pyo3(signature = (start, end, spacecraft=None, ground_stations=None))]
    fn new(
        start: PyTime,
        end: PyTime,
        spacecraft: Option<Vec<PySpacecraft>>,
        ground_stations: Option<Vec<PyGroundStation>>,
    ) -> Self {
        let tai_start = start.0.to_scale(Tai);
        let tai_end = end.0.to_scale(Tai);
        let mut scenario = DynScenario::new(tai_start, tai_end, DynOrigin::Earth, DynFrame::Icrf);
        if let Some(sc) = spacecraft {
            let sc_vec: Vec<Spacecraft> = sc.into_iter().map(|s| s.0).collect();
            scenario = scenario.with_spacecraft(&sc_vec);
        }
        if let Some(gs) = ground_stations {
            let gs_vec: Vec<GroundStation> = gs.into_iter().map(|g| g.0).collect();
            scenario = scenario.with_ground_stations(&gs_vec);
        }
        PyScenario(scenario)
    }

    /// Propagate all spacecraft, returning an Ensemble.
    ///
    /// Trajectories are transformed to ICRF using the default rotation
    /// provider.
    fn propagate(&self, py: Python<'_>) -> PyResult<PyEnsemble> {
        let ensemble = py.detach(|| self.0.propagate(&DefaultRotationProvider));
        Ok(PyEnsemble(
            ensemble.map_err(|e| PyValueError::new_err(e.to_string()))?,
        ))
    }

    /// Return the start time.
    fn start(&self) -> PyTime {
        PyTime(self.0.interval().start().into_dyn())
    }

    /// Add a constellation to the scenario, converting all its satellites
    /// to spacecraft using the constellation's selected propagator.
    fn with_constellation(
        &self,
        constellation: crate::constellations::python::PyConstellation,
    ) -> PyResult<Self> {
        let scenario = self
            .0
            .clone()
            .with_constellation(constellation.0)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(PyScenario(scenario))
    }

    /// Return the end time.
    fn end(&self) -> PyTime {
        PyTime(self.0.interval().end().into_dyn())
    }

    fn __repr__(&self) -> String {
        format!(
            "Scenario({} spacecraft, {} ground stations)",
            self.0.spacecraft().len(),
            self.0.ground_stations().len(),
        )
    }
}

/// A collection of propagated trajectories keyed by spacecraft id.
#[pyclass(name = "Ensemble", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PyEnsemble(pub Ensemble<AssetId, Tai, DynOrigin, DynFrame>);

#[pymethods]
impl PyEnsemble {
    /// Return the trajectory for a given spacecraft id.
    fn get(&self, id: &str) -> Option<PyTrajectory> {
        self.0
            .get(&AssetId::new(id))
            .map(|t| PyTrajectory(t.clone().into_dyn()))
    }

    fn __len__(&self) -> usize {
        self.0.len()
    }

    fn __repr__(&self) -> String {
        format!("Ensemble({} trajectories)", self.0.len())
    }
}

/// Computes ground-station-to-spacecraft and inter-satellite visibility.
///
/// Args:
///     scenario: Scenario containing spacecraft, ground stations, and
///         time interval.
///     ephemeris: SPK ephemeris data.
///     ensemble: Optional pre-computed Ensemble. If not provided, the
///         scenario is propagated automatically.
///     occulting_bodies: Optional list of additional occulting bodies for
///         LOS checking. For inter-satellite visibility, the scenario's
///         central body is always checked automatically.
///     step: Optional time step for event detection (default: 60s).
///     min_pass_duration: Optional minimum pass duration. Passes shorter
///         than this value may be missed. Enables two-level stepping for faster
///         detection.
///     inter_satellite: If True, also compute inter-satellite visibility
///         for all unique spacecraft pairs (default: False).
///     ground_space_filter: Optional callable ``(GroundStation, Spacecraft) -> bool``
///         that receives a ground station and spacecraft and returns whether the
///         pair should be evaluated. Called once per candidate pair before the
///         parallel phase.
///     inter_satellite_filter: Optional callable ``(Spacecraft, Spacecraft) -> bool``
///         that receives two spacecraft and returns whether the pair should be
///         evaluated. Called once per candidate pair before the parallel phase.
///         When provided, inter-satellite visibility is automatically enabled.
///     min_range: Optional minimum range constraint for inter-satellite pairs.
///     max_range: Optional maximum range constraint for inter-satellite pairs.
#[pyclass(name = "VisibilityAnalysis", module = "lox_space", frozen)]
pub struct PyVisibilityAnalysis {
    scenario: DynScenario,
    ensemble: Option<Ensemble<AssetId, Tai, DynOrigin, DynFrame>>,
    occulting_bodies: Vec<DynOrigin>,
    step: TimeDelta,
    min_pass_duration: Option<TimeDelta>,
    inter_satellite: bool,
    ground_space_filter: Option<Py<PyAny>>,
    inter_satellite_filter: Option<Py<PyAny>>,
    min_range: Option<Distance>,
    max_range: Option<Distance>,
}

#[pymethods]
impl PyVisibilityAnalysis {
    #[new]
    #[pyo3(signature = (scenario, ensemble=None, occulting_bodies=None, step=None, min_pass_duration=None, inter_satellite=false, ground_space_filter=None, inter_satellite_filter=None, min_range=None, max_range=None))]
    #[allow(clippy::too_many_arguments)]
    fn new(
        py: Python<'_>,
        scenario: PyScenario,
        ensemble: Option<PyEnsemble>,
        occulting_bodies: Option<Vec<Bound<'_, PyAny>>>,
        step: Option<PyTimeDelta>,
        min_pass_duration: Option<PyTimeDelta>,
        inter_satellite: bool,
        ground_space_filter: Option<Py<PyAny>>,
        inter_satellite_filter: Option<Py<PyAny>>,
        min_range: Option<PyDistance>,
        max_range: Option<PyDistance>,
    ) -> PyResult<Self> {
        let occulting_bodies: Vec<DynOrigin> = occulting_bodies
            .unwrap_or_default()
            .iter()
            .map(|b| Ok(PyOrigin::try_from(b)?.0))
            .collect::<PyResult<_>>()?;
        if let Some(ref f) = ground_space_filter
            && !f.bind(py).is_callable()
        {
            return Err(PyValueError::new_err(
                "ground_space_filter must be callable",
            ));
        }
        if let Some(ref f) = inter_satellite_filter
            && !f.bind(py).is_callable()
        {
            return Err(PyValueError::new_err(
                "inter_satellite_filter must be callable",
            ));
        }
        Ok(Self {
            scenario: scenario.0,
            ensemble: ensemble.map(|e| e.0),
            occulting_bodies,
            step: step
                .map(|s| s.0)
                .unwrap_or_else(|| TimeDelta::from_seconds_f64(60.0)),
            min_pass_duration: min_pass_duration.map(|d| d.0),
            inter_satellite,
            ground_space_filter,
            inter_satellite_filter,
            min_range: min_range.map(|d| d.0),
            max_range: max_range.map(|d| d.0),
        })
    }

    /// Compute visibility intervals for all pairs.
    ///
    /// If no ensemble was provided at construction, the scenario is
    /// propagated automatically (trajectories transformed to ICRF).
    ///
    /// Args:
    ///     ephemeris: SPK ephemeris data.
    ///
    /// Returns:
    ///     VisibilityResults containing intervals for all pairs.
    fn compute(
        &self,
        py: Python<'_>,
        ephemeris: &Bound<'_, PySpk>,
    ) -> PyResult<PyVisibilityResults> {
        let ephemeris = &ephemeris.get().0;
        let step = self.step;
        let scenario = &self.scenario;

        // Auto-propagate if no ensemble was provided.
        let auto_ensemble;
        let ensemble = match &self.ensemble {
            Some(e) => e,
            None => {
                auto_ensemble = scenario
                    .propagate(&DefaultRotationProvider)
                    .map_err(|e| PyValueError::new_err(e.to_string()))?;
                &auto_ensemble
            }
        };

        let occulting_bodies = self.occulting_bodies.clone();
        let min_pass_duration = self.min_pass_duration;
        let inter_satellite = self.inter_satellite;
        let min_range = self.min_range;
        let max_range = self.max_range;

        // Eagerly evaluate Python filters while we hold the GIL, collecting
        // accepted pairs into plain sets that can cross into the GIL-free
        // parallel section.
        let gs_accepted: Option<HashSet<(AssetId, AssetId)>> =
            if let Some(ref filter) = self.ground_space_filter {
                let ground_stations = scenario.ground_stations();
                let spacecraft = scenario.spacecraft();
                let mut set = HashSet::new();
                for gs in ground_stations {
                    for sc in spacecraft {
                        let py_gs = PyGroundStation(gs.clone());
                        let py_sc = PySpacecraft(sc.clone());
                        let accept: bool = filter.call1(py, (py_gs, py_sc))?.extract(py)?;
                        if accept {
                            set.insert((gs.id().clone(), sc.id().clone()));
                        }
                    }
                }
                Some(set)
            } else {
                None
            };

        let isl_accepted: Option<HashSet<(AssetId, AssetId)>> =
            if let Some(ref filter) = self.inter_satellite_filter {
                let spacecraft = scenario.spacecraft();
                let n = spacecraft.len();
                let mut set = HashSet::new();
                for i in 0..n {
                    for j in (i + 1)..n {
                        let py_sc1 = PySpacecraft(spacecraft[i].clone());
                        let py_sc2 = PySpacecraft(spacecraft[j].clone());
                        let accept: bool = filter.call1(py, (py_sc1, py_sc2))?.extract(py)?;
                        if accept {
                            set.insert((spacecraft[i].id().clone(), spacecraft[j].id().clone()));
                        }
                    }
                }
                Some(set)
            } else {
                None
            };

        let results = py.detach(|| {
            let mut analysis = VisibilityAnalysis::new(scenario, ensemble, ephemeris)
                .with_occulting_bodies(occulting_bodies)
                .with_step(step);
            if let Some(mpd) = min_pass_duration {
                analysis = analysis.with_min_pass_duration(mpd);
            }
            if let Some(ref accepted) = gs_accepted {
                analysis = analysis.with_ground_space_filter(|gs, sc| {
                    accepted.contains(&(gs.id().clone(), sc.id().clone()))
                });
            }
            if let Some(ref accepted) = isl_accepted {
                analysis = analysis.with_inter_satellite_filter(|sc1, sc2| {
                    accepted.contains(&(sc1.id().clone(), sc2.id().clone()))
                });
            } else if inter_satellite {
                analysis = analysis.with_inter_satellite();
            }
            if let Some(min_range) = min_range {
                analysis = analysis.with_min_range(min_range);
            }
            if let Some(max_range) = max_range {
                analysis = analysis.with_max_range(max_range);
            }
            analysis.compute()
        });

        Ok(PyVisibilityResults {
            results: results.map_err(PyVisibilityError)?,
            scenario: self.scenario.clone(),
            ensemble: ensemble.clone(),
            step: self.step,
        })
    }

    fn __repr__(&self) -> String {
        let sc_count = self.scenario.spacecraft().len();
        let gs_count = self.scenario.ground_stations().len();
        let mut extras = Vec::new();
        if self.ground_space_filter.is_some() {
            extras.push("ground_space_filter=True".to_string());
        }
        if self.inter_satellite_filter.is_some() {
            extras.push("inter_satellite_filter=True".to_string());
        } else if self.inter_satellite {
            extras.push("inter_satellite=True".to_string());
        }
        if extras.is_empty() {
            format!("VisibilityAnalysis({gs_count} ground assets, {sc_count} space assets)")
        } else {
            format!(
                "VisibilityAnalysis({gs_count} ground assets, {sc_count} space assets, {})",
                extras.join(", "),
            )
        }
    }
}

/// Results of a visibility analysis.
///
/// Provides lazy access to visibility intervals and passes. Intervals
/// (time windows) are computed eagerly; observables-rich Pass objects are
/// computed on demand to avoid unnecessary work.
#[pyclass(name = "VisibilityResults", module = "lox_space", frozen)]
pub struct PyVisibilityResults {
    results: VisibilityResults,
    scenario: DynScenario,
    ensemble: Ensemble<AssetId, Tai, DynOrigin, DynFrame>,
    step: TimeDelta,
}

#[pymethods]
impl PyVisibilityResults {
    /// Return visibility intervals for a specific pair.
    ///
    /// Args:
    ///     id1: First asset identifier (ground or space).
    ///     id2: Second asset identifier (space).
    ///
    /// Returns:
    ///     List of Interval objects, or empty list if pair not found.
    fn intervals(&self, id1: &str, id2: &str) -> Vec<PyInterval> {
        let id1 = AssetId::new(id1);
        let id2 = AssetId::new(id2);
        self.results
            .intervals_for(&id1, &id2)
            .map(|intervals| {
                intervals
                    .iter()
                    .map(|i| {
                        PyInterval(TimeInterval::new(i.start().into_dyn(), i.end().into_dyn()))
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Return all intervals for all pairs.
    ///
    /// Returns:
    ///     Dictionary mapping (id1, id2) to list of Interval objects.
    fn all_intervals(&self) -> HashMap<(String, String), Vec<PyInterval>> {
        self.results
            .all_intervals()
            .iter()
            .map(|((id1, id2), intervals)| {
                (
                    (id1.as_str().to_string(), id2.as_str().to_string()),
                    intervals
                        .iter()
                        .map(|i| {
                            PyInterval(TimeInterval::new(i.start().into_dyn(), i.end().into_dyn()))
                        })
                        .collect(),
                )
            })
            .collect()
    }

    /// Return intervals for ground-to-space pairs only.
    ///
    /// Returns:
    ///     Dictionary mapping (ground_id, space_id) to list of Interval objects.
    fn ground_space_intervals(&self) -> HashMap<(String, String), Vec<PyInterval>> {
        self.results
            .ground_space_pair_ids()
            .into_iter()
            .filter_map(|(gs_id, sc_id)| {
                let intervals = self.results.intervals_for(gs_id, sc_id)?;
                Some((
                    (gs_id.as_str().to_string(), sc_id.as_str().to_string()),
                    intervals
                        .iter()
                        .map(|i| {
                            PyInterval(TimeInterval::new(i.start().into_dyn(), i.end().into_dyn()))
                        })
                        .collect(),
                ))
            })
            .collect()
    }

    /// Return intervals for inter-satellite pairs only.
    ///
    /// Returns:
    ///     Dictionary mapping (sc1_id, sc2_id) to list of Interval objects.
    fn inter_satellite_intervals(&self) -> HashMap<(String, String), Vec<PyInterval>> {
        self.results
            .inter_satellite_pair_ids()
            .into_iter()
            .filter_map(|(sc1_id, sc2_id)| {
                let intervals = self.results.intervals_for(sc1_id, sc2_id)?;
                Some((
                    (sc1_id.as_str().to_string(), sc2_id.as_str().to_string()),
                    intervals
                        .iter()
                        .map(|i| {
                            PyInterval(TimeInterval::new(i.start().into_dyn(), i.end().into_dyn()))
                        })
                        .collect(),
                ))
            })
            .collect()
    }

    /// Compute passes with observables for a specific ground-to-space pair.
    ///
    /// This is more expensive than `intervals()` as it computes azimuth,
    /// elevation, range, and range rate for each time step.
    ///
    /// Raises ValueError for inter-satellite pairs since ground-station
    /// observables are not meaningful for them.
    ///
    /// Args:
    ///     ground_id: Ground asset identifier.
    ///     space_id: Space asset identifier.
    ///
    /// Returns:
    ///     List of Pass objects, or empty list if pair not found.
    fn passes(&self, ground_id: &str, space_id: &str) -> PyResult<Vec<PyPass>> {
        let gs_id = AssetId::new(ground_id);
        let sc_id = AssetId::new(space_id);

        // Check if this is an inter-satellite pair before looking up assets.
        if self.results.pair_type(&gs_id, &sc_id) == Some(PairType::InterSatellite) {
            return Err(PyValueError::new_err(format!(
                "passes are not supported for inter-satellite pair ({}, {}): use intervals() instead",
                ground_id, space_id,
            )));
        }

        let gs = self
            .scenario
            .ground_stations()
            .iter()
            .find(|g| g.id() == &gs_id);
        let sc_traj = self.ensemble.get(&sc_id);
        match (gs, sc_traj) {
            (Some(gs), Some(sc_traj)) => {
                let dyn_traj = sc_traj.clone().into_dyn();
                let passes = self
                    .results
                    .to_passes(
                        &gs_id,
                        &sc_id,
                        gs.location(),
                        gs.mask(),
                        &dyn_traj,
                        self.step,
                        gs.body_fixed_frame(),
                    )
                    .map_err(|e| PyValueError::new_err(e.to_string()))?;
                Ok(passes.into_iter().map(PyPass).collect())
            }
            _ => Ok(vec![]),
        }
    }

    /// Compute passes for all ground-to-space pairs.
    ///
    /// Inter-satellite pairs are skipped since ground-station observables
    /// are not meaningful for them.
    ///
    /// Returns:
    ///     Dictionary mapping (ground_id, space_id) to list of Pass objects.
    fn all_passes(&self) -> HashMap<(String, String), Vec<PyPass>> {
        let gs_map: HashMap<&AssetId, &GroundStation> = self
            .scenario
            .ground_stations()
            .iter()
            .map(|g| (g.id(), g))
            .collect();

        self.results
            .ground_space_pair_ids()
            .into_iter()
            .filter_map(|(gs_id, sc_id)| {
                let gs = gs_map.get(gs_id)?;
                let sc_traj = self.ensemble.get(sc_id)?;
                let dyn_traj = sc_traj.clone().into_dyn();
                let intervals = self.results.intervals_for(gs_id, sc_id)?;
                let passes: Vec<PyPass> = intervals
                    .iter()
                    .filter_map(|interval| {
                        let dyn_interval = TimeInterval::new(
                            interval.start().into_dyn(),
                            interval.end().into_dyn(),
                        );
                        DynPass::from_interval(
                            dyn_interval,
                            self.step,
                            gs.location(),
                            gs.mask(),
                            &dyn_traj,
                            gs.body_fixed_frame(),
                        )
                    })
                    .map(PyPass)
                    .collect();
                Some((
                    (gs_id.as_str().to_string(), sc_id.as_str().to_string()),
                    passes,
                ))
            })
            .collect()
    }

    /// Return all pair identifiers.
    fn pair_ids(&self) -> Vec<(String, String)> {
        self.results
            .pair_ids()
            .map(|(id1, id2)| (id1.as_str().to_string(), id2.as_str().to_string()))
            .collect()
    }

    /// Return pair identifiers for ground-to-space pairs only.
    fn ground_space_pair_ids(&self) -> Vec<(String, String)> {
        self.results
            .ground_space_pair_ids()
            .into_iter()
            .map(|(id1, id2)| (id1.as_str().to_string(), id2.as_str().to_string()))
            .collect()
    }

    /// Return pair identifiers for inter-satellite pairs only.
    fn inter_satellite_pair_ids(&self) -> Vec<(String, String)> {
        self.results
            .inter_satellite_pair_ids()
            .into_iter()
            .map(|(id1, id2)| (id1.as_str().to_string(), id2.as_str().to_string()))
            .collect()
    }

    /// Return the total number of pairs.
    fn num_pairs(&self) -> usize {
        self.results.num_pairs()
    }

    /// Return the total number of visibility intervals across all pairs.
    fn total_intervals(&self) -> usize {
        self.results.total_intervals()
    }

    fn __repr__(&self) -> String {
        format!(
            "VisibilityResults({} pairs, {} intervals)",
            self.results.num_pairs(),
            self.results.total_intervals(),
        )
    }
}

/// Defines elevation constraints for visibility analysis.
///
/// An elevation mask specifies the minimum elevation angle required for
/// visibility at different azimuth angles. Can be either fixed (constant
/// minimum elevation) or variable (azimuth-dependent).
///
/// Args:
///     azimuth: Array of azimuth angles in radians (for variable mask).
///     elevation: Array of minimum elevations in radians (for variable mask).
///     min_elevation: Fixed minimum elevation in radians.
#[pyclass(
    name = "ElevationMask",
    module = "lox_space",
    frozen,
    eq,
    from_py_object
)]
#[derive(Debug, Clone, PartialEq)]
pub struct PyElevationMask(pub ElevationMask);

#[pymethods]
impl PyElevationMask {
    #[new]
    #[pyo3(signature = (azimuth=None, elevation=None, min_elevation=None))]
    fn new(
        azimuth: Option<&Bound<'_, PyArray1<f64>>>,
        elevation: Option<&Bound<'_, PyArray1<f64>>>,
        min_elevation: Option<PyAngle>,
    ) -> PyResult<Self> {
        if let Some(min_elevation) = min_elevation {
            return Ok(PyElevationMask(ElevationMask::with_fixed_elevation(
                min_elevation.0.to_radians(),
            )));
        }
        if let (Some(azimuth), Some(elevation)) = (azimuth, elevation) {
            let azimuth = azimuth.to_vec()?;
            let elevation = elevation.to_vec()?;
            return Ok(PyElevationMask(
                ElevationMask::new(azimuth, elevation).map_err(PyElevationMaskError)?,
            ));
        }
        Err(PyValueError::new_err(
            "invalid argument combination, either `min_elevation` or `azimuth` and `elevation` arrays need to be present",
        ))
    }

    /// Create a fixed elevation mask with constant minimum elevation.
    ///
    /// Args:
    ///     min_elevation: Minimum elevation angle as Angle.
    ///
    /// Returns:
    ///     ElevationMask with fixed minimum elevation.
    #[classmethod]
    fn fixed(_cls: &Bound<'_, PyType>, min_elevation: PyAngle) -> Self {
        PyElevationMask(ElevationMask::with_fixed_elevation(
            min_elevation.0.to_radians(),
        ))
    }

    /// Create a variable elevation mask from azimuth-dependent data.
    ///
    /// Args:
    ///     azimuth: Array of azimuth angles in radians.
    ///     elevation: Array of minimum elevations in radians.
    ///
    /// Returns:
    ///     ElevationMask with variable minimum elevation.
    #[classmethod]
    fn variable(
        _cls: &Bound<'_, PyType>,
        azimuth: &Bound<'_, PyArray1<f64>>,
        elevation: &Bound<'_, PyArray1<f64>>,
    ) -> PyResult<Self> {
        let azimuth = azimuth.to_vec()?;
        let elevation = elevation.to_vec()?;
        Ok(PyElevationMask(
            ElevationMask::new(azimuth, elevation).map_err(PyElevationMaskError)?,
        ))
    }

    fn __getnewargs__(&self) -> (Option<Vec<f64>>, Option<Vec<f64>>, Option<PyAngle>) {
        (self.azimuth(), self.elevation(), self.fixed_elevation())
    }

    /// Return the azimuth array (for variable masks only).
    fn azimuth(&self) -> Option<Vec<f64>> {
        match &self.0 {
            ElevationMask::Fixed(_) => None,
            ElevationMask::Variable(series) => Some(series.x().to_vec()),
        }
    }

    /// Return the elevation array (for variable masks only).
    fn elevation(&self) -> Option<Vec<f64>> {
        match &self.0 {
            ElevationMask::Fixed(_) => None,
            ElevationMask::Variable(series) => Some(series.y().to_vec()),
        }
    }

    /// Return the fixed elevation value (for fixed masks only).
    fn fixed_elevation(&self) -> Option<PyAngle> {
        match &self.0 {
            ElevationMask::Fixed(min_elevation) => Some(PyAngle(Angle::radians(*min_elevation))),
            ElevationMask::Variable(_) => None,
        }
    }

    /// Return the minimum elevation at the given azimuth.
    ///
    /// Args:
    ///     azimuth: Azimuth angle as Angle.
    ///
    /// Returns:
    ///     Minimum elevation as Angle.
    fn min_elevation(&self, azimuth: PyAngle) -> PyAngle {
        PyAngle(Angle::radians(self.0.min_elevation(azimuth.0.to_radians())))
    }

    fn __repr__(&self) -> String {
        match &self.0 {
            ElevationMask::Fixed(min_elevation) => {
                format!(
                    "ElevationMask(min_elevation={})",
                    PyAngle(Angle::radians(*min_elevation)).__repr__(),
                )
            }
            ElevationMask::Variable(series) => {
                let n = series.x().len();
                format!("ElevationMask({n} azimuth/elevation pairs)")
            }
        }
    }
}

/// Observation data from a ground station to a target.
///
/// Observables contain the geometric relationship between a ground station
/// and a spacecraft, including angles and range information.
///
/// Args:
///     azimuth: Azimuth angle as Angle.
///     elevation: Elevation angle as Angle.
///     range: Distance to target as Distance.
///     range_rate: Rate of change of range as Velocity.
#[pyclass(name = "Observables", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PyObservables(pub Observables);

#[pymethods]
impl PyObservables {
    #[new]
    fn new(
        azimuth: PyAngle,
        elevation: PyAngle,
        range: PyDistance,
        range_rate: PyVelocity,
    ) -> Self {
        PyObservables(Observables::new(
            azimuth.0.to_radians(),
            elevation.0.to_radians(),
            range.0.to_meters(),
            range_rate.0.to_meters_per_second(),
        ))
    }

    /// Return the azimuth angle.
    fn azimuth(&self) -> PyAngle {
        PyAngle(Angle::radians(self.0.azimuth()))
    }

    /// Return the elevation angle.
    fn elevation(&self) -> PyAngle {
        PyAngle(Angle::radians(self.0.elevation()))
    }

    /// Return the range (distance).
    fn range(&self) -> PyDistance {
        PyDistance(Distance::meters(self.0.range()))
    }

    /// Return the range rate.
    fn range_rate(&self) -> PyVelocity {
        PyVelocity(Velocity::meters_per_second(self.0.range_rate()))
    }

    fn __repr__(&self) -> String {
        format!(
            "Observables({}, {}, {}, {})",
            self.azimuth().__repr__(),
            self.elevation().__repr__(),
            self.range().__repr__(),
            self.range_rate().__repr__(),
        )
    }
}

/// Represents a visibility pass between a ground station and spacecraft.
///
/// A Pass contains the visibility interval (start and end times) along with
/// observables computed at regular intervals throughout the pass.
#[pyclass(name = "Pass", module = "lox_space", frozen, from_py_object)]
#[derive(Debug, Clone)]
pub struct PyPass(pub DynPass);

#[pymethods]
impl PyPass {
    #[new]
    fn new(
        interval: PyInterval,
        times: Vec<PyTime>,
        observables: Vec<PyObservables>,
    ) -> PyResult<Self> {
        let times: Vec<crate::time::DynTime> = times.into_iter().map(|t| t.0).collect();
        let observables: Vec<Observables> = observables.into_iter().map(|o| o.0).collect();

        let pass = Pass::try_new(interval.0, times, observables)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;

        Ok(PyPass(pass))
    }

    /// Return the visibility interval for this pass.
    fn interval(&self) -> PyInterval {
        PyInterval(*self.0.interval())
    }

    /// Return the time samples during this pass.
    fn times(&self) -> Vec<PyTime> {
        self.0.times().iter().map(|&t| PyTime(t)).collect()
    }

    /// Return the observables at each time sample.
    fn observables(&self) -> Vec<PyObservables> {
        self.0
            .observables()
            .iter()
            .map(|o| PyObservables(o.clone()))
            .collect()
    }

    /// Interpolate observables at a specific time within the pass.
    ///
    /// Args:
    ///     time: Time to interpolate at.
    ///
    /// Returns:
    ///     Interpolated Observables, or None if time is outside the pass.
    fn interpolate(&self, time: PyTime) -> Option<PyObservables> {
        self.0.interpolate(time.0).map(PyObservables)
    }

    fn __repr__(&self) -> String {
        format!(
            "Pass(interval={}, {} observables)",
            self.interval().__repr__(),
            self.0.observables().len(),
        )
    }
}

// ---------------------------------------------------------------------------
// PowerBudgetAnalysis / PowerBudgetResults Python bindings
// ---------------------------------------------------------------------------

struct PyPowerError(PowerError);

impl From<PyPowerError> for PyErr {
    fn from(err: PyPowerError) -> Self {
        PyValueError::new_err(err.0.to_string())
    }
}

/// Power budget analysis for spacecraft in a scenario.
///
/// Computes eclipse intervals, sun beta angle, and solar flux for each
/// spacecraft.  The shadow model is cylindrical (umbra only) — penumbra
/// is **not** modelled.
///
/// Args:
///     scenario: Scenario containing spacecraft and time interval.
///     ensemble: Optional pre-computed Ensemble. If not provided, the
///         scenario is propagated automatically.
///     step: Optional time step for sampling / event detection (default: 60s).
///     spacecraft_ids: Optional list of spacecraft ids to analyse. Mutually
///         exclusive with ``constellation_id``.
///     constellation_id: Optional constellation id — only spacecraft belonging
///         to this constellation are analysed. Mutually exclusive with
///         ``spacecraft_ids``.
#[pyclass(name = "PowerBudgetAnalysis", module = "lox_space", frozen)]
pub struct PyPowerBudgetAnalysis {
    scenario: DynScenario,
    ensemble: Option<Ensemble<AssetId, Tai, DynOrigin, DynFrame>>,
    step: TimeDelta,
    filter: Option<SpacecraftFilter>,
}

#[pymethods]
impl PyPowerBudgetAnalysis {
    #[new]
    #[pyo3(signature = (scenario, ensemble=None, step=None, spacecraft_ids=None, constellation_id=None))]
    fn new(
        scenario: PyScenario,
        ensemble: Option<PyEnsemble>,
        step: Option<PyTimeDelta>,
        spacecraft_ids: Option<Vec<String>>,
        constellation_id: Option<String>,
    ) -> PyResult<Self> {
        let filter = match (spacecraft_ids, constellation_id) {
            (Some(_), Some(_)) => {
                return Err(PyValueError::new_err(
                    "spacecraft_ids and constellation_id are mutually exclusive",
                ));
            }
            (Some(ids), None) => Some(SpacecraftFilter::Ids(
                ids.into_iter().map(AssetId::new).collect(),
            )),
            (None, Some(cid)) => Some(SpacecraftFilter::Constellation(ConstellationId::new(cid))),
            (None, None) => None,
        };
        Ok(Self {
            scenario: scenario.0,
            ensemble: ensemble.map(|e| e.0),
            step: step
                .map(|s| s.0)
                .unwrap_or_else(|| TimeDelta::from_seconds_f64(60.0)),
            filter,
        })
    }

    /// Compute the power budget analysis.
    ///
    /// Args:
    ///     ephemeris: Optional SPK ephemeris for Sun position. When omitted,
    ///         an analytical model is used (valid for Earth-centred scenarios).
    ///
    /// Returns:
    ///     PowerBudgetResults with eclipse intervals, beta angles, and
    ///     solar flux for each spacecraft.
    #[pyo3(signature = (ephemeris=None))]
    fn compute(
        &self,
        py: Python<'_>,
        ephemeris: Option<&Bound<'_, PySpk>>,
    ) -> PyResult<PyPowerBudgetResults> {
        let scenario = &self.scenario;
        let step = self.step;
        let filter = self.filter.clone();

        // Auto-propagate if no ensemble was provided.
        let auto_ensemble;
        let ensemble = match &self.ensemble {
            Some(e) => e,
            None => {
                auto_ensemble = scenario
                    .propagate(&DefaultRotationProvider)
                    .map_err(|e| PyValueError::new_err(e.to_string()))?;
                &auto_ensemble
            }
        };

        let results = if let Some(spk_bound) = ephemeris {
            let spk = &spk_bound.get().0;
            py.detach(|| {
                let mut a = PowerBudgetAnalysis::new(scenario, ensemble, spk).with_step(step);
                if let Some(f) = &filter {
                    a = a.with_filter(f.clone());
                }
                a.compute()
            })
        } else {
            let analytical = AnalyticalSunEphemeris;
            py.detach(|| {
                let mut a =
                    PowerBudgetAnalysis::new(scenario, ensemble, &analytical).with_step(step);
                if let Some(f) = &filter {
                    a = a.with_filter(f.clone());
                }
                a.compute()
            })
        };

        Ok(PyPowerBudgetResults {
            results: results.map_err(PyPowerError)?,
        })
    }

    fn __repr__(&self) -> String {
        let sc_count = self.scenario.spacecraft().len();
        match &self.filter {
            Some(SpacecraftFilter::Ids(ids)) => format!(
                "PowerBudgetAnalysis({sc_count} spacecraft, filtered to {} ids)",
                ids.len()
            ),
            Some(SpacecraftFilter::Constellation(cid)) => {
                format!("PowerBudgetAnalysis({sc_count} spacecraft, constellation=\"{cid}\")",)
            }
            None => format!("PowerBudgetAnalysis({sc_count} spacecraft)"),
        }
    }
}

/// Convert a `TimeSeries<Tai>` to a `PyTimeSeries` (which uses `DynTimeScale`).
fn to_py_time_series(ts: &TimeSeries<Tai>) -> PyTimeSeries {
    let dyn_ts = TimeSeries::new(ts.epoch().into_dyn(), ts.series().clone());
    PyTimeSeries(dyn_ts)
}

/// Results of a power budget analysis.
///
/// Provides access to eclipse intervals, eclipse/sunlit fractions,
/// beta-angle time series, and solar-flux time series for each spacecraft.
#[pyclass(name = "PowerBudgetResults", module = "lox_space", frozen)]
pub struct PyPowerBudgetResults {
    results: PowerBudgetResults,
}

#[pymethods]
impl PyPowerBudgetResults {
    /// Eclipse intervals for a given spacecraft.
    ///
    /// Args:
    ///     id: Spacecraft identifier.
    ///
    /// Returns:
    ///     List of Interval objects, or empty list if id not found.
    fn eclipse_intervals(&self, id: &str) -> Vec<PyInterval> {
        let asset_id = AssetId::new(id);
        self.results
            .eclipse_intervals_for(&asset_id)
            .map(|intervals| {
                intervals
                    .iter()
                    .map(|i| {
                        PyInterval(TimeInterval::new(i.start().into_dyn(), i.end().into_dyn()))
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Eclipse fraction for a given spacecraft (0 = fully sunlit, 1 = always eclipsed).
    ///
    /// Args:
    ///     id: Spacecraft identifier.
    ///
    /// Returns:
    ///     Eclipse fraction as float, or None if id not found.
    fn eclipse_fraction(&self, id: &str) -> Option<f64> {
        self.results.eclipse_fraction(&AssetId::new(id))
    }

    /// Sunlit fraction for a given spacecraft (1 - eclipse_fraction).
    ///
    /// Args:
    ///     id: Spacecraft identifier.
    ///
    /// Returns:
    ///     Sunlit fraction as float, or None if id not found.
    fn sunlit_fraction(&self, id: &str) -> Option<f64> {
        self.results.sunlit_fraction(&AssetId::new(id))
    }

    /// Beta-angle time series for a given spacecraft (radians).
    ///
    /// Args:
    ///     id: Spacecraft identifier.
    ///
    /// Returns:
    ///     TimeSeries of beta angles in radians, or None if id not found.
    fn beta_angles(&self, id: &str) -> Option<PyTimeSeries> {
        let ts = self.results.beta_angles_for(&AssetId::new(id))?;
        Some(to_py_time_series(ts))
    }

    /// Solar-flux time series for a given spacecraft (W/m²).
    ///
    /// Args:
    ///     id: Spacecraft identifier.
    ///
    /// Returns:
    ///     TimeSeries of solar flux in W/m², or None if id not found.
    fn solar_flux(&self, id: &str) -> Option<PyTimeSeries> {
        let ts = self.results.solar_flux_for(&AssetId::new(id))?;
        Some(to_py_time_series(ts))
    }

    fn __repr__(&self) -> String {
        let n = self.results.all_eclipse_intervals().len();
        format!("PowerBudgetResults({n} spacecraft)")
    }
}

// ---------------------------------------------------------------------------
// Imaging Python bindings (optical + SAR)
// ---------------------------------------------------------------------------

struct PyAccessError(AccessError);

impl From<PyAccessError> for PyErr {
    fn from(err: PyAccessError) -> Self {
        PyValueError::new_err(err.0.to_string())
    }
}

/// An area of interest (AOI) defined as a geographic polygon.
///
/// Coordinates follow GeoJSON convention: longitude/latitude in degrees.
///
/// Args:
///     coords: List of (longitude, latitude) tuples in degrees forming the
///         polygon exterior ring. The ring should be closed (first == last).
#[pyclass(name = "Aoi", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PyAoi(pub Aoi);

#[pymethods]
impl PyAoi {
    #[new]
    fn new(coords: Vec<(f64, f64)>) -> Self {
        let line_string = geo::LineString::from(coords);
        let polygon = geo::Polygon::new(line_string, vec![]);
        PyAoi(Aoi::new(polygon))
    }

    /// Parse an AOI from a GeoJSON string.
    ///
    /// Expects a GeoJSON Polygon geometry, Feature containing a Polygon,
    /// or FeatureCollection containing a Feature with a Polygon.
    ///
    /// Args:
    ///     geojson: GeoJSON string.
    ///
    /// Returns:
    ///     Aoi parsed from the GeoJSON.
    #[classmethod]
    fn from_geojson(_cls: &Bound<'_, PyType>, geojson: &str) -> PyResult<Self> {
        let aoi = Aoi::from_geojson(geojson).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(PyAoi(aoi))
    }

    fn __repr__(&self) -> String {
        let n = self.0.polygon().exterior().0.len();
        format!("Aoi({n} vertices)")
    }
}

/// Optical imaging payload describing a spacecraft's ground coverage capability.
///
/// Defines the sensor's swath width and optional off-nadir pointing capability.
/// Assign to a spacecraft via the ``optical_payload`` parameter.
#[pyclass(name = "OpticalPayload", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug)]
pub struct PyOpticalPayload(pub OpticalPayload);

#[pymethods]
impl PyOpticalPayload {
    /// Create parameters for a nadir-only sensor.
    ///
    /// Args:
    ///     swath_width: Full swath width as Distance.
    ///
    /// Returns:
    ///     OpticalPayload for nadir-only imaging.
    #[classmethod]
    fn nadir_only(_cls: &Bound<'_, PyType>, swath_width: PyDistance) -> Self {
        PyOpticalPayload(OpticalPayload::nadir_only(swath_width.0))
    }

    /// Create parameters for a sensor with off-nadir pointing capability.
    ///
    /// Args:
    ///     swath_width: Full swath width as Distance.
    ///     max_off_nadir: Maximum off-nadir angle as Angle.
    ///
    /// Returns:
    ///     OpticalPayload for off-nadir imaging.
    #[classmethod]
    fn off_nadir(
        _cls: &Bound<'_, PyType>,
        swath_width: PyDistance,
        max_off_nadir: PyAngle,
    ) -> Self {
        PyOpticalPayload(OpticalPayload::off_nadir(swath_width.0, max_off_nadir.0))
    }

    fn __repr__(&self) -> String {
        "OpticalPayload(...)".to_string()
    }
}

/// AOI optical access analysis: computes imaging windows for spacecraft over AOIs.
///
/// Optical payloads are read from each spacecraft; spacecraft without an
/// optical payload are skipped.
///
/// Args:
///     scenario: Scenario containing spacecraft and time interval.
///         Spacecraft must have an ``optical_payload`` assigned.
///     aois: List of (id, Aoi) tuples defining the areas of interest.
///     ensemble: Optional pre-computed Ensemble. If not provided, the
///         scenario is propagated automatically.
///     step: Optional time step for event detection (default: 60s).
///     body_fixed_frame: Optional body-fixed frame override (e.g. "ITRF").
///         Defaults to IAU frame of the scenario's origin.
#[pyclass(name = "OpticalAccessAnalysis", module = "lox_space", frozen)]
pub struct PyOpticalAccessAnalysis {
    scenario: DynScenario,
    aois: Vec<(AoiId, Aoi)>,
    ensemble: Option<Ensemble<AssetId, Tai, DynOrigin, DynFrame>>,
    step: TimeDelta,
    body_fixed_frame: Option<DynFrame>,
}

#[pymethods]
impl PyOpticalAccessAnalysis {
    #[new]
    #[pyo3(signature = (scenario, aois, ensemble=None, step=None, body_fixed_frame=None))]
    fn new(
        scenario: PyScenario,
        aois: Vec<(String, PyAoi)>,
        ensemble: Option<PyEnsemble>,
        step: Option<PyTimeDelta>,
        body_fixed_frame: Option<PyFrame>,
    ) -> Self {
        let aois = aois
            .into_iter()
            .map(|(id, aoi)| (AoiId::new(id), aoi.0))
            .collect();
        Self {
            scenario: scenario.0,
            aois,
            ensemble: ensemble.map(|e| e.0),
            step: step
                .map(|s| s.0)
                .unwrap_or_else(|| TimeDelta::from_seconds_f64(60.0)),
            body_fixed_frame: body_fixed_frame.map(|f| f.0),
        }
    }

    /// Compute optical access intervals for all (spacecraft, AOI) pairs.
    ///
    /// If no ensemble was provided at construction, the scenario is
    /// propagated automatically (trajectories transformed to ICRF).
    ///
    /// Returns:
    ///     AccessResults containing intervals for all pairs.
    fn compute(&self, py: Python<'_>) -> PyResult<PyAccessResults> {
        let scenario = &self.scenario;
        let step = self.step;
        let body_fixed_frame = self.body_fixed_frame;

        // Auto-propagate if no ensemble was provided.
        let auto_ensemble;
        let ensemble = match &self.ensemble {
            Some(e) => e,
            None => {
                auto_ensemble = scenario
                    .propagate(&DefaultRotationProvider)
                    .map_err(|e| PyValueError::new_err(e.to_string()))?;
                &auto_ensemble
            }
        };

        let aois = self.aois.clone();

        let results = py.detach(|| {
            let mut analysis = OpticalAccessAnalysis::new(scenario, ensemble, aois).with_step(step);
            if let Some(frame) = body_fixed_frame {
                analysis = analysis.with_body_fixed_frame(frame);
            }
            analysis.compute()
        });

        Ok(PyAccessResults {
            results: results.map_err(PyAccessError)?,
        })
    }

    fn __repr__(&self) -> String {
        let sc_count = self.scenario.spacecraft().len();
        let aoi_count = self.aois.len();
        let aoi_label = if aoi_count == 1 { "AOI" } else { "AOIs" };
        format!("OpticalAccessAnalysis({sc_count} spacecraft, {aoi_count} {aoi_label})")
    }
}

/// Direction of orbital motion at the time of an access window.
#[pyclass(
    name = "PassDirection",
    module = "lox_space",
    eq,
    eq_int,
    hash,
    frozen,
    from_py_object
)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PyPassDirection {
    /// Spacecraft is moving from south to north at the access midpoint.
    Ascending,
    /// Spacecraft is moving from north to south at the access midpoint.
    Descending,
}

impl From<PyPassDirection> for crate::analysis::imaging::PassDirection {
    fn from(d: PyPassDirection) -> Self {
        match d {
            PyPassDirection::Ascending => Self::Ascending,
            PyPassDirection::Descending => Self::Descending,
        }
    }
}

impl From<crate::analysis::imaging::PassDirection> for PyPassDirection {
    fn from(d: crate::analysis::imaging::PassDirection) -> Self {
        match d {
            crate::analysis::imaging::PassDirection::Ascending => Self::Ascending,
            crate::analysis::imaging::PassDirection::Descending => Self::Descending,
        }
    }
}

/// A single access window: time interval + pass direction at the midpoint.
#[pyclass(name = "AccessWindow", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Copy)]
pub struct PyAccessWindow(pub crate::analysis::imaging::AccessWindow);

#[pymethods]
impl PyAccessWindow {
    /// The access time interval.
    fn interval(&self) -> PyInterval {
        PyInterval(TimeInterval::new(
            self.0.interval.start().into_dyn(),
            self.0.interval.end().into_dyn(),
        ))
    }

    /// The spacecraft pass direction at the interval midpoint.
    fn direction(&self) -> PyPassDirection {
        self.0.direction.into()
    }

    fn __repr__(&self) -> String {
        let dir = match self.0.direction {
            crate::analysis::imaging::PassDirection::Ascending => "Ascending",
            crate::analysis::imaging::PassDirection::Descending => "Descending",
        };
        format!(
            "AccessWindow({}{}, {dir})",
            self.0.interval.start(),
            self.0.interval.end(),
        )
    }
}

/// Results of an imaging access analysis (optical or SAR).
///
/// Provides access windows for each (spacecraft, AOI) pair.
#[pyclass(name = "AccessResults", module = "lox_space", frozen)]
pub struct PyAccessResults {
    results: crate::analysis::imaging::AccessResults,
}

#[pymethods]
impl PyAccessResults {
    /// Return access windows for a specific (spacecraft, AOI) pair.
    ///
    /// Args:
    ///     spacecraft_id: Spacecraft identifier.
    ///     aoi_id: AOI identifier.
    ///
    /// Returns:
    ///     List of AccessWindow objects, or empty list if pair not found.
    fn windows(&self, spacecraft_id: &str, aoi_id: &str) -> Vec<PyAccessWindow> {
        let sc_id = AssetId::new(spacecraft_id);
        let aoi_id = AoiId::new(aoi_id);
        self.results
            .windows(&sc_id, &aoi_id)
            .iter()
            .map(|w| PyAccessWindow(*w))
            .collect()
    }

    /// Return all access windows for all (spacecraft, AOI) pairs.
    ///
    /// Returns:
    ///     Dictionary mapping (spacecraft_id, aoi_id) to list of AccessWindow objects.
    fn all_windows(&self) -> HashMap<(String, String), Vec<PyAccessWindow>> {
        self.results
            .all_windows()
            .iter()
            .map(|((sc_id, aoi_id), windows)| {
                (
                    (sc_id.as_str().to_string(), aoi_id.as_str().to_string()),
                    windows.iter().map(|w| PyAccessWindow(*w)).collect(),
                )
            })
            .collect()
    }

    fn __repr__(&self) -> String {
        let n = self.results.num_pairs();
        let label = if n == 1 { "pair" } else { "pairs" };
        format!("AccessResults({n} {label})")
    }
}

// ---------------------------------------------------------------------------
// SAR Python bindings: LookSide, SarPayload, SarAccessAnalysis
// ---------------------------------------------------------------------------

/// Which side of the ground track a SAR payload can image.
#[pyclass(
    name = "LookSide",
    module = "lox_space",
    eq,
    eq_int,
    hash,
    frozen,
    from_py_object
)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PyLookSide {
    /// SAR payload images to the left of the ground track.
    Left,
    /// SAR payload images to the right of the ground track.
    Right,
    /// SAR payload can image on either side of the ground track.
    Either,
}

impl From<PyLookSide> for LookSide {
    fn from(s: PyLookSide) -> Self {
        match s {
            PyLookSide::Left => LookSide::Left,
            PyLookSide::Right => LookSide::Right,
            PyLookSide::Either => LookSide::Either,
        }
    }
}

impl From<LookSide> for PyLookSide {
    fn from(s: LookSide) -> Self {
        match s {
            LookSide::Left => PyLookSide::Left,
            LookSide::Right => PyLookSide::Right,
            LookSide::Either => PyLookSide::Either,
        }
    }
}

/// SAR (Synthetic Aperture Radar) payload — side-looking annular access geometry.
///
/// Construct via :meth:`with_look_angles` (look angle at the satellite) or
/// :meth:`with_incidence_angles` (incidence angle at the ground point).
///
/// Assign to a spacecraft via the ``sar_payload`` parameter.
///
/// ```python
/// import lox_space as lox
/// payload = lox.SarPayload.with_incidence_angles(29.0 * lox.deg, 46.0 * lox.deg, lox.LookSide.Right)
/// sc = lox.Spacecraft("sat1", orbit, sar_payload=payload)
/// ```
#[pyclass(name = "SarPayload", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Copy)]
pub struct PySarPayload(pub SarPayload);

#[pymethods]
impl PySarPayload {
    /// Constructs a SAR payload from a look-angle envelope.
    ///
    /// Args:
    ///     min: Minimum look angle (off-nadir at the satellite).
    ///     max: Maximum look angle (off-nadir at the satellite).
    ///     side: Which side of the ground track the payload can image.
    ///
    /// Returns:
    ///     SarPayload for the given envelope.
    ///
    /// Raises:
    ///     ValueError: if min ≥ max or either angle is outside [0°, 90°).
    #[classmethod]
    fn with_look_angles(
        _cls: &Bound<'_, PyType>,
        min: PyAngle,
        max: PyAngle,
        side: PyLookSide,
    ) -> PyResult<Self> {
        SarPayload::with_look_angles(min.0, max.0, side.into())
            .map(PySarPayload)
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }

    /// Constructs a SAR payload from an incidence-angle envelope.
    ///
    /// Args:
    ///     min: Minimum incidence angle (off-vertical at the ground point).
    ///     max: Maximum incidence angle (off-vertical at the ground point).
    ///     side: Which side of the ground track the payload can image.
    ///
    /// Returns:
    ///     SarPayload for the given envelope.
    ///
    /// Raises:
    ///     ValueError: if min ≥ max or either angle is outside [0°, 90°).
    #[classmethod]
    fn with_incidence_angles(
        _cls: &Bound<'_, PyType>,
        min: PyAngle,
        max: PyAngle,
        side: PyLookSide,
    ) -> PyResult<Self> {
        SarPayload::with_incidence_angles(min.0, max.0, side.into())
            .map(PySarPayload)
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }

    /// Returns the configured looking side.
    fn side(&self) -> PyLookSide {
        self.0.side().into()
    }

    fn __repr__(&self) -> String {
        "SarPayload(...)".to_string()
    }
}

/// AOI SAR access analysis: computes imaging windows for SAR spacecraft over AOIs.
///
/// SAR payloads are read from each spacecraft; spacecraft without a SAR
/// payload are skipped.
///
/// Args:
///     scenario: Scenario containing spacecraft and time interval.
///         Spacecraft must have a ``sar_payload`` assigned.
///     aois: List of (id, Aoi) tuples defining the areas of interest.
///     ensemble: Optional pre-computed Ensemble. If not provided, the
///         scenario is propagated automatically.
///     step: Optional time step for event detection (default: 60s).
///     body_fixed_frame: Optional body-fixed frame override (e.g. "ITRF").
///         Defaults to IAU frame of the scenario's origin.
#[pyclass(name = "SarAccessAnalysis", module = "lox_space", frozen)]
pub struct PySarAccessAnalysis {
    scenario: DynScenario,
    aois: Vec<(AoiId, Aoi)>,
    ensemble: Option<Ensemble<AssetId, Tai, DynOrigin, DynFrame>>,
    step: TimeDelta,
    body_fixed_frame: Option<DynFrame>,
}

#[pymethods]
impl PySarAccessAnalysis {
    #[new]
    #[pyo3(signature = (scenario, aois, ensemble=None, step=None, body_fixed_frame=None))]
    fn new(
        scenario: PyScenario,
        aois: Vec<(String, PyAoi)>,
        ensemble: Option<PyEnsemble>,
        step: Option<PyTimeDelta>,
        body_fixed_frame: Option<PyFrame>,
    ) -> Self {
        let aois = aois
            .into_iter()
            .map(|(id, aoi)| (AoiId::new(id), aoi.0))
            .collect();
        Self {
            scenario: scenario.0,
            aois,
            ensemble: ensemble.map(|e| e.0),
            step: step
                .map(|s| s.0)
                .unwrap_or_else(|| TimeDelta::from_seconds_f64(60.0)),
            body_fixed_frame: body_fixed_frame.map(|f| f.0),
        }
    }

    /// Compute SAR access intervals for all (spacecraft, AOI) pairs.
    ///
    /// If no ensemble was provided at construction, the scenario is
    /// propagated automatically (trajectories transformed to ICRF).
    ///
    /// Returns:
    ///     AccessResults containing intervals for all pairs.
    fn compute(&self, py: Python<'_>) -> PyResult<PyAccessResults> {
        let scenario = &self.scenario;
        let step = self.step;
        let body_fixed_frame = self.body_fixed_frame;

        // Auto-propagate if no ensemble was provided.
        let auto_ensemble;
        let ensemble = match &self.ensemble {
            Some(e) => e,
            None => {
                auto_ensemble = scenario
                    .propagate(&DefaultRotationProvider)
                    .map_err(|e| PyValueError::new_err(e.to_string()))?;
                &auto_ensemble
            }
        };

        let aois = self.aois.clone();

        let results = py.detach(|| {
            let mut analysis = SarAccessAnalysis::new(scenario, ensemble, aois).with_step(step);
            if let Some(frame) = body_fixed_frame {
                analysis = analysis.with_body_fixed_frame(frame);
            }
            analysis.compute()
        });

        Ok(PyAccessResults {
            results: results.map_err(PyAccessError)?,
        })
    }

    fn __repr__(&self) -> String {
        let sc_count = self.scenario.spacecraft().len();
        let aoi_count = self.aois.len();
        let aoi_label = if aoi_count == 1 { "AOI" } else { "AOIs" };
        format!("SarAccessAnalysis({sc_count} spacecraft, {aoi_count} {aoi_label})")
    }
}