orts 0.1.0

Orts core — orbital mechanics simulation, force/torque/sensor models, and WASM plugin host runtime.
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
use std::ops::ControlFlow;
use std::sync::Arc;

use nalgebra::Vector3;
use utsuroi::{
    AdvanceOutcome, AdvanceOutcome853, Dop853, DormandPrince, DynamicalSystem, IntegrationError,
    Integrator, OdeState, Rk4, Tolerances,
};

use super::prop_group::{GroupSnapshot, PropGroupOutcome, SatId, SatelliteTermination};
use super::state::GroupState;
use super::{FromAcceleration, HasPosition, IntegratorConfig};

/// Context passed to [`InterSatelliteForce::acceleration_pair`].
///
/// Marked `#[non_exhaustive]` so that future fields (e.g., `vel_i`, `vel_j`
/// for velocity-dependent forces) can be added without breaking existing
/// implementations.
#[non_exhaustive]
pub struct PairContext<'a> {
    pub t: f64,
    pub pos_i: &'a Vector3<f64>,
    pub pos_j: &'a Vector3<f64>,
}

/// A pairwise force between two satellites.
///
/// Returns accelerations (not forces) on each satellite of the pair.
/// Newton's third law compliance is the implementor's responsibility.
pub trait InterSatelliteForce: Send + Sync {
    fn name(&self) -> &str;
    fn acceleration_pair(&self, ctx: &PairContext<'_>) -> (Vector3<f64>, Vector3<f64>);
}

/// A specific satellite-pair interaction: indices into the group + force model.
pub struct InteractionPair {
    pub i: usize,
    pub j: usize,
    pub force: Arc<dyn InterSatelliteForce>,
}

/// Mutual gravitational attraction between two bodies.
///
/// `mu_i = G * m_i` and `mu_j = G * m_j` in km³/s².
/// Newton's third law: `m_i * a_i + m_j * a_j = 0`.
///
/// For `r < 1e-10 km`, returns zero accelerations (singularity guard).
pub struct MutualGravity {
    pub mu_i: f64,
    pub mu_j: f64,
}

impl InterSatelliteForce for MutualGravity {
    fn name(&self) -> &str {
        "mutual_gravity"
    }

    fn acceleration_pair(&self, ctx: &PairContext<'_>) -> (Vector3<f64>, Vector3<f64>) {
        let r_vec = ctx.pos_j - ctx.pos_i; // from i toward j
        let r_sq = r_vec.magnitude_squared();
        if r_sq < 1e-20 {
            return (Vector3::zeros(), Vector3::zeros());
        }
        let r = r_sq.sqrt();
        let r_cubed = r * r_sq;
        let a_i = (self.mu_j / r_cubed) * r_vec;
        let a_j = -(self.mu_i / r_cubed) * r_vec;
        (a_i, a_j)
    }
}

/// Equal-mass spring force for testing coupled dynamics.
///
/// **Assumes equal mass**: `a_j = -a_i` holds only when `m_i = m_j`.
/// For unequal masses, use a separate force/mass formulation.
/// This is intentionally simplified for analytical solution testing:
/// relative motion is simple harmonic with period `2π/√(2k)`.
///
/// For `|r| < 1e-10 km`, returns zero accelerations (singularity guard).
pub struct Spring {
    pub stiffness: f64,
    pub rest_length: f64,
}

impl InterSatelliteForce for Spring {
    fn name(&self) -> &str {
        "spring"
    }

    fn acceleration_pair(&self, ctx: &PairContext<'_>) -> (Vector3<f64>, Vector3<f64>) {
        let r_vec = ctx.pos_j - ctx.pos_i;
        let r = r_vec.magnitude();
        if r < 1e-10 {
            return (Vector3::zeros(), Vector3::zeros());
        }
        let r_hat = r_vec / r;
        let a_i = self.stiffness * (r - self.rest_length) * r_hat;
        let a_j = -a_i;
        (a_i, a_j)
    }
}

/// Extracted data returned by [`CoupledGroup::into_parts`].
///
/// Contains everything needed to transfer satellites back to the Scheduler.
/// Interactions are NOT returned; the Scheduler holds `Arc` references
/// to forces and re-clones them into new ephemeral groups.
pub struct CoupledGroupParts<S, D> {
    pub ids: Vec<SatId>,
    pub states: Vec<S>,
    pub dynamics: Vec<D>,
    pub t: f64,
    pub terminated: bool,
    pub termination: Option<SatelliteTermination>,
    /// `true` if termination was caused by a `ControlFlow::Break` event
    /// (only the triggering satellite is "dead"). `false` for integration
    /// errors where the composite ODE state is corrupted.
    pub is_event_termination: bool,
}

/// Coupled group dynamics: each satellite's derivatives plus inter-satellite
/// force contributions, integrated as a single ODE.
pub struct CoupledGroupDynamics<D: DynamicalSystem>
where
    D::State: HasPosition + FromAcceleration,
{
    pub(crate) dynamics: Vec<D>,
    pub(crate) interactions: Vec<InteractionPair>,
}

impl<D: DynamicalSystem> CoupledGroupDynamics<D>
where
    D::State: HasPosition + FromAcceleration,
{
    pub fn new(dynamics: Vec<D>, interactions: Vec<InteractionPair>) -> Self {
        Self {
            dynamics,
            interactions,
        }
    }
}

impl<D: DynamicalSystem> DynamicalSystem for CoupledGroupDynamics<D>
where
    D::State: HasPosition + FromAcceleration,
{
    type State = GroupState<D::State>;

    fn derivatives(&self, t: f64, state: &GroupState<D::State>) -> GroupState<D::State> {
        assert_eq!(
            self.dynamics.len(),
            state.states.len(),
            "CoupledGroupDynamics: dynamics count ({}) != state count ({})",
            self.dynamics.len(),
            state.states.len()
        );

        // 1. Per-satellite derivatives (gravity, drag, etc.)
        let mut derivs: Vec<D::State> = self
            .dynamics
            .iter()
            .zip(&state.states)
            .map(|(d, s)| d.derivatives(t, s))
            .collect();

        // 2. Add inter-satellite force accelerations
        for pair in &self.interactions {
            assert!(
                pair.i < state.states.len() && pair.j < state.states.len(),
                "InteractionPair indices ({}, {}) out of range for {} satellites",
                pair.i,
                pair.j,
                state.states.len()
            );

            let pos_i = state.states[pair.i].position();
            let pos_j = state.states[pair.j].position();
            let ctx = PairContext {
                t,
                pos_i: &pos_i,
                pos_j: &pos_j,
            };
            let (a_i, a_j) = pair.force.acceleration_pair(&ctx);
            derivs[pair.i] = derivs[pair.i].axpy(1.0, &D::State::from_acceleration(a_i));
            derivs[pair.j] = derivs[pair.j].axpy(1.0, &D::State::from_acceleration(a_j));
        }

        GroupState { states: derivs }
    }
}

// ── CoupledGroup (PropGroup impl) ──────────────────────────────────────────

type EventChecker<S> = Box<dyn Fn(f64, &S) -> ControlFlow<String> + Send>;

/// Group of coupled satellites integrated as a single ODE.
///
/// All satellites share a single adaptive/fixed stepper and advance with
/// a common time step. If any satellite triggers an event, the entire
/// group terminates (the stepper cannot continue without that satellite).
pub struct CoupledGroup<D: DynamicalSystem>
where
    D::State: HasPosition + FromAcceleration,
{
    ids: Vec<SatId>,
    dynamics: CoupledGroupDynamics<D>,
    state: GroupState<D::State>,
    t: f64,
    terminated: bool,
    termination: Option<SatelliteTermination>,
    is_event_termination: bool,
    integrator: IntegratorConfig,
    event_checker: Option<EventChecker<D::State>>,
}

impl<D: DynamicalSystem> CoupledGroup<D>
where
    D::State: HasPosition + FromAcceleration,
{
    pub fn new(integrator: IntegratorConfig) -> Self {
        Self {
            ids: Vec::new(),
            dynamics: CoupledGroupDynamics::new(Vec::new(), Vec::new()),
            state: GroupState::new(Vec::new()),
            t: 0.0,
            terminated: false,
            termination: None,
            is_event_termination: false,
            integrator,
            event_checker: None,
        }
    }

    pub fn dp45(dt: f64, tolerances: Tolerances) -> Self {
        Self::new(IntegratorConfig::Dp45 { dt, tolerances })
    }

    pub fn rk4(dt: f64) -> Self {
        Self::new(IntegratorConfig::Rk4 { dt })
    }

    pub fn with_event_checker(
        mut self,
        checker: impl Fn(f64, &D::State) -> ControlFlow<String> + Send + 'static,
    ) -> Self {
        self.event_checker = Some(Box::new(checker));
        self
    }

    pub fn add_satellite(mut self, id: impl Into<SatId>, state: D::State, dynamics: D) -> Self {
        self.ids.push(id.into());
        self.dynamics.dynamics.push(dynamics);
        self.state.states.push(state);
        self
    }

    pub fn with_interaction(
        mut self,
        i: usize,
        j: usize,
        force: Arc<dyn InterSatelliteForce>,
    ) -> Self {
        self.dynamics
            .interactions
            .push(InteractionPair { i, j, force });
        self
    }

    /// Add a satellite to an already-constructed group (mutable reference).
    ///
    /// Unlike [`add_satellite`](Self::add_satellite) (builder pattern, consumes self),
    /// this method borrows `&mut self` for use by the Scheduler when building
    /// ephemeral groups.
    pub fn push_satellite(&mut self, id: impl Into<SatId>, state: D::State, dynamics: D) {
        self.ids.push(id.into());
        self.dynamics.dynamics.push(dynamics);
        self.state.states.push(state);
    }

    /// Add an interaction to an already-constructed group (mutable reference).
    pub fn push_interaction(&mut self, i: usize, j: usize, force: Arc<dyn InterSatelliteForce>) {
        self.dynamics
            .interactions
            .push(InteractionPair { i, j, force });
    }

    /// Set the current time for this group.
    ///
    /// Used by the Scheduler to set the start time of an ephemeral group.
    pub fn set_t(&mut self, t: f64) {
        self.t = t;
    }

    /// Consume the group, returning all satellite data and dynamics.
    ///
    /// Used by the Scheduler to recover state and dynamics after ephemeral
    /// group propagation. Interactions are NOT returned; the Scheduler
    /// holds `Arc` references to forces and re-clones them.
    pub fn into_parts(self) -> CoupledGroupParts<D::State, D> {
        CoupledGroupParts {
            ids: self.ids,
            states: self.state.states,
            dynamics: self.dynamics.dynamics,
            t: self.t,
            terminated: self.terminated,
            termination: self.termination,
            is_event_termination: self.is_event_termination,
        }
    }

    pub fn group_state(&self) -> &GroupState<D::State> {
        &self.state
    }

    pub fn current_t(&self) -> f64 {
        self.t
    }

    pub fn is_terminated(&self) -> bool {
        self.terminated
    }

    pub fn propagate_to(&mut self, t_target: f64) -> Result<PropGroupOutcome, IntegrationError> {
        if self.terminated || self.t >= t_target {
            return Ok(PropGroupOutcome {
                terminations: Vec::new(),
            });
        }

        match &self.integrator {
            IntegratorConfig::Dp45 { dt, tolerances } => {
                let mut stepper = DormandPrince.stepper(
                    &self.dynamics,
                    self.state.clone(),
                    self.t,
                    *dt,
                    tolerances.clone(),
                );

                // Build group-level event checker that iterates over all satellites
                let ids = self.ids.clone();
                let event_checker = &self.event_checker;

                let result = if let Some(checker) = event_checker {
                    stepper.advance_to(
                        t_target,
                        |_, _| {},
                        |t: f64, gs: &GroupState<D::State>| {
                            for (id, sat_state) in ids.iter().zip(&gs.states) {
                                if let ControlFlow::Break(reason) = checker(t, sat_state) {
                                    return ControlFlow::Break((id.clone(), reason));
                                }
                            }
                            ControlFlow::Continue(())
                        },
                    )
                } else {
                    stepper.advance_to(
                        t_target,
                        |_, _| {},
                        |_: f64, _: &GroupState<D::State>| {
                            ControlFlow::<(SatId, String)>::Continue(())
                        },
                    )
                };

                match result {
                    Ok(AdvanceOutcome::Reached) => {
                        self.state = stepper.into_state();
                        self.t = t_target;
                        Ok(PropGroupOutcome {
                            terminations: Vec::new(),
                        })
                    }
                    Ok(AdvanceOutcome::Event {
                        reason: (sat_id, reason),
                    }) => {
                        let t = stepper.t();
                        self.state = stepper.into_state();
                        self.t = t;
                        self.terminated = true;
                        self.is_event_termination = true;
                        let term = SatelliteTermination {
                            satellite_id: sat_id,
                            t,
                            reason,
                        };
                        self.termination = Some(term.clone());
                        Ok(PropGroupOutcome {
                            terminations: vec![term],
                        })
                    }
                    Err(e) => {
                        self.terminated = true;
                        let t = match &e {
                            IntegrationError::NonFiniteState { t } => *t,
                            IntegrationError::StepSizeTooSmall { t, .. } => *t,
                        };
                        let term = SatelliteTermination {
                            satellite_id: self
                                .ids
                                .first()
                                .cloned()
                                .unwrap_or_else(|| SatId::from("unknown")),
                            t,
                            reason: format!("{e:?}"),
                        };
                        self.termination = Some(term.clone());
                        Ok(PropGroupOutcome {
                            terminations: vec![term],
                        })
                    }
                }
            }
            IntegratorConfig::Dop853 { dt, tolerances } => {
                let mut stepper = Dop853.stepper(
                    &self.dynamics,
                    self.state.clone(),
                    self.t,
                    *dt,
                    tolerances.clone(),
                );

                let ids = self.ids.clone();
                let event_checker = &self.event_checker;

                let result = if let Some(checker) = event_checker {
                    stepper.advance_to(
                        t_target,
                        |_, _| {},
                        |t: f64, gs: &GroupState<D::State>| {
                            for (id, sat_state) in ids.iter().zip(&gs.states) {
                                if let ControlFlow::Break(reason) = checker(t, sat_state) {
                                    return ControlFlow::Break((id.clone(), reason));
                                }
                            }
                            ControlFlow::Continue(())
                        },
                    )
                } else {
                    stepper.advance_to(
                        t_target,
                        |_, _| {},
                        |_: f64, _: &GroupState<D::State>| {
                            ControlFlow::<(SatId, String)>::Continue(())
                        },
                    )
                };

                match result {
                    Ok(AdvanceOutcome853::Reached) => {
                        self.state = stepper.into_state();
                        self.t = t_target;
                        Ok(PropGroupOutcome {
                            terminations: Vec::new(),
                        })
                    }
                    Ok(AdvanceOutcome853::Event {
                        reason: (sat_id, reason),
                    }) => {
                        let t = stepper.t();
                        self.state = stepper.into_state();
                        self.t = t;
                        self.terminated = true;
                        self.is_event_termination = true;
                        let term = SatelliteTermination {
                            satellite_id: sat_id,
                            t,
                            reason,
                        };
                        self.termination = Some(term.clone());
                        Ok(PropGroupOutcome {
                            terminations: vec![term],
                        })
                    }
                    Err(e) => {
                        self.terminated = true;
                        let t = match &e {
                            IntegrationError::NonFiniteState { t } => *t,
                            IntegrationError::StepSizeTooSmall { t, .. } => *t,
                        };
                        let term = SatelliteTermination {
                            satellite_id: self
                                .ids
                                .first()
                                .cloned()
                                .unwrap_or_else(|| SatId::from("unknown")),
                            t,
                            reason: format!("{e:?}"),
                        };
                        self.termination = Some(term.clone());
                        Ok(PropGroupOutcome {
                            terminations: vec![term],
                        })
                    }
                }
            }
            IntegratorConfig::Rk4 { dt } => {
                let dt = *dt;
                let mut current_t = self.t;
                let mut current_state = self.state.clone();

                while current_t < t_target - 1e-12 {
                    let h = dt.min(t_target - current_t);
                    current_state = Rk4.step(&self.dynamics, current_t, &current_state, h);
                    current_t += h;

                    if !current_state.is_finite() {
                        self.state = current_state;
                        self.t = current_t;
                        self.terminated = true;
                        let term = SatelliteTermination {
                            satellite_id: self
                                .ids
                                .first()
                                .cloned()
                                .unwrap_or_else(|| SatId::from("unknown")),
                            t: current_t,
                            reason: "NonFiniteState".to_string(),
                        };
                        self.termination = Some(term.clone());
                        return Ok(PropGroupOutcome {
                            terminations: vec![term],
                        });
                    }

                    if let Some(ref checker) = self.event_checker {
                        for (id, sat_state) in self.ids.iter().zip(&current_state.states) {
                            if let ControlFlow::Break(reason) = checker(current_t, sat_state) {
                                self.state = current_state;
                                self.t = current_t;
                                self.terminated = true;
                                self.is_event_termination = true;
                                let term = SatelliteTermination {
                                    satellite_id: id.clone(),
                                    t: current_t,
                                    reason,
                                };
                                self.termination = Some(term.clone());
                                return Ok(PropGroupOutcome {
                                    terminations: vec![term],
                                });
                            }
                        }
                    }
                }

                self.state = current_state;
                self.t = current_t;
                Ok(PropGroupOutcome {
                    terminations: Vec::new(),
                })
            }
        }
    }

    pub fn snapshot(&self) -> GroupSnapshot {
        if self.terminated {
            return GroupSnapshot {
                positions: Vec::new(),
            };
        }
        GroupSnapshot {
            positions: self
                .ids
                .iter()
                .zip(&self.state.states)
                .map(|(id, s)| (id.clone(), s.position()))
                .collect(),
        }
    }
}

impl<D: DynamicalSystem + Send> super::prop_group::PropGroup for CoupledGroup<D>
where
    D::State: HasPosition + FromAcceleration + Send,
{
    fn ids(&self) -> Vec<SatId> {
        self.ids.clone()
    }

    fn propagate_to(&mut self, t_target: f64) -> Result<PropGroupOutcome, IntegrationError> {
        self.propagate_to(t_target)
    }

    fn snapshot(&self) -> GroupSnapshot {
        self.snapshot()
    }
}

#[cfg(test)]
mod tests {
    use super::super::prop_group::PropGroup;
    use super::*;
    use crate::OrbitalState;
    use nalgebra::Vector3;
    use utsuroi::{Integrator, Rk4, Tolerances};

    // ── InterSatelliteForce tests ──────────────────────────────────────────

    fn pair_ctx<'a>(t: f64, pos_i: &'a Vector3<f64>, pos_j: &'a Vector3<f64>) -> PairContext<'a> {
        PairContext { t, pos_i, pos_j }
    }

    #[test]
    fn mutual_gravity_newton_third_law() {
        // Newton's 3rd: F_i + F_j = 0, i.e., m_i * a_i + m_j * a_j = 0
        // Since mu = G*m, this is: mu_i * a_i + mu_j * a_j = 0
        let mg = MutualGravity {
            mu_i: 1.0,
            mu_j: 2.0,
        };
        let pi = Vector3::new(0.0, 0.0, 0.0);
        let pj = Vector3::new(10.0, 0.0, 0.0);
        let (a_i, a_j) = mg.acceleration_pair(&pair_ctx(0.0, &pi, &pj));

        // a_i = mu_j/r³ * r_vec, a_j = -mu_i/r³ * r_vec
        // mu_i * a_i = mu_i * mu_j / r³ * r_vec
        // mu_j * a_j = -mu_j * mu_i / r³ * r_vec
        // Sum = 0 ✓
        let momentum_check = mg.mu_i * a_i + mg.mu_j * a_j;
        assert!(momentum_check.magnitude() < 1e-15);
    }

    #[test]
    fn mutual_gravity_inverse_square() {
        let mg = MutualGravity {
            mu_i: 1.0,
            mu_j: 1.0,
        };
        let pi = Vector3::zeros();
        let pj1 = Vector3::new(1.0, 0.0, 0.0);
        let pj2 = Vector3::new(2.0, 0.0, 0.0);

        let (a1, _) = mg.acceleration_pair(&pair_ctx(0.0, &pi, &pj1));
        let (a2, _) = mg.acceleration_pair(&pair_ctx(0.0, &pi, &pj2));

        // At double distance, acceleration should be 1/4
        let ratio = a1.magnitude() / a2.magnitude();
        assert!((ratio - 4.0).abs() < 1e-12);
    }

    #[test]
    fn mutual_gravity_symmetric() {
        let mg = MutualGravity {
            mu_i: 3.0,
            mu_j: 3.0,
        };
        let pi = Vector3::new(-5.0, 0.0, 0.0);
        let pj = Vector3::new(5.0, 0.0, 0.0);
        let (a_i, a_j) = mg.acceleration_pair(&pair_ctx(0.0, &pi, &pj));

        assert!((a_i.magnitude() - a_j.magnitude()).abs() < 1e-15);
        // Directions should be opposite
        assert!((a_i + a_j).magnitude() < 1e-15);
    }

    #[test]
    fn mutual_gravity_singularity_guard() {
        let mg = MutualGravity {
            mu_i: 1.0,
            mu_j: 1.0,
        };
        let p = Vector3::new(1.0, 2.0, 3.0);
        let (a_i, a_j) = mg.acceleration_pair(&pair_ctx(0.0, &p, &p));

        assert_eq!(a_i, Vector3::zeros());
        assert_eq!(a_j, Vector3::zeros());
    }

    #[test]
    fn spring_equilibrium_zero_force() {
        let spring = Spring {
            stiffness: 1.0,
            rest_length: 10.0,
        };
        let pi = Vector3::new(0.0, 0.0, 0.0);
        let pj = Vector3::new(10.0, 0.0, 0.0); // exactly rest_length apart
        let (a_i, a_j) = spring.acceleration_pair(&pair_ctx(0.0, &pi, &pj));

        assert!(a_i.magnitude() < 1e-15);
        assert!(a_j.magnitude() < 1e-15);
    }

    #[test]
    fn spring_newton_third_law() {
        let spring = Spring {
            stiffness: 2.0,
            rest_length: 5.0,
        };
        let pi = Vector3::new(1.0, 2.0, 3.0);
        let pj = Vector3::new(4.0, 6.0, 8.0);
        let (a_i, a_j) = spring.acceleration_pair(&pair_ctx(0.0, &pi, &pj));

        // Equal-mass: a_j = -a_i
        assert!((a_i + a_j).magnitude() < 1e-15);
    }

    #[test]
    fn spring_singularity_guard() {
        let spring = Spring {
            stiffness: 1.0,
            rest_length: 5.0,
        };
        let p = Vector3::new(1.0, 2.0, 3.0);
        let (a_i, a_j) = spring.acceleration_pair(&pair_ctx(0.0, &p, &p));

        assert_eq!(a_i, Vector3::zeros());
        assert_eq!(a_j, Vector3::zeros());
    }

    // ── CoupledGroupDynamics tests ─────────────────────────────────────────

    use crate::orbital::two_body::TwoBodySystem;

    fn iss_state() -> OrbitalState {
        let r: f64 = 6778.137;
        let v = (398600.4418_f64 / r).sqrt();
        OrbitalState::new(Vector3::new(r, 0.0, 0.0), Vector3::new(0.0, v, 0.0))
    }

    fn sso_state() -> OrbitalState {
        let r: f64 = 6378.137 + 800.0;
        let v = (398600.4418_f64 / r).sqrt();
        OrbitalState::new(Vector3::new(r, 0.0, 0.0), Vector3::new(0.0, v, 0.0))
    }

    #[test]
    fn no_interactions_matches_independent() {
        use super::super::IndependentGroupDynamics;

        let mu = 398600.4418;
        let coupled = CoupledGroupDynamics::new(
            vec![TwoBodySystem { mu }, TwoBodySystem { mu }],
            vec![], // no interactions
        );
        let independent =
            IndependentGroupDynamics::new(vec![TwoBodySystem { mu }, TwoBodySystem { mu }]);

        let state = GroupState::new(vec![iss_state(), sso_state()]);
        let d_coupled = coupled.derivatives(0.0, &state);
        let d_independent = independent.derivatives(0.0, &state);

        // Should be bit-identical
        assert_eq!(
            d_coupled.states[0].position(),
            d_independent.states[0].position()
        );
        assert_eq!(
            d_coupled.states[0].velocity(),
            d_independent.states[0].velocity()
        );
        assert_eq!(
            d_coupled.states[1].position(),
            d_independent.states[1].position()
        );
        assert_eq!(
            d_coupled.states[1].velocity(),
            d_independent.states[1].velocity()
        );
    }

    #[test]
    fn mutual_gravity_adds_acceleration() {
        let mu = 398600.4418;
        let coupled = CoupledGroupDynamics::new(
            vec![TwoBodySystem { mu }, TwoBodySystem { mu }],
            vec![InteractionPair {
                i: 0,
                j: 1,
                force: Arc::new(MutualGravity {
                    mu_i: 1e-10,
                    mu_j: 1e-10,
                }),
            }],
        );
        let independent = super::super::IndependentGroupDynamics::new(vec![
            TwoBodySystem { mu },
            TwoBodySystem { mu },
        ]);

        let state = GroupState::new(vec![iss_state(), sso_state()]);
        let d_coupled = coupled.derivatives(0.0, &state);
        let d_independent = independent.derivatives(0.0, &state);

        // Coupled should differ from independent (mutual gravity adds acceleration)
        let diff0 =
            (*d_coupled.states[0].velocity() - *d_independent.states[0].velocity()).magnitude();
        let diff1 =
            (*d_coupled.states[1].velocity() - *d_independent.states[1].velocity()).magnitude();
        assert!(diff0 > 0.0);
        assert!(diff1 > 0.0);
    }

    #[test]
    fn three_satellites_pair_accounting() {
        // 3 satellites with 3 pairs: (0,1), (0,2), (1,2)
        // Verify all pairs contribute correctly
        let mu = 398600.4418;
        let s0 = OrbitalState::new(Vector3::new(7000.0, 0.0, 0.0), Vector3::new(0.0, 7.5, 0.0));
        let s1 = OrbitalState::new(Vector3::new(0.0, 7200.0, 0.0), Vector3::new(-7.3, 0.0, 0.0));
        let s2 = OrbitalState::new(Vector3::new(0.0, 0.0, 7400.0), Vector3::new(0.0, 0.0, 7.1));

        let mg =
            |mu_i, mu_j| -> Arc<dyn InterSatelliteForce> { Arc::new(MutualGravity { mu_i, mu_j }) };

        let coupled = CoupledGroupDynamics::new(
            vec![
                TwoBodySystem { mu },
                TwoBodySystem { mu },
                TwoBodySystem { mu },
            ],
            vec![
                InteractionPair {
                    i: 0,
                    j: 1,
                    force: mg(1.0, 2.0),
                },
                InteractionPair {
                    i: 0,
                    j: 2,
                    force: mg(1.0, 3.0),
                },
                InteractionPair {
                    i: 1,
                    j: 2,
                    force: mg(2.0, 3.0),
                },
            ],
        );

        let state = GroupState::new(vec![s0.clone(), s1.clone(), s2.clone()]);
        let derivs = coupled.derivatives(0.0, &state);

        // Compare with independent (no interactions)
        let independent = super::super::IndependentGroupDynamics::new(vec![
            TwoBodySystem { mu },
            TwoBodySystem { mu },
            TwoBodySystem { mu },
        ]);
        let d_indep = independent.derivatives(0.0, &state);

        // All 3 satellites should have different accelerations from independent
        for k in 0..3 {
            let diff = (*derivs.states[k].velocity() - *d_indep.states[k].velocity()).magnitude();
            assert!(
                diff > 0.0,
                "satellite {k} should have inter-satellite acceleration"
            );
        }
    }

    #[test]
    fn three_satellites_momentum_conservation() {
        // For MutualGravity: Σ m_i * a_i = 0 (total momentum conserved)
        // mu_i = G * m_i, so check Σ mu_i * a_extra_i = 0
        let mu_0 = 1.0;
        let mu_1 = 2.0;
        let mu_2 = 3.0;

        let s0 = OrbitalState::new(Vector3::new(10.0, 0.0, 0.0), Vector3::zeros());
        let s1 = OrbitalState::new(Vector3::new(0.0, 10.0, 0.0), Vector3::zeros());
        let s2 = OrbitalState::new(Vector3::new(0.0, 0.0, 10.0), Vector3::zeros());

        // Use a dummy DynamicalSystem that returns zero derivatives
        /// Free particle: d(pos)/dt = vel, d(vel)/dt = 0.
        struct FreeParticle;
        impl DynamicalSystem for FreeParticle {
            type State = OrbitalState;
            fn derivatives(&self, _t: f64, state: &OrbitalState) -> OrbitalState {
                OrbitalState::from_derivative(*state.velocity(), Vector3::zeros())
            }
        }

        let coupled = CoupledGroupDynamics::new(
            vec![FreeParticle, FreeParticle, FreeParticle],
            vec![
                InteractionPair {
                    i: 0,
                    j: 1,
                    force: Arc::new(MutualGravity {
                        mu_i: mu_0,
                        mu_j: mu_1,
                    }),
                },
                InteractionPair {
                    i: 0,
                    j: 2,
                    force: Arc::new(MutualGravity {
                        mu_i: mu_0,
                        mu_j: mu_2,
                    }),
                },
                InteractionPair {
                    i: 1,
                    j: 2,
                    force: Arc::new(MutualGravity {
                        mu_i: mu_1,
                        mu_j: mu_2,
                    }),
                },
            ],
        );

        let state = GroupState::new(vec![s0, s1, s2]);
        let derivs = coupled.derivatives(0.0, &state);

        // Σ mu_i * a_i = 0 (since FreeParticle → only inter-satellite forces)
        let momentum = mu_0 * *derivs.states[0].velocity()
            + mu_1 * *derivs.states[1].velocity()
            + mu_2 * *derivs.states[2].velocity();
        assert!(
            momentum.magnitude() < 1e-15,
            "total momentum should be conserved, got {momentum:?}"
        );
    }

    #[test]
    fn spring_energy_conservation_rk4() {
        // Two equal-mass bodies connected by spring, no other forces
        // Total energy = KE + PE = (v1² + v2²)/2 + k*(|r12| - L)²/2
        /// Free particle: d(pos)/dt = vel, d(vel)/dt = 0.
        struct FreeParticle;
        impl DynamicalSystem for FreeParticle {
            type State = OrbitalState;
            fn derivatives(&self, _t: f64, state: &OrbitalState) -> OrbitalState {
                OrbitalState::from_derivative(*state.velocity(), Vector3::zeros())
            }
        }

        let k = 0.01; // stiffness
        let rest = 10.0;
        let coupled = CoupledGroupDynamics::new(
            vec![FreeParticle, FreeParticle],
            vec![InteractionPair {
                i: 0,
                j: 1,
                force: Arc::new(Spring {
                    stiffness: k,
                    rest_length: rest,
                }),
            }],
        );

        // Initial: stretched spring (15 km apart, rest = 10 km), both at rest
        let s0 = OrbitalState::new(Vector3::new(0.0, 0.0, 0.0), Vector3::zeros());
        let s1 = OrbitalState::new(Vector3::new(15.0, 0.0, 0.0), Vector3::zeros());

        let energy = |gs: &GroupState<OrbitalState>| -> f64 {
            let ke = gs.states[0].velocity().magnitude_squared() / 2.0
                + gs.states[1].velocity().magnitude_squared() / 2.0;
            let r = (*gs.states[1].position() - *gs.states[0].position()).magnitude();
            let pe = k * (r - rest).powi(2) / 2.0;
            ke + pe
        };

        let mut state = GroupState::new(vec![s0, s1]);
        let e0 = energy(&state);

        let dt = 0.01;
        let mut t = 0.0;
        for _ in 0..10000 {
            state = Rk4.step(&coupled, t, &state, dt);
            t += dt;
            let e = energy(&state);
            assert!(
                (e - e0).abs() / e0 < 1e-7,
                "energy drift at t={t}: {e} vs {e0}, relative = {}",
                (e - e0).abs() / e0
            );
        }
    }

    #[test]
    fn spring_relative_oscillation_period() {
        // Two equal-mass bodies on a spring: relative motion is SHM
        // ω_rel = √(2k) (each mass feels k*Δx, relative accel = 2k*Δx)
        // Period T = 2π/√(2k)
        /// Free particle: d(pos)/dt = vel, d(vel)/dt = 0.
        struct FreeParticle;
        impl DynamicalSystem for FreeParticle {
            type State = OrbitalState;
            fn derivatives(&self, _t: f64, state: &OrbitalState) -> OrbitalState {
                OrbitalState::from_derivative(*state.velocity(), Vector3::zeros())
            }
        }

        let k = 0.04; // ω_rel = √0.08 ≈ 0.2828, T ≈ 22.21 s
        let rest = 10.0;
        let amplitude = 3.0; // initial stretch
        let coupled = CoupledGroupDynamics::new(
            vec![FreeParticle, FreeParticle],
            vec![InteractionPair {
                i: 0,
                j: 1,
                force: Arc::new(Spring {
                    stiffness: k,
                    rest_length: rest,
                }),
            }],
        );

        let s0 = OrbitalState::new(Vector3::new(0.0, 0.0, 0.0), Vector3::zeros());
        let s1 = OrbitalState::new(Vector3::new(rest + amplitude, 0.0, 0.0), Vector3::zeros());

        let expected_period = 2.0 * std::f64::consts::PI / (2.0 * k).sqrt();

        // Propagate for one full period and check that relative displacement returns
        let mut state = GroupState::new(vec![s0, s1]);
        let dt = 0.01;
        let n_steps = (expected_period / dt).round() as usize;
        let mut t = 0.0;
        for _ in 0..n_steps {
            state = Rk4.step(&coupled, t, &state, dt);
            t += dt;
        }

        let final_sep = (*state.states[1].position() - *state.states[0].position()).magnitude();
        // After one full period, separation should return to rest + amplitude
        assert!(
            (final_sep - (rest + amplitude)).abs() < 0.01,
            "after period T={expected_period:.2}, separation = {final_sep:.4}, expected {:.4}",
            rest + amplitude
        );
    }

    #[test]
    fn dt_convergence_rk4_fourth_order() {
        // RK4 error should decrease by factor ~16 when dt is halved
        /// Free particle: d(pos)/dt = vel, d(vel)/dt = 0.
        struct FreeParticle;
        impl DynamicalSystem for FreeParticle {
            type State = OrbitalState;
            fn derivatives(&self, _t: f64, state: &OrbitalState) -> OrbitalState {
                OrbitalState::from_derivative(*state.velocity(), Vector3::zeros())
            }
        }

        let k = 1.0; // higher stiffness for faster dynamics and larger errors
        let rest = 10.0;
        let coupled = CoupledGroupDynamics::new(
            vec![FreeParticle, FreeParticle],
            vec![InteractionPair {
                i: 0,
                j: 1,
                force: Arc::new(Spring {
                    stiffness: k,
                    rest_length: rest,
                }),
            }],
        );

        let s0 = OrbitalState::new(Vector3::zeros(), Vector3::zeros());
        let s1 = OrbitalState::new(Vector3::new(15.0, 0.0, 0.0), Vector3::zeros());

        let t_end = 10.0; // ~2.25 relative oscillation periods

        let propagate = |dt: f64| -> GroupState<OrbitalState> {
            let mut state = GroupState::new(vec![s0.clone(), s1.clone()]);
            let n_steps = (t_end / dt).round() as usize;
            let mut t = 0.0;
            for _ in 0..n_steps {
                state = Rk4.step(&coupled, t, &state, dt);
                t += dt;
            }
            state
        };

        // Reference solution with very small dt
        let ref_state = propagate(0.0001);

        let state_coarse = propagate(0.02);
        let state_fine = propagate(0.01);

        let err_coarse =
            (*state_coarse.states[0].position() - *ref_state.states[0].position()).magnitude();
        let err_fine =
            (*state_fine.states[0].position() - *ref_state.states[0].position()).magnitude();

        assert!(err_coarse > 0.0, "coarse error should be nonzero");
        assert!(err_fine > 0.0, "fine error should be nonzero");

        // RK4: error ~ O(dt⁴), so err_coarse/err_fine ≈ (0.02/0.01)⁴ = 16
        let ratio = err_coarse / err_fine;
        assert!(
            ratio > 12.0 && ratio < 20.0,
            "expected ~16x convergence, got {ratio:.2} (coarse={err_coarse:.2e}, fine={err_fine:.2e})"
        );
    }

    // ── CoupledGroup (PropGroup) tests ─────────────────────────────────────

    const MU_EARTH: f64 = 398600.4418;
    const EARTH_RADIUS: f64 = 6378.137;

    fn default_tol() -> Tolerances {
        Tolerances {
            atol: 1e-10,
            rtol: 1e-8,
        }
    }

    #[test]
    fn coupled_group_dp45_basic_propagation() {
        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::dp45(10.0, default_tol())
            .add_satellite("iss", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("sso", sso_state(), TwoBodySystem { mu: MU_EARTH });

        let outcome = group.propagate_to(100.0).unwrap();
        assert!(outcome.terminations.is_empty());
        assert!((group.current_t() - 100.0).abs() < 1e-9);
        assert!(!group.is_terminated());
    }

    #[test]
    fn coupled_group_rk4_basic_propagation() {
        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::rk4(10.0)
            .add_satellite("iss", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("sso", sso_state(), TwoBodySystem { mu: MU_EARTH });

        let outcome = group.propagate_to(100.0).unwrap();
        assert!(outcome.terminations.is_empty());
        assert!((group.current_t() - 100.0).abs() < 1e-9);
        assert!(!group.is_terminated());
    }

    #[test]
    fn coupled_group_rk4_matches_independent() {
        // CoupledGroup with no interactions should match IndependentGroup (RK4)
        use super::super::IndependentGroup;

        let dt = 10.0;
        let mut coupled: CoupledGroup<TwoBodySystem> = CoupledGroup::rk4(dt)
            .add_satellite("iss", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("sso", sso_state(), TwoBodySystem { mu: MU_EARTH });
        coupled.propagate_to(100.0).unwrap();

        let mut independent: IndependentGroup<TwoBodySystem> = IndependentGroup::rk4(dt)
            .add_satellite("iss", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("sso", sso_state(), TwoBodySystem { mu: MU_EARTH });
        independent.propagate_to(100.0).unwrap();

        let coupled_states = &coupled.group_state().states;
        let indep_entries: Vec<_> = independent.satellites().collect();

        // RK4 with same dt: should be bit-identical
        let iss_pos_err =
            (*coupled_states[0].position() - *indep_entries[0].state.position()).magnitude();
        let sso_pos_err =
            (*coupled_states[1].position() - *indep_entries[1].state.position()).magnitude();
        assert!(iss_pos_err < 1e-12, "ISS position error: {iss_pos_err}");
        assert!(sso_pos_err < 1e-12, "SSO position error: {sso_pos_err}");
    }

    #[test]
    fn coupled_group_spring_dp45_energy() {
        // Spring-coupled two-body with DP45: energy should be well conserved
        /// Free particle: d(pos)/dt = vel, d(vel)/dt = 0.
        struct FreeParticle;
        impl DynamicalSystem for FreeParticle {
            type State = OrbitalState;
            fn derivatives(&self, _t: f64, state: &OrbitalState) -> OrbitalState {
                OrbitalState::from_derivative(*state.velocity(), Vector3::zeros())
            }
        }

        let k = 0.01;
        let rest = 10.0;
        let s0 = OrbitalState::new(Vector3::zeros(), Vector3::zeros());
        let s1 = OrbitalState::new(Vector3::new(15.0, 0.0, 0.0), Vector3::zeros());

        let mut group: CoupledGroup<FreeParticle> = CoupledGroup::dp45(
            1.0,
            Tolerances {
                atol: 1e-12,
                rtol: 1e-10,
            },
        )
        .add_satellite("a", s0, FreeParticle)
        .add_satellite("b", s1, FreeParticle)
        .with_interaction(
            0,
            1,
            Arc::new(Spring {
                stiffness: k,
                rest_length: rest,
            }),
        );

        let energy = |gs: &GroupState<OrbitalState>| -> f64 {
            let ke = gs.states[0].velocity().magnitude_squared() / 2.0
                + gs.states[1].velocity().magnitude_squared() / 2.0;
            let r = (*gs.states[1].position() - *gs.states[0].position()).magnitude();
            ke + k * (r - rest).powi(2) / 2.0
        };

        let e0 = energy(group.group_state());

        // Propagate for ~2 oscillation periods
        group.propagate_to(200.0).unwrap();

        let e_final = energy(group.group_state());
        let rel_err = (e_final - e0).abs() / e0;
        assert!(rel_err < 1e-8, "DP45 energy relative error = {rel_err:.2e}");
    }

    #[test]
    fn coupled_group_spring_rk4_oscillation() {
        /// Free particle: d(pos)/dt = vel, d(vel)/dt = 0.
        struct FreeParticle;
        impl DynamicalSystem for FreeParticle {
            type State = OrbitalState;
            fn derivatives(&self, _t: f64, state: &OrbitalState) -> OrbitalState {
                OrbitalState::from_derivative(*state.velocity(), Vector3::zeros())
            }
        }

        let k = 0.04;
        let rest = 10.0;
        let amplitude = 3.0;
        let s0 = OrbitalState::new(Vector3::zeros(), Vector3::zeros());
        let s1 = OrbitalState::new(Vector3::new(rest + amplitude, 0.0, 0.0), Vector3::zeros());

        let expected_period = 2.0 * std::f64::consts::PI / (2.0_f64 * k).sqrt();

        let mut group: CoupledGroup<FreeParticle> = CoupledGroup::rk4(0.01)
            .add_satellite("a", s0, FreeParticle)
            .add_satellite("b", s1, FreeParticle)
            .with_interaction(
                0,
                1,
                Arc::new(Spring {
                    stiffness: k,
                    rest_length: rest,
                }),
            );

        group.propagate_to(expected_period).unwrap();

        let final_sep = (group.group_state().states[1].position()
            - group.group_state().states[0].position())
        .magnitude();
        assert!(
            (final_sep - (rest + amplitude)).abs() < 0.01,
            "after period T={expected_period:.2}, separation = {final_sep:.4}"
        );
    }

    #[test]
    fn coupled_group_event_terminates_whole_group() {
        // One satellite hits Earth → entire coupled group terminates
        let decaying =
            OrbitalState::new(Vector3::new(6500.0, 0.0, 0.0), Vector3::new(-5.0, 3.0, 0.0));

        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::dp45(10.0, default_tol())
            .with_event_checker(move |_t: f64, state: &OrbitalState| {
                if state.position().magnitude() < EARTH_RADIUS {
                    ControlFlow::Break("collision".to_string())
                } else {
                    ControlFlow::Continue(())
                }
            })
            .add_satellite("safe", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("decay", decaying, TwoBodySystem { mu: MU_EARTH });

        let outcome = group.propagate_to(10000.0).unwrap();

        assert_eq!(outcome.terminations.len(), 1);
        assert_eq!(outcome.terminations[0].satellite_id, SatId::from("decay"));
        assert!(outcome.terminations[0].reason.contains("collision"));
        assert!(group.is_terminated());
        assert!(group.current_t() < 10000.0);
    }

    #[test]
    fn coupled_group_multiple_events_first_wins() {
        // Two decaying satellites: first one detected wins
        let decay1 =
            OrbitalState::new(Vector3::new(6500.0, 0.0, 0.0), Vector3::new(-5.0, 3.0, 0.0));
        let decay2 =
            OrbitalState::new(Vector3::new(6500.0, 0.0, 0.0), Vector3::new(-5.0, 3.0, 0.0));

        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::dp45(10.0, default_tol())
            .with_event_checker(move |_t: f64, state: &OrbitalState| {
                if state.position().magnitude() < EARTH_RADIUS {
                    ControlFlow::Break("collision".to_string())
                } else {
                    ControlFlow::Continue(())
                }
            })
            .add_satellite("first", decay1, TwoBodySystem { mu: MU_EARTH })
            .add_satellite("second", decay2, TwoBodySystem { mu: MU_EARTH });

        let outcome = group.propagate_to(10000.0).unwrap();

        // Exactly one termination (first detected, in iteration order)
        assert_eq!(outcome.terminations.len(), 1);
        assert_eq!(outcome.terminations[0].satellite_id, SatId::from("first"));
        assert!(group.is_terminated());
    }

    #[test]
    fn coupled_group_nan_terminates() {
        let degenerate = OrbitalState::new(Vector3::zeros(), Vector3::new(0.0, 1.0, 0.0));

        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::rk4(10.0)
            .add_satellite("good", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("bad", degenerate, TwoBodySystem { mu: MU_EARTH });

        let outcome = group.propagate_to(100.0).unwrap();

        assert_eq!(outcome.terminations.len(), 1);
        assert!(outcome.terminations[0].reason.contains("NonFinite"));
        assert!(group.is_terminated());
    }

    #[test]
    fn coupled_group_snapshot() {
        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::dp45(10.0, default_tol())
            .add_satellite("iss", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("sso", sso_state(), TwoBodySystem { mu: MU_EARTH });

        let snap = group.snapshot();
        assert_eq!(snap.positions.len(), 2);
        assert_eq!(snap.positions[0].0, SatId::from("iss"));
        assert!((snap.positions[0].1[0] - 6778.137).abs() < 1e-10);

        group.propagate_to(100.0).unwrap();
        let snap2 = group.snapshot();
        assert_eq!(snap2.positions.len(), 2);
        assert!((snap2.positions[0].1 - snap.positions[0].1).magnitude() > 1.0);
    }

    // ── into_parts + push API tests ──────────────────────────────────────

    #[test]
    fn into_parts_preserves_state_and_dynamics() {
        let group: CoupledGroup<TwoBodySystem> = CoupledGroup::rk4(10.0)
            .add_satellite("iss", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("sso", sso_state(), TwoBodySystem { mu: MU_EARTH })
            .with_interaction(
                0,
                1,
                Arc::new(MutualGravity {
                    mu_i: 1e-10,
                    mu_j: 1e-10,
                }),
            );

        let parts = group.into_parts();
        assert_eq!(parts.ids.len(), 2);
        assert_eq!(parts.states.len(), 2);
        assert_eq!(parts.dynamics.len(), 2);
        assert_eq!(parts.ids[0], SatId::from("iss"));
        assert_eq!(parts.ids[1], SatId::from("sso"));
        assert!((parts.states[0].position().x - 6778.137).abs() < 1e-10);
        assert!((parts.dynamics[0].mu - MU_EARTH).abs() < 1e-6);
        assert!((parts.t - 0.0).abs() < 1e-15);
        assert!(!parts.terminated);
        assert!(parts.termination.is_none());
    }

    #[test]
    fn into_parts_after_termination() {
        let decaying =
            OrbitalState::new(Vector3::new(6500.0, 0.0, 0.0), Vector3::new(-5.0, 3.0, 0.0));

        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::dp45(10.0, default_tol())
            .with_event_checker(move |_t: f64, state: &OrbitalState| {
                if state.position().magnitude() < EARTH_RADIUS {
                    ControlFlow::Break("collision".to_string())
                } else {
                    ControlFlow::Continue(())
                }
            })
            .add_satellite("safe", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("decay", decaying, TwoBodySystem { mu: MU_EARTH });

        group.propagate_to(10000.0).unwrap();
        assert!(group.is_terminated());

        let parts = group.into_parts();
        assert!(parts.terminated);
        assert!(parts.termination.is_some());
        assert!(parts.termination.unwrap().reason.contains("collision"));
        // Dynamics are still returned even after termination
        assert_eq!(parts.dynamics.len(), 2);
    }

    #[test]
    fn push_satellite_and_interaction() {
        let mut group: CoupledGroup<TwoBodySystem> = CoupledGroup::rk4(10.0);
        group.push_satellite("a", iss_state(), TwoBodySystem { mu: MU_EARTH });
        group.push_satellite("b", sso_state(), TwoBodySystem { mu: MU_EARTH });
        group.push_interaction(
            0,
            1,
            Arc::new(Spring {
                stiffness: 0.01,
                rest_length: 10.0,
            }),
        );
        group.set_t(42.0);

        assert_eq!(group.ids(), vec![SatId::from("a"), SatId::from("b")]);
        assert!((group.current_t() - 42.0).abs() < 1e-15);

        // Should be able to propagate after push construction
        group.propagate_to(52.0).unwrap();
        assert!((group.current_t() - 52.0).abs() < 1e-9);
    }

    #[test]
    fn coupled_group_ids() {
        let group: CoupledGroup<TwoBodySystem> = CoupledGroup::dp45(10.0, default_tol())
            .add_satellite("alpha", iss_state(), TwoBodySystem { mu: MU_EARTH })
            .add_satellite("beta", sso_state(), TwoBodySystem { mu: MU_EARTH });

        let ids = group.ids();
        assert_eq!(ids.len(), 2);
        assert_eq!(ids[0], SatId::from("alpha"));
        assert_eq!(ids[1], SatId::from("beta"));
    }
}