astrora_core 0.1.1

Astrora - Rust-backed astrodynamics library - core computational components
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
//! Perturbation models for orbit propagation
//!
//! This module provides various perturbation models for high-fidelity
//! orbit propagation beyond the two-body problem:
//! - J2 (Earth oblateness)
//! - Atmospheric drag (exponential atmosphere model)
//! - Third-body perturbations (Sun and Moon)
//! - Solar radiation pressure (future)
//!
//! # References
//! - Curtis, H. D. "Orbital Mechanics for Engineering Students" (Equation 12.30, 12.69-12.71)
//! - Vallado, D. A. "Fundamentals of Astrodynamics and Applications" (Section 8.7.1, 8.6.2, 8.6.3)
//! - Wertz, J. R. "Spacecraft Attitude Determination and Control" (Chapter 17)
//! - Montenbruck, O. "Satellite Orbits" (Section 3.3.2)

use crate::core::error::{PoliastroError, PoliastroResult};
use crate::core::linalg::Vector3;
use std::f64::consts::PI;

/// J2 oblateness perturbation acceleration
///
/// Computes the acceleration due to Earth's oblateness (J2 term) in Cartesian coordinates.
/// This is the dominant perturbation for Earth-orbiting satellites and accounts for the
/// equatorial bulge.
///
/// # Formula
/// ```text
/// a_J2 = (3/2) * (J2 * μ * R²/r⁴) * [
///     x/r * (5z²/r² - 1) î +
///     y/r * (5z²/r² - 1) ĵ +
///     z/r * (5z²/r² - 3) k̂
/// ]
/// ```
///
/// Where:
/// - J2 is the oblateness coefficient (~1.08263e-3 for Earth)
/// - μ is the standard gravitational parameter (m³/s²)
/// - R is the body's equatorial radius (m)
/// - r is the orbital radius magnitude (m)
/// - x, y, z are position components in inertial frame (m)
///
/// # Arguments
/// * `r` - Position vector [x, y, z] in meters (inertial frame)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `J2` - Oblateness coefficient (dimensionless)
/// * `R` - Body equatorial radius (meters)
///
/// # Returns
/// Acceleration vector [ax, ay, az] in m/s²
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::j2_perturbation;
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// // ISS orbit at 400 km altitude
/// let r = Vector3::new(6778e3, 0.0, 0.0);  // On equator
/// let acc = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);
/// ```
///
/// # Notes
/// - The acceleration is computed in the same inertial frame as the position vector
/// - For Earth, typical magnitude is ~1e-5 m/s² at LEO altitudes
/// - J2 causes secular changes in RAAN and argument of perigee
/// - Effect decreases as ~1/r⁴ with increasing altitude
pub fn j2_perturbation(r: &Vector3, mu: f64, j2: f64, R: f64) -> Vector3 {
    // Position components
    let x = r.x;
    let y = r.y;
    let z = r.z;

    // Orbital radius magnitude
    let r_mag = r.norm();

    // Precompute common terms for efficiency
    let r2 = r_mag * r_mag;
    let r4 = r2 * r2;
    let z2 = z * z;

    // Common coefficient: (3/2) * J2 * μ * R² / r⁴
    let k = 1.5 * j2 * mu * R * R / r4;

    // z²/r² term (appears multiple times)
    let z2_r2 = z2 / r2;

    // Acceleration components
    // ax = k * (x/r) * (5*z²/r² - 1)
    // ay = k * (y/r) * (5*z²/r² - 1)
    // az = k * (z/r) * (5*z²/r² - 3)
    let factor_xy = 5.0 * z2_r2 - 1.0;
    let factor_z = 5.0 * z2_r2 - 3.0;

    Vector3::new(
        k * (x / r_mag) * factor_xy,
        k * (y / r_mag) * factor_xy,
        k * (z / r_mag) * factor_z,
    )
}

// =============================================================================
// ATMOSPHERIC DRAG MODELS
// =============================================================================

/// Compute atmospheric density using exponential atmosphere model
///
/// The exponential model approximates atmospheric density as:
/// ρ(h) = ρ₀ × exp(-h/H)
///
/// Where:
/// - h = altitude above reference surface (m)
/// - ρ₀ = reference density at surface (kg/m³)
/// - H = atmospheric scale height (m)
///
/// # Arguments
/// * `altitude` - Altitude above reference surface (m)
/// * `rho0` - Reference density at surface (kg/m³)
/// * `H0` - Atmospheric scale height (m)
///
/// # Returns
/// Atmospheric density (kg/m³)
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::exponential_density;
/// use astrora::core::constants::{RHO0_EARTH, H0_EARTH, R_EARTH};
///
/// let altitude = 400e3; // 400 km altitude (ISS)
/// let rho = exponential_density(altitude, RHO0_EARTH, H0_EARTH);
/// ```
///
/// # Notes
/// - This is a simplified model suitable for preliminary analysis
/// - For high-fidelity work, consider Harris-Priester or NRLMSISE-00
/// - Valid primarily for altitudes 100-1000 km
/// - Does not account for solar activity, geomagnetic effects, or diurnal variations
pub fn exponential_density(altitude: f64, rho0: f64, H0: f64) -> f64 {
    rho0 * (-altitude / H0).exp()
}

/// Atmospheric drag acceleration (exponential atmosphere model)
///
/// Computes the acceleration due to atmospheric drag using the exponential
/// atmosphere density model and a constant ballistic coefficient.
///
/// # Formula
/// ```text
/// a_drag = -(1/2) × ρ(h) × v_rel² × (1/B) × v̂_rel
/// ```
///
/// Where:
/// - ρ(h) is atmospheric density at altitude h
/// - v_rel is velocity relative to the atmosphere
/// - B = m/(C_d × A) is the ballistic coefficient (kg/m²)
/// - v̂_rel is the unit vector in the velocity direction
///
/// # Arguments
/// * `r` - Position vector [x, y, z] in meters (inertial frame)
/// * `v` - Velocity vector [vx, vy, vz] in m/s (inertial frame)
/// * `R` - Body equatorial radius (m) - reference surface for altitude
/// * `rho0` - Reference atmospheric density at surface (kg/m³)
/// * `H0` - Atmospheric scale height (m)
/// * `B` - Ballistic coefficient B = m/(C_d × A) in kg/m²
///
/// # Returns
/// Acceleration vector [ax, ay, az] in m/s²
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::drag_acceleration;
/// use astrora::core::constants::{R_EARTH, RHO0_EARTH, H0_EARTH};
///
/// // ISS parameters: mass ~450,000 kg, area ~2500 m², C_d ≈ 2.2
/// // B = 450000 / (2.2 × 2500) ≈ 82 kg/m²
/// let B = 82.0;
///
/// let r = Vector3::new(6778e3, 0.0, 0.0);  // 400 km altitude
/// let v = Vector3::new(0.0, 7670.0, 0.0);  // ~7.67 km/s circular velocity
/// let a_drag = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B);
/// ```
///
/// # Notes
/// - This model assumes non-rotating atmosphere (v_rel = v_inertial)
/// - For Earth, atmospheric rotation should be considered for high precision
/// - Drag always opposes the velocity direction
/// - Typical ballistic coefficients:
///   - Small satellites/CubeSats: 10-50 kg/m²
///   - ISS: 50-100 kg/m²
///   - Large satellites: 100-500 kg/m²
/// - Higher B = less drag effect (more massive or smaller cross-section)
pub fn drag_acceleration(r: &Vector3, v: &Vector3, R: f64, rho0: f64, H0: f64, B: f64) -> Vector3 {
    // Calculate altitude above reference surface
    let r_mag = r.norm();
    let altitude = r_mag - R;

    // Atmospheric density at current altitude
    let rho = exponential_density(altitude, rho0, H0);

    // Velocity magnitude and unit vector
    let v_mag = v.norm();

    // Handle zero velocity case (shouldn't happen in orbit, but be safe)
    if v_mag < 1e-10 {
        return Vector3::zeros();
    }

    let v_unit = v / v_mag;

    // Drag acceleration: a = -(1/2) × ρ × v² × (1/B) × v̂
    // Negative sign because drag opposes motion
    let drag_mag = -0.5 * rho * v_mag * v_mag / B;

    drag_mag * v_unit
}

/// Perturbed acceleration function type
///
/// This type alias represents a function that computes perturbation accelerations
/// given the current time, position, and velocity.
///
/// # Arguments
/// * `t` - Current time (seconds since epoch)
/// * `r` - Position vector (m)
/// * `v` - Velocity vector (m/s)
///
/// # Returns
/// Acceleration vector (m/s²)
pub type PerturbationFn = fn(f64, &Vector3, &Vector3) -> Vector3;

/// J2 perturbation function wrapper for use with numerical integrators
///
/// Returns a function suitable for use with RK4 or DOPRI5 integrators.
/// The returned function computes total acceleration (two-body + J2).
///
/// # Arguments
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `j2` - Oblateness coefficient
/// * `R` - Body equatorial radius (m)
///
/// # Returns
/// Function that computes [vx, vy, vz, ax, ay, az] given state vector
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::j2_acceleration_func;
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// let accel_func = j2_acceleration_func(GM_EARTH, J2_EARTH, R_EARTH);
/// // Use with RK4 or DOPRI5 integrator
/// ```
pub fn j2_acceleration_func(
    mu: f64,
    j2: f64,
    R: f64,
) -> impl Fn(f64, &nalgebra::DVector<f64>) -> nalgebra::DVector<f64> {
    move |_t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        // State vector: [x, y, z, vx, vy, vz]
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration: -μ/r³ * r
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // J2 perturbation acceleration
        let a_j2 = j2_perturbation(&r, mu, j2, R);

        // Total acceleration
        let a_total = a_twobody + a_j2;

        // Return derivative: [vx, vy, vz, ax, ay, az]
        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    }
}

/// Propagate orbit with J2 perturbation using RK4 integrator
///
/// Propagates a state vector forward in time accounting for Earth's oblateness.
/// Uses fixed-step RK4 integration with multiple sub-steps for accuracy.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `j2` - Oblateness coefficient
/// * `R` - Body equatorial radius (m)
/// * `n_steps` - Number of RK4 sub-steps (default: 10)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::propagate_j2_rk4;
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// let r0 = Vector3::new(7000e3, 0.0, 0.0);
/// let v0 = Vector3::new(0.0, 7546.0, 0.0);
/// let (r1, v1) = propagate_j2_rk4(&r0, &v0, 3600.0, GM_EARTH, J2_EARTH, R_EARTH, None).unwrap();
/// ```
pub fn propagate_j2_rk4(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    j2: f64,
    R: f64,
    n_steps: Option<usize>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::rk4_step;

    let n_steps = n_steps.unwrap_or(10);
    let h = dt / n_steps as f64;

    // Create acceleration function
    let f = j2_acceleration_func(mu, j2, R);

    // Initial state vector: [x, y, z, vx, vy, vz]
    let mut state = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate using multiple RK4 steps
    let mut t = 0.0;
    for _ in 0..n_steps {
        state = rk4_step(&f, t, &state, h);
        t += h;
    }

    // Extract final position and velocity
    let r_final = Vector3::new(state[0], state[1], state[2]);
    let v_final = Vector3::new(state[3], state[4], state[5]);

    Ok((r_final, v_final))
}

/// Propagate orbit with J2 perturbation using adaptive DOPRI5 integrator
///
/// Higher accuracy propagation using Dormand-Prince 5(4) adaptive integration.
/// Automatically adjusts step size to maintain specified error tolerance.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `j2` - Oblateness coefficient
/// * `R` - Body equatorial radius (m)
/// * `tol` - Error tolerance (default: 1e-8)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::propagate_j2_dopri5;
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// let r0 = Vector3::new(7000e3, 0.0, 0.0);
/// let v0 = Vector3::new(0.0, 7546.0, 0.0);
/// let (r1, v1) = propagate_j2_dopri5(&r0, &v0, 3600.0, GM_EARTH, J2_EARTH, R_EARTH, None).unwrap();
/// ```
pub fn propagate_j2_dopri5(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    j2: f64,
    R: f64,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::dopri5_integrate;

    let tol = tol.unwrap_or(1e-8);

    // Create acceleration function
    let f = j2_acceleration_func(mu, j2, R);

    // Initial state vector
    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate from t0=0 to tf=dt
    let state_final = dopri5_integrate(f, 0.0, &state0, dt, dt.abs() / 10.0, tol, None)?;

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

/// Propagate orbit with J2 perturbation using adaptive DOP853 integrator
///
/// Ultra-high accuracy propagation using Dormand-Prince 8(5,3) adaptive integration.
/// This 8th-order method is recommended for problems requiring very tight error
/// tolerances (e.g., tol < 1e-10) or long-duration high-precision propagation.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `j2` - Oblateness coefficient
/// * `R` - Body equatorial radius (m)
/// * `tol` - Error tolerance (default: 1e-10)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::propagate_j2_dop853;
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// let r0 = Vector3::new(7000e3, 0.0, 0.0);
/// let v0 = Vector3::new(0.0, 7546.0, 0.0);
/// let (r1, v1) = propagate_j2_dop853(&r0, &v0, 3600.0, GM_EARTH, J2_EARTH, R_EARTH, None).unwrap();
/// ```
pub fn propagate_j2_dop853(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    j2: f64,
    R: f64,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::dop853_integrate;

    let tol = tol.unwrap_or(1e-10);

    // Create acceleration function
    let f = j2_acceleration_func(mu, j2, R);

    // Initial state vector
    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate from t0=0 to tf=dt
    let state_final = dop853_integrate(f, 0.0, &state0, dt, dt.abs() / 10.0, tol, None)?;

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

/// Drag acceleration function wrapper for use with numerical integrators
///
/// Returns a function suitable for use with RK4 or DOPRI5 integrators.
/// The returned function computes total acceleration (two-body + drag).
///
/// # Arguments
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `R` - Body equatorial radius (m)
/// * `rho0` - Reference atmospheric density (kg/m³)
/// * `H0` - Atmospheric scale height (m)
/// * `B` - Ballistic coefficient (kg/m²)
///
/// # Returns
/// Function that computes [vx, vy, vz, ax, ay, az] given state vector
pub fn drag_acceleration_func(
    mu: f64,
    R: f64,
    rho0: f64,
    H0: f64,
    B: f64,
) -> impl Fn(f64, &nalgebra::DVector<f64>) -> nalgebra::DVector<f64> {
    move |_t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        // State vector: [x, y, z, vx, vy, vz]
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration: -μ/r³ * r
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // Drag acceleration
        let a_drag = drag_acceleration(&r, &v, R, rho0, H0, B);

        // Total acceleration
        let a_total = a_twobody + a_drag;

        // Return derivative: [vx, vy, vz, ax, ay, az]
        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    }
}

/// Propagate orbit with atmospheric drag using RK4 integrator
///
/// Propagates a state vector forward in time accounting for atmospheric drag.
/// Uses fixed-step RK4 integration with multiple sub-steps for accuracy.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `R` - Body equatorial radius (m)
/// * `rho0` - Reference atmospheric density (kg/m³)
/// * `H0` - Atmospheric scale height (m)
/// * `B` - Ballistic coefficient (kg/m²)
/// * `n_steps` - Number of RK4 sub-steps (default: 10)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::propagate_drag_rk4;
/// use astrora::core::constants::{GM_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH};
///
/// let r0 = Vector3::new(6778e3, 0.0, 0.0);  // 400 km altitude
/// let v0 = Vector3::new(0.0, 7670.0, 0.0);
/// let B = 50.0;  // CubeSat ballistic coefficient
/// let (r1, v1) = propagate_drag_rk4(&r0, &v0, 3600.0, GM_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH, B, None).unwrap();
/// ```
pub fn propagate_drag_rk4(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    R: f64,
    rho0: f64,
    H0: f64,
    B: f64,
    n_steps: Option<usize>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::rk4_step;

    let n_steps = n_steps.unwrap_or(10);
    let h = dt / n_steps as f64;

    // Create acceleration function
    let f = drag_acceleration_func(mu, R, rho0, H0, B);

    // Initial state vector: [x, y, z, vx, vy, vz]
    let mut state = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate using multiple RK4 steps
    let mut t = 0.0;
    for _ in 0..n_steps {
        state = rk4_step(&f, t, &state, h);
        t += h;
    }

    // Extract final position and velocity
    let r_final = Vector3::new(state[0], state[1], state[2]);
    let v_final = Vector3::new(state[3], state[4], state[5]);

    Ok((r_final, v_final))
}

/// Propagate orbit with atmospheric drag using adaptive DOPRI5 integrator
///
/// Higher accuracy propagation using Dormand-Prince 5(4) adaptive integration.
/// Automatically adjusts step size to maintain specified error tolerance.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `R` - Body equatorial radius (m)
/// * `rho0` - Reference atmospheric density (kg/m³)
/// * `H0` - Atmospheric scale height (m)
/// * `B` - Ballistic coefficient (kg/m²)
/// * `tol` - Error tolerance (default: 1e-8)
///
/// # Returns
/// Tuple of (final position, final velocity)
pub fn propagate_drag_dopri5(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    R: f64,
    rho0: f64,
    H0: f64,
    B: f64,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::dopri5_integrate;

    let tol = tol.unwrap_or(1e-8);

    // Create acceleration function
    let f = drag_acceleration_func(mu, R, rho0, H0, B);

    // Initial state vector
    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate from t0=0 to tf=dt
    let state_final = dopri5_integrate(f, 0.0, &state0, dt, dt.abs() / 10.0, tol, None)?;

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

/// Combined J2 + drag acceleration function wrapper
///
/// Returns a function suitable for use with RK4 or DOPRI5 integrators.
/// Computes total acceleration from two-body + J2 + drag.
///
/// # Arguments
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `j2` - Oblateness coefficient
/// * `R` - Body equatorial radius (m)
/// * `rho0` - Reference atmospheric density (kg/m³)
/// * `H0` - Atmospheric scale height (m)
/// * `B` - Ballistic coefficient (kg/m²)
pub fn j2_drag_acceleration_func(
    mu: f64,
    j2: f64,
    R: f64,
    rho0: f64,
    H0: f64,
    B: f64,
) -> impl Fn(f64, &nalgebra::DVector<f64>) -> nalgebra::DVector<f64> {
    move |_t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // J2 perturbation
        let a_j2 = j2_perturbation(&r, mu, j2, R);

        // Drag perturbation
        let a_drag = drag_acceleration(&r, &v, R, rho0, H0, B);

        // Total acceleration
        let a_total = a_twobody + a_j2 + a_drag;

        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    }
}

/// Propagate orbit with J2 + drag perturbations using RK4 integrator
///
/// Combines Earth oblateness and atmospheric drag effects.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `j2` - Oblateness coefficient
/// * `R` - Body equatorial radius (m)
/// * `rho0` - Reference atmospheric density (kg/m³)
/// * `H0` - Atmospheric scale height (m)
/// * `B` - Ballistic coefficient (kg/m²)
/// * `n_steps` - Number of RK4 sub-steps (default: 10)
pub fn propagate_j2_drag_rk4(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    j2: f64,
    R: f64,
    rho0: f64,
    H0: f64,
    B: f64,
    n_steps: Option<usize>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::rk4_step;

    let n_steps = n_steps.unwrap_or(10);
    let h = dt / n_steps as f64;

    let f = j2_drag_acceleration_func(mu, j2, R, rho0, H0, B);

    let mut state = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    let mut t = 0.0;
    for _ in 0..n_steps {
        state = rk4_step(&f, t, &state, h);
        t += h;
    }

    let r_final = Vector3::new(state[0], state[1], state[2]);
    let v_final = Vector3::new(state[3], state[4], state[5]);

    Ok((r_final, v_final))
}

/// Propagate orbit with J2 + drag perturbations using adaptive DOPRI5 integrator
///
/// High-accuracy propagation combining Earth oblateness and atmospheric drag.
pub fn propagate_j2_drag_dopri5(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    j2: f64,
    R: f64,
    rho0: f64,
    H0: f64,
    B: f64,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::dopri5_integrate;

    let tol = tol.unwrap_or(1e-8);

    let f = j2_drag_acceleration_func(mu, j2, R, rho0, H0, B);

    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    let state_final = dopri5_integrate(f, 0.0, &state0, dt, dt.abs() / 10.0, tol, None)?;

    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

// =============================================================================
// THIRD-BODY PERTURBATIONS (SUN AND MOON)
// =============================================================================

/// Simplified ephemeris for Sun position relative to Earth
///
/// Returns the Sun's position vector using a simple circular orbit approximation.
/// This is a simplified model suitable for basic perturbation calculations.
/// For high-precision work, use JPL ephemerides.
///
/// # Formula
/// The Sun is approximated as being in a circular orbit at 1 AU with a period
/// of 365.25 days (one sidereal year). The ecliptic plane is assumed to coincide
/// with the equatorial plane (no obliquity), and the Sun starts at the vernal equinox.
///
/// Position: r_sun = AU * [cos(λ), sin(λ), 0]
/// where λ = n * t (mean longitude), n = 2π / T (mean motion)
///
/// # Arguments
/// * `t` - Time since J2000 epoch (seconds)
///
/// # Returns
/// Sun position vector in ECI frame (meters)
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::sun_position_simple;
///
/// let t = 0.0; // J2000 epoch
/// let r_sun = sun_position_simple(t);
/// ```
///
/// # Notes
/// - This is a simplified model: no obliquity, no eccentricity
/// - Error: ~3-5% in position (acceptable for basic perturbation analysis)
/// - For comparison, real Sun orbit has e ≈ 0.0167
/// - For high-precision work, use JPL Horizons or DE440/441 ephemerides
pub fn sun_position_simple(t: f64) -> Vector3 {
    use crate::core::constants::{AU, DAY_TO_SEC};

    // Sidereal year (365.25636 days)
    const YEAR_SEC: f64 = 365.25636 * DAY_TO_SEC;

    // Mean motion: n = 2π / T
    let n = 2.0 * PI / YEAR_SEC;

    // Mean longitude: λ = n * t
    let lambda = n * t;

    // Circular orbit position at 1 AU
    // Simplified: Sun in ecliptic plane (ignoring obliquity)
    Vector3::new(AU * lambda.cos(), AU * lambda.sin(), 0.0)
}

/// Simplified ephemeris for Moon position relative to Earth
///
/// Returns the Moon's position vector using a simple circular orbit approximation.
/// This is a simplified model suitable for basic perturbation calculations.
/// For high-precision work, use JPL ephemerides or lunar theory (ELP-2000/82).
///
/// # Formula
/// The Moon is approximated as being in a circular orbit at the mean lunar distance
/// with a sidereal month period of 27.321661 days. The orbit is assumed to be
/// in the equatorial plane (no inclination).
///
/// Position: r_moon = a_moon * [cos(λ), sin(λ), 0]
/// where λ = n * t (mean longitude), n = 2π / T (mean motion)
///
/// # Arguments
/// * `t` - Time since J2000 epoch (seconds)
///
/// # Returns
/// Moon position vector in ECI frame (meters)
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::moon_position_simple;
///
/// let t = 0.0; // J2000 epoch
/// let r_moon = moon_position_simple(t);
/// ```
///
/// # Notes
/// - This is a very simplified model: no inclination, no eccentricity
/// - Error: ~10-20% in position (sufficient for basic perturbation studies)
/// - Real Moon orbit: i ≈ 5.145°, e ≈ 0.0549
/// - For high-precision work, use JPL Horizons or ELP-2000/82 lunar theory
pub fn moon_position_simple(t: f64) -> Vector3 {
    use crate::core::constants::DAY_TO_SEC;

    // Mean lunar distance (semi-major axis)
    const A_MOON: f64 = 384_400_000.0; // 384,400 km in meters

    // Sidereal month (27.321661 days)
    const MONTH_SEC: f64 = 27.321661 * DAY_TO_SEC;

    // Mean motion: n = 2π / T
    let n = 2.0 * PI / MONTH_SEC;

    // Mean longitude: λ = n * t
    let lambda = n * t;

    // Circular orbit position at mean lunar distance
    // Simplified: Moon in equatorial plane (ignoring 5.145° inclination)
    Vector3::new(A_MOON * lambda.cos(), A_MOON * lambda.sin(), 0.0)
}

/// Third-body perturbation acceleration (point-mass approximation)
///
/// Computes the gravitational perturbation acceleration on a satellite due to
/// a third body (e.g., Sun or Moon) using the point-mass approximation.
///
/// # Formula
/// The third-body perturbation acceleration is:
/// ```text
/// a_3rd = μ₃ * [(r₃ - r) / |r₃ - r|³ - r₃ / |r₃|³]
/// ```
///
/// This can be decomposed into two terms:
/// - **Direct term**: μ₃ * (r₃ - r) / |r₃ - r|³
///   - Gravitational attraction of satellite toward third body
/// - **Indirect term**: -μ₃ * r₃ / |r₃|³
///   - Effect of third body's attraction on the primary body (Earth)
///
/// Where:
/// - μ₃ is the gravitational parameter of the third body (m³/s²)
/// - r is the position of the satellite relative to Earth (m)
/// - r₃ is the position of the third body relative to Earth (m)
///
/// # Arguments
/// * `r` - Satellite position vector relative to Earth (m)
/// * `r_third` - Third body position vector relative to Earth (m)
/// * `mu_third` - Gravitational parameter of third body (m³/s²)
///
/// # Returns
/// Perturbation acceleration vector (m/s²)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::{third_body_perturbation, sun_position_simple};
/// use astrora::core::constants::GM_SUN;
///
/// let r_sat = Vector3::new(7000e3, 0.0, 0.0);  // Satellite at 7000 km
/// let r_sun = sun_position_simple(0.0);         // Sun position at J2000
/// let a_sun = third_body_perturbation(&r_sat, &r_sun, GM_SUN);
/// ```
///
/// # Notes
/// - Magnitude for Sun at LEO: ~6×10⁻⁶ m/s²
/// - Magnitude for Moon at LEO: ~3×10⁻⁶ m/s²
/// - Combined Sun+Moon effect comparable to J2 (~1×10⁻⁵ m/s²)
/// - Most significant for high-altitude orbits (GEO, lunar missions)
/// - For GEO satellites: Moon effect > Sun effect > J2 effect
///
/// # References
/// - Curtis "Orbital Mechanics" Section 12.8 (Equation 12.69)
/// - Vallado "Fundamentals" Section 8.6.3
/// - Montenbruck "Satellite Orbits" Section 3.3.2
pub fn third_body_perturbation(r: &Vector3, r_third: &Vector3, mu_third: f64) -> Vector3 {
    // Relative position: third body to satellite
    let r_rel = r_third - r;
    let r_rel_mag = r_rel.norm();
    let r_third_mag = r_third.norm();

    // Avoid division by zero (shouldn't happen in practice)
    if r_rel_mag < 1e-10 || r_third_mag < 1e-10 {
        return Vector3::zeros();
    }

    // Direct term: attraction toward third body
    // a_direct = μ₃ * (r₃ - r) / |r₃ - r|³
    let direct = mu_third / (r_rel_mag * r_rel_mag * r_rel_mag) * r_rel;

    // Indirect term: effect on Earth's motion
    // a_indirect = -μ₃ * r₃ / |r₃|³
    let indirect = -mu_third / (r_third_mag * r_third_mag * r_third_mag) * r_third;

    // Total third-body acceleration
    direct + indirect
}

/// Combined Sun and Moon third-body perturbation acceleration
///
/// Convenience function that computes the total perturbation from both
/// the Sun and Moon using simplified ephemerides.
///
/// # Arguments
/// * `r` - Satellite position vector relative to Earth (m)
/// * `t` - Time since J2000 epoch (seconds)
///
/// # Returns
/// Combined perturbation acceleration from Sun and Moon (m/s²)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::sun_moon_perturbation;
///
/// let r = Vector3::new(42164e3, 0.0, 0.0);  // GEO altitude
/// let t = 0.0;  // J2000 epoch
/// let a_thirdbody = sun_moon_perturbation(&r, t);
/// ```
pub fn sun_moon_perturbation(r: &Vector3, t: f64) -> Vector3 {
    use crate::core::constants::{GM_MOON, GM_SUN};

    // Get third body positions at time t
    let r_sun = sun_position_simple(t);
    let r_moon = moon_position_simple(t);

    // Compute perturbations
    let a_sun = third_body_perturbation(r, &r_sun, GM_SUN);
    let a_moon = third_body_perturbation(r, &r_moon, GM_MOON);

    // Total third-body acceleration
    a_sun + a_moon
}

/// Third-body perturbation acceleration function wrapper for numerical integrators
///
/// Returns a function suitable for use with RK4, DOPRI5, or DOP853 integrators.
/// Computes total acceleration (two-body + third-body perturbations).
///
/// # Arguments
/// * `mu` - Standard gravitational parameter of primary body (m³/s²)
/// * `mu_third` - Gravitational parameter of third body (m³/s²)
/// * `ephemeris_func` - Function that returns third body position given time
///
/// # Returns
/// Function that computes [vx, vy, vz, ax, ay, az] given time and state vector
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::{third_body_acceleration_func, sun_position_simple};
/// use astrora::core::constants::{GM_EARTH, GM_SUN};
///
/// let accel_func = third_body_acceleration_func(GM_EARTH, GM_SUN, sun_position_simple);
/// // Use with RK4 or DOPRI5 integrator
/// ```
pub fn third_body_acceleration_func<F>(
    mu: f64,
    mu_third: f64,
    ephemeris_func: F,
) -> impl Fn(f64, &nalgebra::DVector<f64>) -> nalgebra::DVector<f64>
where
    F: Fn(f64) -> Vector3,
{
    move |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        // State vector: [x, y, z, vx, vy, vz]
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration: -μ/r³ * r
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // Third-body perturbation
        let r_third = ephemeris_func(t);
        let a_thirdbody = third_body_perturbation(&r, &r_third, mu_third);

        // Total acceleration
        let a_total = a_twobody + a_thirdbody;

        // Return derivative: [vx, vy, vz, ax, ay, az]
        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    }
}

/// Combined Sun + Moon third-body acceleration function wrapper
///
/// Returns a function for numerical integration with both Sun and Moon perturbations.
///
/// # Arguments
/// * `mu` - Standard gravitational parameter of primary body (m³/s²)
///
/// # Returns
/// Function that computes [vx, vy, vz, ax, ay, az] with Sun and Moon perturbations
pub fn sun_moon_acceleration_func(
    mu: f64,
) -> impl Fn(f64, &nalgebra::DVector<f64>) -> nalgebra::DVector<f64> {
    move |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // Sun + Moon perturbations
        let a_thirdbody = sun_moon_perturbation(&r, t);

        // Total acceleration
        let a_total = a_twobody + a_thirdbody;

        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    }
}

/// Propagate orbit with third-body perturbations using RK4 integrator
///
/// Propagates a state vector forward in time accounting for third-body
/// gravitational perturbations from the Sun and/or Moon.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter of primary body (m³/s²)
/// * `t0` - Initial time since J2000 epoch (seconds)
/// * `include_sun` - Include Sun perturbation
/// * `include_moon` - Include Moon perturbation
/// * `n_steps` - Number of RK4 sub-steps (default: 10)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::propagate_thirdbody_rk4;
/// use astrora::core::constants::GM_EARTH;
///
/// let r0 = Vector3::new(42164e3, 0.0, 0.0);  // GEO
/// let v0 = Vector3::new(0.0, 3075.0, 0.0);   // GEO velocity
/// let (r1, v1) = propagate_thirdbody_rk4(
///     &r0, &v0, 86400.0, GM_EARTH, 0.0, true, true, Some(100)
/// ).unwrap();
/// ```
pub fn propagate_thirdbody_rk4(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    t0: f64,
    include_sun: bool,
    include_moon: bool,
    n_steps: Option<usize>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::constants::{GM_MOON, GM_SUN};
    use crate::core::numerical::rk4_step;

    let n_steps = n_steps.unwrap_or(10);
    let h = dt / n_steps as f64;

    // Create acceleration function based on flags
    let f = move |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration
        let mut a_total = -mu / (r_mag * r_mag * r_mag) * r;

        // Add third-body perturbations
        if include_sun {
            let r_sun = sun_position_simple(t);
            a_total += third_body_perturbation(&r, &r_sun, GM_SUN);
        }
        if include_moon {
            let r_moon = moon_position_simple(t);
            a_total += third_body_perturbation(&r, &r_moon, GM_MOON);
        }

        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    };

    // Initial state vector
    let mut state = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate using multiple RK4 steps
    let mut t = t0;
    for _ in 0..n_steps {
        state = rk4_step(f, t, &state, h);
        t += h;
    }

    // Extract final position and velocity
    let r_final = Vector3::new(state[0], state[1], state[2]);
    let v_final = Vector3::new(state[3], state[4], state[5]);

    Ok((r_final, v_final))
}

/// Propagate orbit with third-body perturbations using adaptive DOPRI5 integrator
///
/// Higher accuracy propagation using Dormand-Prince 5(4) adaptive integration.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter of primary body (m³/s²)
/// * `t0` - Initial time since J2000 epoch (seconds)
/// * `include_sun` - Include Sun perturbation
/// * `include_moon` - Include Moon perturbation
/// * `tol` - Error tolerance (default: 1e-8)
///
/// # Returns
/// Tuple of (final position, final velocity)
pub fn propagate_thirdbody_dopri5(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    t0: f64,
    include_sun: bool,
    include_moon: bool,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::constants::{GM_MOON, GM_SUN};
    use crate::core::numerical::dopri5_integrate;

    let tol = tol.unwrap_or(1e-8);

    // Create acceleration function
    let f = move |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        let mut a_total = -mu / (r_mag * r_mag * r_mag) * r;

        if include_sun {
            let r_sun = sun_position_simple(t);
            a_total += third_body_perturbation(&r, &r_sun, GM_SUN);
        }
        if include_moon {
            let r_moon = moon_position_simple(t);
            a_total += third_body_perturbation(&r, &r_moon, GM_MOON);
        }

        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    };

    // Initial state vector
    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate from t0 to t0+dt
    let state_final = dopri5_integrate(f, t0, &state0, t0 + dt, dt.abs() / 10.0, tol, None)?;

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

// =============================================================================
// SOLAR RADIATION PRESSURE (SRP)
// =============================================================================

/// Compute shadow function for solar radiation pressure
///
/// Determines the degree of illumination of a spacecraft by the Sun,
/// accounting for Earth's shadow (umbra and penumbra regions).
///
/// # Returns
/// Shadow factor k:
/// - k = 1.0: Full sunlight (no shadow)
/// - k = 0.0: Full umbra (complete shadow)
/// - 0.0 < k < 1.0: Partial shadow (penumbra)
///
/// # Formula
/// Uses a conical shadow model with:
/// - θ_sun = apparent angular radius of Sun as seen from spacecraft
/// - θ_earth = apparent angular radius of Earth as seen from spacecraft
/// - α = angle between Sun and Earth as seen from spacecraft
///
/// Conditions:
/// - Umbra: α + θ_sun < θ_earth (Earth completely blocks Sun)
/// - Penumbra: |θ_sun - θ_earth| < α < θ_sun + θ_earth
/// - Full sunlight: α > θ_sun + θ_earth
///
/// # Arguments
/// * `r_sat` - Satellite position vector (m) in inertial frame
/// * `r_sun` - Sun position vector (m) in inertial frame
/// * `R_earth` - Earth's radius (m)
///
/// # Returns
/// Shadow factor k ∈ [0, 1]
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::{shadow_function, sun_position_simple};
/// use astrora::core::constants::R_EARTH;
///
/// let r_sat = Vector3::new(7000e3, 0.0, 0.0);
/// let r_sun = sun_position_simple(0.0);
/// let k = shadow_function(&r_sat, &r_sun, R_EARTH);
/// ```
///
/// # Notes
/// - This is a conical shadow model (more accurate than cylindrical)
/// - Earth is treated as a sphere (oblate effects neglected)
/// - Sun is treated as a point source for umbra calculation, disk for penumbra
/// - For high-precision work, consider ray-tracing or ellipsoidal Earth models
///
/// # References
/// - Montenbruck & Gill, "Satellite Orbits", Section 3.4
/// - Vallado, "Fundamentals of Astrodynamics", Section 8.7.2
pub fn shadow_function(r_sat: &Vector3, r_sun: &Vector3, R_earth: f64) -> f64 {
    use crate::core::constants::R_SUN;

    // Vectors from Earth to satellite and Sun
    let r_sat_mag = r_sat.norm();
    let r_sun_mag = r_sun.norm();

    // Unit vectors
    let u_sat = r_sat / r_sat_mag;
    let u_sun = r_sun / r_sun_mag;

    // Angle between satellite and Sun directions (cosine)
    let cos_alpha = u_sat.dot(&u_sun);

    // If satellite is on Sun side of Earth, definitely in sunlight
    if cos_alpha >= 0.0 {
        return 1.0;
    }

    // Apparent angular radii as seen from satellite
    // θ = arcsin(R / r) ≈ R/r for small angles
    let theta_earth = (R_earth / r_sat_mag).asin();
    let theta_sun = (R_SUN / (r_sun_mag - r_sat_mag).abs()).asin();

    // Angle between Sun and Earth as seen from spacecraft
    let alpha = cos_alpha.abs().acos();

    // Check shadow conditions
    if alpha + theta_sun <= theta_earth {
        // Total umbra: Earth completely blocks Sun
        0.0
    } else if alpha - theta_sun >= theta_earth {
        // Full sunlight: no shadow
        1.0
    } else {
        // Penumbra: partial shadow
        // Linear approximation for penumbra transition
        // More accurate models use actual area overlap calculations
        let penumbra_start = theta_earth - theta_sun;
        let penumbra_end = theta_earth + theta_sun;

        if alpha < penumbra_start {
            0.0 // Full umbra
        } else if alpha > penumbra_end {
            1.0 // Full sunlight
        } else {
            // Linear interpolation in penumbra
            (alpha - penumbra_start) / (penumbra_end - penumbra_start)
        }
    }
}

/// Solar radiation pressure acceleration (cannon-ball model)
///
/// Computes the acceleration due to solar radiation pressure using the
/// simple cannon-ball model (spacecraft treated as a sphere).
///
/// # Formula
/// ```text
/// a_srp = k · C_r · (A/m) · P_sun · (AU²/r²) · û_sun
/// ```
///
/// Where:
/// - k = shadow factor (0 = umbra, 1 = full sun, 0-1 = penumbra)
/// - C_r = reflectivity coefficient (dimensionless)
///   - C_r = 1.0: Perfect absorption (black body)
///   - C_r = 2.0: Perfect specular reflection
///   - C_r ≈ 1.2-1.5: Typical spacecraft surfaces
/// - A/m = area-to-mass ratio (m²/kg)
/// - P_sun = solar radiation pressure at 1 AU (N/m²)
/// - AU = astronomical unit (m)
/// - r = distance from Sun to spacecraft (m)
/// - û_sun = unit vector from spacecraft to Sun
///
/// The pressure at 1 AU is: P = E/c = 1361 W/m² / 299792458 m/s ≈ 4.54×10⁻⁶ N/m²
///
/// # Arguments
/// * `r_sat` - Satellite position vector (m) in inertial frame
/// * `r_sun` - Sun position vector (m) in inertial frame
/// * `area_mass_ratio` - Cross-sectional area divided by mass (A/m) in m²/kg
/// * `C_r` - Reflectivity coefficient (typically 1.0-2.0)
/// * `R_earth` - Earth's radius for shadow calculations (m)
///
/// # Returns
/// Acceleration vector [ax, ay, az] in m/s²
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::{srp_acceleration, sun_position_simple};
/// use astrora::core::constants::R_EARTH;
///
/// // CubeSat: 0.1 m × 0.1 m × 0.1 m, mass 1 kg
/// // A = 0.01 m² (one face), A/m = 0.01 m²/kg
/// let area_mass_ratio = 0.01;
/// let C_r = 1.3; // Typical value
///
/// let r_sat = Vector3::new(7000e3, 0.0, 0.0);
/// let r_sun = sun_position_simple(0.0);
/// let a_srp = srp_acceleration(&r_sat, &r_sun, area_mass_ratio, C_r, R_EARTH);
/// ```
///
/// # Notes
/// - Cannon-ball model assumes spacecraft is spherical with uniform reflectivity
/// - More accurate models account for:
///   - Multi-faceted spacecraft geometry
///   - Surface material properties (specular vs diffuse reflection)
///   - Thermal re-radiation
///   - Material degradation over time
/// - SRP magnitude at 1 AU for A/m=1 m²/kg, C_r=1.0: ~4.54×10⁻⁶ m/s²
/// - Effect decreases as 1/r² with distance from Sun
/// - Most significant for:
///   - High area-to-mass ratio spacecraft (solar sails, large antennas)
///   - GEO and higher altitude orbits (drag negligible)
///   - Long-duration missions (cumulative effect)
///
/// # References
/// - Curtis, "Orbital Mechanics for Engineering Students", Section 12.9
/// - Vallado, "Fundamentals of Astrodynamics", Section 8.7
/// - Montenbruck, "Satellite Orbits", Section 3.4
pub fn srp_acceleration(
    r_sat: &Vector3,
    r_sun: &Vector3,
    area_mass_ratio: f64,
    C_r: f64,
    R_earth: f64,
) -> Vector3 {
    use crate::core::constants::{AU, SOLAR_RADIATION_PRESSURE};

    // Shadow factor (0 = umbra, 1 = full sun)
    let k = shadow_function(r_sat, r_sun, R_earth);

    // If in full shadow, no SRP
    if k < 1e-10 {
        return Vector3::zeros();
    }

    // Vector from satellite to Sun
    let r_sun_sat = r_sun - r_sat;
    let r_sun_sat_mag = r_sun_sat.norm();

    // Handle edge case (shouldn't happen, but be safe)
    if r_sun_sat_mag < 1e3 {
        return Vector3::zeros();
    }

    // Unit vector from satellite to Sun
    let u_sun = r_sun_sat / r_sun_sat_mag;

    // Distance scaling factor: (AU/r)² accounts for inverse-square law
    let distance_factor = (AU / r_sun_sat_mag).powi(2);

    // SRP acceleration magnitude
    // a = k · C_r · (A/m) · P_sun · (AU/r)²
    let a_mag = k * C_r * area_mass_ratio * SOLAR_RADIATION_PRESSURE * distance_factor;

    // Acceleration vector points away from Sun
    a_mag * u_sun
}

/// SRP acceleration function wrapper for use with numerical integrators
///
/// Returns a function suitable for use with RK4 or DOPRI5 integrators.
/// The returned function computes total acceleration (two-body + SRP).
///
/// # Arguments
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `area_mass_ratio` - Cross-sectional area divided by mass (m²/kg)
/// * `C_r` - Reflectivity coefficient (1.0-2.0)
/// * `R_earth` - Earth's radius for shadow calculations (m)
/// * `t0` - Initial time since J2000 epoch (seconds)
///
/// # Returns
/// Function that computes [vx, vy, vz, ax, ay, az] given state vector
pub fn srp_acceleration_func(
    mu: f64,
    area_mass_ratio: f64,
    C_r: f64,
    R_earth: f64,
    t0: f64,
) -> impl Fn(f64, &nalgebra::DVector<f64>) -> nalgebra::DVector<f64> {
    move |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        // State vector: [x, y, z, vx, vy, vz]
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration: -μ/r³ * r
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // Sun position at current time
        let r_sun = sun_position_simple(t0 + t);

        // SRP acceleration
        let a_srp = srp_acceleration(&r, &r_sun, area_mass_ratio, C_r, R_earth);

        // Total acceleration
        let a_total = a_twobody + a_srp;

        // Return derivative: [vx, vy, vz, ax, ay, az]
        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    }
}

/// Propagate orbit with solar radiation pressure using RK4 integrator
///
/// Propagates a state vector forward in time accounting for solar radiation
/// pressure using the cannon-ball model. Uses fixed-step RK4 integration.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `area_mass_ratio` - Cross-sectional area divided by mass (m²/kg)
/// * `C_r` - Reflectivity coefficient (1.0-2.0)
/// * `R_earth` - Earth's radius for shadow calculations (m)
/// * `t0` - Initial time since J2000 epoch (seconds)
/// * `n_steps` - Number of RK4 sub-steps (default: 100)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::propagate_srp_rk4;
/// use astrora::core::constants::{GM_EARTH, R_EARTH};
///
/// // CubeSat in GEO
/// let r0 = Vector3::new(42164e3, 0.0, 0.0);
/// let v0 = Vector3::new(0.0, 3075.0, 0.0);
/// let area_mass_ratio = 0.01; // 0.01 m²/kg
/// let C_r = 1.3;
/// let t0 = 0.0; // J2000 epoch
///
/// let (r1, v1) = propagate_srp_rk4(
///     &r0, &v0, 3600.0, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(100)
/// ).unwrap();
/// ```
pub fn propagate_srp_rk4(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    area_mass_ratio: f64,
    C_r: f64,
    R_earth: f64,
    t0: f64,
    n_steps: Option<usize>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::rk4_step;

    let n_steps = n_steps.unwrap_or(100);
    let h = dt / (n_steps as f64);

    // Create acceleration function
    let f = srp_acceleration_func(mu, area_mass_ratio, C_r, R_earth, t0);

    // Initial state vector
    let mut state = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate using multiple RK4 steps
    let mut t = 0.0;
    for _ in 0..n_steps {
        state = rk4_step(&f, t, &state, h);
        t += h;
    }

    // Extract final position and velocity
    let r_final = Vector3::new(state[0], state[1], state[2]);
    let v_final = Vector3::new(state[3], state[4], state[5]);

    Ok((r_final, v_final))
}

/// Propagate orbit with solar radiation pressure using adaptive DOPRI5 integrator
///
/// Higher accuracy propagation using Dormand-Prince 5(4) adaptive integration.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `area_mass_ratio` - Cross-sectional area divided by mass (m²/kg)
/// * `C_r` - Reflectivity coefficient (1.0-2.0)
/// * `R_earth` - Earth's radius for shadow calculations (m)
/// * `t0` - Initial time since J2000 epoch (seconds)
/// * `tol` - Error tolerance (default: 1e-8)
///
/// # Returns
/// Tuple of (final position, final velocity)
pub fn propagate_srp_dopri5(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    area_mass_ratio: f64,
    C_r: f64,
    R_earth: f64,
    t0: f64,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::dopri5_integrate;

    let tol = tol.unwrap_or(1e-8);

    // Create acceleration function
    let f = srp_acceleration_func(mu, area_mass_ratio, C_r, R_earth, t0);

    // Initial state vector
    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate from 0 to dt (time is relative to t0)
    let state_final = dopri5_integrate(f, 0.0, &state0, dt, dt.abs() / 10.0, tol, None)?;

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
    use approx::assert_relative_eq;

    #[test]
    fn test_j2_perturbation_equatorial_orbit() {
        // Satellite on equator (z=0) should have no vertical component initially
        let r = Vector3::new(7000e3, 0.0, 0.0);
        let acc = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);

        // At equator (z=0): factor_xy = -1, factor_z = -3
        // ax should be negative (towards Earth's center, modified by J2)
        assert!(acc.x < 0.0);
        // ay = 0 (no y component)
        assert_relative_eq!(acc.y, 0.0, epsilon = 1e-20);
        // az = 0 (no z-component for equatorial position)
        assert_relative_eq!(acc.z, 0.0, epsilon = 1e-20);
    }

    #[test]
    fn test_j2_perturbation_polar_orbit() {
        // Satellite above pole (x=0, y=0, z>0)
        let r = Vector3::new(0.0, 0.0, 7000e3);
        let acc = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);

        // At pole: x=y=0, so ax=ay=0
        assert_relative_eq!(acc.x, 0.0, epsilon = 1e-20);
        assert_relative_eq!(acc.y, 0.0, epsilon = 1e-20);
        // az should be positive (J2 acts away from equator at poles)
        // factor_z = 5 - 3 = 2 > 0
        assert!(acc.z > 0.0);
    }

    #[test]
    fn test_j2_perturbation_magnitude() {
        // Check magnitude is reasonable for LEO
        let r = Vector3::new(7000e3, 0.0, 1000e3);
        let acc = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);

        let acc_mag = acc.norm();
        // J2 acceleration at LEO should be ~1e-5 to 1e-2 m/s²
        assert!(acc_mag > 1e-6 && acc_mag < 2e-2);
    }

    #[test]
    fn test_j2_acceleration_decreases_with_altitude() {
        // J2 effect should decrease as ~1/r⁴
        let r1 = Vector3::new(7000e3, 0.0, 0.0);
        let r2 = Vector3::new(14000e3, 0.0, 0.0); // 2x radius

        let acc1 = j2_perturbation(&r1, GM_EARTH, J2_EARTH, R_EARTH);
        let acc2 = j2_perturbation(&r2, GM_EARTH, J2_EARTH, R_EARTH);

        let ratio = acc1.norm() / acc2.norm();
        // Should be approximately 2⁴ = 16
        assert!(ratio > 14.0 && ratio < 18.0);
    }

    #[test]
    fn test_propagate_j2_rk4_basic() {
        // Simple propagation test - just verify it runs
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        let result = propagate_j2_rk4(&r0, &v0, 100.0, GM_EARTH, J2_EARTH, R_EARTH, Some(10));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Verify orbit hasn't degraded unrealistically
        assert!(r1.norm() > 6000e3); // Still above Earth
        assert!(v1.norm() > 1000.0); // Still has significant velocity
    }

    #[test]
    fn test_propagate_j2_dopri5_basic() {
        // Adaptive integration test
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        let result = propagate_j2_dopri5(&r0, &v0, 100.0, GM_EARTH, J2_EARTH, R_EARTH, Some(1e-8));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Verify orbit is reasonable
        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_j2_vs_two_body_difference() {
        // J2 should cause orbit to differ from pure two-body
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(7000e3, 0.0, 1000e3); // Inclined orbit
        let v0 = Vector3::new(0.0, 7546.0, 100.0);
        let dt = 3600.0; // 1 hour

        // Two-body propagation
        let (r_twobody, _v_twobody) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // J2-perturbed propagation
        let (r_j2, _v_j2) = propagate_j2_rk4(&r0, &v0, dt, GM_EARTH, J2_EARTH, R_EARTH, Some(100)).unwrap();

        // Positions should differ (J2 causes secular drift)
        let pos_diff = (r_twobody - r_j2).norm();
        println!("Position difference after 1 hour: {} m", pos_diff);
        assert!(pos_diff > 10.0); // At least 10 meters difference after 1 hour

        // But shouldn't be too different (same order of magnitude)
        // After 1 hour with J2, difference can be several km
        assert!(pos_diff < 100000.0); // Less than 100 km difference
    }

    #[test]
    fn test_j2_energy_not_exactly_conserved() {
        // J2 perturbations should cause slight energy changes over time
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        let (r1, v1) = propagate_j2_rk4(&r0, &v0, 3600.0, GM_EARTH, J2_EARTH, R_EARTH, Some(100)).unwrap();

        // Calculate specific energies
        let e0 = v0.norm_squared() / 2.0 - GM_EARTH / r0.norm();
        let e1 = v1.norm_squared() / 2.0 - GM_EARTH / r1.norm();

        // Energy should change slightly (J2 is a conservative perturbation
        // but causes redistribution between kinetic and potential)
        // Note: Total mechanical energy is still conserved for conservative J2,
        // but the simple two-body energy formula doesn't capture the full picture
        let energy_diff = (e1 - e0).abs();

        // The difference should be small but measurable
        assert!(energy_diff < 1e6); // Less than 1 MJ/kg change
    }

    #[test]
    fn test_propagate_j2_dop853_basic() {
        // Test high-order DOP853 propagator for J2
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        let result = propagate_j2_dop853(&r0, &v0, 100.0, GM_EARTH, J2_EARTH, R_EARTH, Some(1e-10));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Verify orbit is reasonable
        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_propagate_j2_dop853_vs_dopri5() {
        // DOP853 should be more accurate than DOPRI5 for same tolerance
        let r0 = Vector3::new(7000e3, 0.0, 1000e3);
        let v0 = Vector3::new(0.0, 7546.0, 100.0);
        let dt = 3600.0;

        // Both with same tolerance
        let (r_dop853, v_dop853) = propagate_j2_dop853(&r0, &v0, dt, GM_EARTH, J2_EARTH, R_EARTH, Some(1e-10)).unwrap();
        let (r_dopri5, v_dopri5) = propagate_j2_dopri5(&r0, &v0, dt, GM_EARTH, J2_EARTH, R_EARTH, Some(1e-10)).unwrap();

        // Results should be very close (both high accuracy)
        let pos_diff = (r_dop853 - r_dopri5).norm();
        let vel_diff = (v_dop853 - v_dopri5).norm();

        // Should agree to within meters/mm/s (both are accurate)
        assert!(pos_diff < 10.0, "Position difference: {} m", pos_diff);
        assert!(vel_diff < 0.01, "Velocity difference: {} m/s", vel_diff);
    }

    #[test]
    fn test_propagate_j2_dop853_long_duration() {
        // Test longer propagation (1 orbit period)
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        // Orbital period ~98 minutes
        let period = 2.0 * std::f64::consts::PI * (r0.norm().powi(3) / GM_EARTH).sqrt();

        let result = propagate_j2_dop853(&r0, &v0, period, GM_EARTH, J2_EARTH, R_EARTH, None);
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // After one period, should be roughly back to same position
        // (J2 causes secular drift, so won't be exact)
        let pos_diff = (r1 - r0).norm();
        assert!(pos_diff < 150e3, "Position drift after 1 orbit: {} km", pos_diff / 1e3);

        // Velocity magnitude should be preserved
        let v_ratio = v1.norm() / v0.norm();
        assert!((v_ratio - 1.0).abs() < 0.01, "Velocity change: {}", v_ratio);
    }

    #[test]
    fn test_exponential_density_at_sea_level() {
        use crate::core::constants::{H0_EARTH, RHO0_EARTH};

        // At zero altitude, density should equal reference density
        let rho = exponential_density(0.0, RHO0_EARTH, H0_EARTH);
        assert_relative_eq!(rho, RHO0_EARTH, epsilon = 1e-10);
    }

    #[test]
    fn test_exponential_density_decreases_with_altitude() {
        use crate::core::constants::{H0_EARTH, RHO0_EARTH};

        // Density should decrease exponentially with altitude
        let rho_100km = exponential_density(100e3, RHO0_EARTH, H0_EARTH);
        let rho_200km = exponential_density(200e3, RHO0_EARTH, H0_EARTH);
        let rho_400km = exponential_density(400e3, RHO0_EARTH, H0_EARTH);

        // Each should be less than the previous
        assert!(rho_100km < RHO0_EARTH);
        assert!(rho_200km < rho_100km);
        assert!(rho_400km < rho_200km);

        // At 400 km with this simple model, density is extremely small
        // Note: Real atmospheric density at 400 km is ~1e-11 to 1e-12 kg/m³
        // This simple exponential model with H0=8500m underestimates at high altitude
        assert!(rho_400km < 1e-10);
        assert!(rho_400km > 0.0); // But not zero
    }

    #[test]
    fn test_exponential_density_scale_height() {
        use crate::core::constants::{H0_EARTH, RHO0_EARTH};

        // At one scale height, density should be 1/e of reference
        let rho_H = exponential_density(H0_EARTH, RHO0_EARTH, H0_EARTH);
        let expected = RHO0_EARTH / std::f64::consts::E;

        assert_relative_eq!(rho_H, expected, epsilon = 1e-10);
    }

    #[test]
    fn test_drag_acceleration_opposes_velocity() {
        use crate::core::constants::{H0_EARTH, R_EARTH, RHO0_EARTH};

        // ISS-like orbit at 400 km altitude
        let r = Vector3::new(6778e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7670.0, 0.0);
        let B = 50.0; // CubeSat-like ballistic coefficient

        let a_drag = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B);

        // Drag should oppose velocity: a_drag · v < 0
        let dot_product = a_drag.dot(&v);
        assert!(dot_product < 0.0, "Drag should oppose velocity");

        // Drag should be parallel to velocity (but opposite direction)
        let a_drag_normalized = a_drag.normalize();
        let v_normalized = v.normalize();
        let cos_angle = a_drag_normalized.dot(&v_normalized);

        // Should be antiparallel: cos(angle) ≈ -1
        assert_relative_eq!(cos_angle, -1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_drag_acceleration_magnitude() {
        use crate::core::constants::{H0_EARTH, R_EARTH, RHO0_EARTH};

        // ISS at 400 km altitude
        let r = Vector3::new(6778e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7670.0, 0.0);
        let B = 82.0; // ISS ballistic coefficient

        let a_drag = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B);

        // At 400 km with this simple exponential model, drag is extremely small
        // Note: This simple model underestimates drag at high altitudes
        // Real drag at 400 km would be ~1e-7 to 1e-6 m/s² with accurate density models
        let mag = a_drag.norm();
        assert!(mag > 0.0 && mag < 1e-5, "Drag magnitude at 400km: {} m/s²", mag);
    }

    #[test]
    fn test_drag_acceleration_increases_at_lower_altitude() {
        use crate::core::constants::{H0_EARTH, R_EARTH, RHO0_EARTH};

        let B = 50.0;

        // Compare drag at 300 km vs 400 km
        let r_300km = Vector3::new(6678e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7730.0, 0.0); // Slightly faster at lower altitude
        let a_drag_300 = drag_acceleration(&r_300km, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B);

        let r_400km = Vector3::new(6778e3, 0.0, 0.0);
        let v2 = Vector3::new(0.0, 7670.0, 0.0);
        let a_drag_400 = drag_acceleration(&r_400km, &v2, R_EARTH, RHO0_EARTH, H0_EARTH, B);

        // Drag at lower altitude should be stronger (more negative)
        assert!(a_drag_300.norm() > a_drag_400.norm());
    }

    #[test]
    fn test_drag_acceleration_zero_velocity() {
        use crate::core::constants::{H0_EARTH, R_EARTH, RHO0_EARTH};

        let r = Vector3::new(6778e3, 0.0, 0.0);
        let v = Vector3::zeros(); // No velocity
        let B = 50.0;

        let a_drag = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B);

        // With zero velocity, drag should be zero
        assert_relative_eq!(a_drag.norm(), 0.0, epsilon = 1e-20);
    }

    #[test]
    fn test_drag_ballistic_coefficient_effect() {
        use crate::core::constants::{H0_EARTH, R_EARTH, RHO0_EARTH};

        let r = Vector3::new(6778e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7670.0, 0.0);

        // Compare two different ballistic coefficients
        let B_small = 20.0; // Small satellite (more drag)
        let B_large = 200.0; // Large satellite (less drag)

        let a_drag_small = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B_small);
        let a_drag_large = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, B_large);

        // Smaller B should experience more drag
        assert!(a_drag_small.norm() > a_drag_large.norm());

        // Ratio should be approximately B_large / B_small
        let ratio = a_drag_small.norm() / a_drag_large.norm();
        let expected_ratio = B_large / B_small;
        assert_relative_eq!(ratio, expected_ratio, epsilon = 1e-10);
    }

    #[test]
    fn test_propagate_drag_rk4_basic() {
        use crate::core::constants::{GM_EARTH, H0_EARTH, R_EARTH, RHO0_EARTH};

        // ISS-like orbit
        let r0 = Vector3::new(6778e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7670.0, 0.0);
        let B = 50.0;

        let result = propagate_drag_rk4(&r0, &v0, 600.0, GM_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH, B, Some(100));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Orbit should still be valid
        assert!(r1.norm() > 6000e3); // Still above Earth
        assert!(v1.norm() > 1000.0); // Still has significant velocity
    }

    #[test]
    fn test_propagate_drag_dopri5_basic() {
        use crate::core::constants::{GM_EARTH, H0_EARTH, R_EARTH, RHO0_EARTH};

        let r0 = Vector3::new(6778e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7670.0, 0.0);
        let B = 50.0;

        let result = propagate_drag_dopri5(&r0, &v0, 600.0, GM_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH, B, Some(1e-8));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_drag_causes_orbit_decay() {
        use crate::core::constants::{GM_EARTH, H0_EARTH, R_EARTH, RHO0_EARTH};
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(6778e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7670.0, 0.0);
        let B = 50.0;
        let dt = 3600.0; // 1 hour

        // Two-body propagation (no drag)
        let (r_twobody, v_twobody) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // Drag propagation
        let (r_drag, v_drag) = propagate_drag_rk4(&r0, &v0, dt, GM_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH, B, Some(100)).unwrap();

        // With drag, orbit should decay: energy should decrease
        let e_twobody = v_twobody.norm_squared() / 2.0 - GM_EARTH / r_twobody.norm();
        let e_drag = v_drag.norm_squared() / 2.0 - GM_EARTH / r_drag.norm();

        assert!(e_drag < e_twobody, "Drag should decrease orbital energy");

        // Orbital altitude should decrease
        assert!(r_drag.norm() < r_twobody.norm(), "Drag should cause orbit to decay");
    }

    #[test]
    fn test_propagate_j2_drag_combined() {
        use crate::core::constants::{GM_EARTH, H0_EARTH, J2_EARTH, R_EARTH, RHO0_EARTH};

        let r0 = Vector3::new(6778e3, 0.0, 1000e3); // Slightly inclined
        let v0 = Vector3::new(100.0, 7670.0, 0.0);
        let B = 50.0;

        let result = propagate_j2_drag_rk4(&r0, &v0, 600.0, GM_EARTH, J2_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH, B, Some(100));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_propagate_j2_drag_dopri5() {
        use crate::core::constants::{GM_EARTH, H0_EARTH, J2_EARTH, R_EARTH, RHO0_EARTH};

        let r0 = Vector3::new(6778e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7670.0, 0.0);
        let B = 50.0;

        let result = propagate_j2_drag_dopri5(&r0, &v0, 600.0, GM_EARTH, J2_EARTH, R_EARTH, RHO0_EARTH, H0_EARTH, B, Some(1e-8));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }
}

/// Cowell's method for numerical orbit propagation with perturbations
///
/// General numerical propagator that solves the equations of motion:
/// d²r/dt² = -μ/r³ * r + a_pert
///
/// where a_pert is the total perturbation acceleration from all sources.
///
/// # Arguments
/// * `r0` - Initial position vector (m)
/// * `v0` - Initial velocity vector (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Standard gravitational parameter (m³/s²)
/// * `perturbations` - Vector of perturbation functions
/// * `method` - Integration method ("rk4" or "dopri5")
/// * `n_steps` - Number of sub-steps for RK4 (ignored for DOPRI5)
/// * `tol` - Error tolerance for DOPRI5 (ignored for RK4)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::core::linalg::Vector3;
/// use astrora::propagators::perturbations::{propagate_cowell, j2_perturbation};
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// let r0 = Vector3::new(7000e3, 0.0, 0.0);
/// let v0 = Vector3::new(0.0, 7546.0, 0.0);
///
/// // Create J2 perturbation function
/// let j2_pert = |_t: f64, r: &Vector3, _v: &Vector3| {
///     j2_perturbation(r, GM_EARTH, J2_EARTH, R_EARTH)
/// };
///
/// let perts: Vec<Box<dyn Fn(f64, &Vector3, &Vector3) -> Vector3>> = vec![Box::new(j2_pert)];
/// let (r1, v1) = propagate_cowell(&r0, &v0, 3600.0, GM_EARTH, &perts, "rk4", Some(100), None).unwrap();
/// ```
#[allow(dead_code)]
pub fn propagate_cowell<F>(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    perturbations: &[F],
    method: &str,
    n_steps: Option<usize>,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)>
where
    F: Fn(f64, &Vector3, &Vector3) -> Vector3,
{
    // Create total acceleration function (two-body + perturbations)
    let accel_func = |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration: -μ/r³ * r
        let mut a_total = -mu / (r_mag * r_mag * r_mag) * r;

        // Add all perturbations
        for pert in perturbations {
            a_total += pert(t, &r, &v);
        }

        // Return derivative: [vx, vy, vz, ax, ay, az]
        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    };

    // Initial state vector
    let state0 = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Choose integration method
    let state_final = match method {
        "rk4" => {
            use crate::core::numerical::rk4_step;

            let n_steps = n_steps.unwrap_or(10);
            let h = dt / n_steps as f64;

            let mut state = state0;
            let mut t = 0.0;
            for _ in 0..n_steps {
                state = rk4_step(accel_func, t, &state, h);
                t += h;
            }
            state
        }
        "dopri5" => {
            use crate::core::numerical::dopri5_integrate;

            let tol = tol.unwrap_or(1e-8);
            dopri5_integrate(accel_func, 0.0, &state0, dt, dt.abs() / 10.0, tol, None)?
        }
        _ => {
            return Err(PoliastroError::ComputationError {
                message: format!("Invalid integration method '{method}'. Expected either 'rk4' or 'dopri5'"),
            });
        }
    };

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

#[cfg(test)]
mod cowell_tests {
    use super::*;
    use crate::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
    use approx::assert_relative_eq;

    #[test]
    fn test_cowell_two_body_only() {
        // With no perturbations, should match two-body propagation
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0; // 10 minutes

        // Cowell with no perturbations
        let perts: Vec<Box<dyn Fn(f64, &Vector3, &Vector3) -> Vector3>> = vec![];
        let (r_cowell, v_cowell) = propagate_cowell(&r0, &v0, dt, GM_EARTH, &perts, "rk4", Some(100), None).unwrap();

        // Keplerian propagation
        let (r_kep, v_kep) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // Should be very close (RK4 with 100 steps is quite accurate)
        let pos_diff = (r_cowell - r_kep).norm();
        let vel_diff = (v_cowell - v_kep).norm();

        assert!(pos_diff < 100.0); // < 100 m difference
        assert!(vel_diff < 0.1); // < 0.1 m/s difference
    }

    #[test]
    fn test_cowell_with_j2() {
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 3600.0;

        // Create J2 perturbation function
        let j2_pert = |_t: f64, r: &Vector3, _v: &Vector3| {
            j2_perturbation(r, GM_EARTH, J2_EARTH, R_EARTH)
        };

        let perts: Vec<Box<dyn Fn(f64, &Vector3, &Vector3) -> Vector3>> = vec![Box::new(j2_pert)];
        let (r_cowell, v_cowell) = propagate_cowell(&r0, &v0, dt, GM_EARTH, &perts, "rk4", Some(100), None).unwrap();

        // Compare with dedicated J2 propagator
        let (r_j2, v_j2) = propagate_j2_rk4(&r0, &v0, dt, GM_EARTH, J2_EARTH, R_EARTH, Some(100)).unwrap();

        // Should be identical (same algorithm)
        assert_relative_eq!(r_cowell.x, r_j2.x, epsilon = 1.0);
        assert_relative_eq!(r_cowell.y, r_j2.y, epsilon = 1.0);
        assert_relative_eq!(r_cowell.z, r_j2.z, epsilon = 1.0);
        assert_relative_eq!(v_cowell.x, v_j2.x, epsilon = 0.001);
        assert_relative_eq!(v_cowell.y, v_j2.y, epsilon = 0.001);
        assert_relative_eq!(v_cowell.z, v_j2.z, epsilon = 0.001);
    }

    #[test]
    fn test_cowell_dopri5_method() {
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0;

        let perts: Vec<Box<dyn Fn(f64, &Vector3, &Vector3) -> Vector3>> = vec![];
        let result = propagate_cowell(&r0, &v0, dt, GM_EARTH, &perts, "dopri5", None, Some(1e-8));

        assert!(result.is_ok());
        let (r, v) = result.unwrap();

        // Should still be in orbit
        assert!(r.norm() > 6000e3);
        assert!(v.norm() > 1000.0);
    }

    #[test]
    fn test_cowell_invalid_method() {
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        let perts: Vec<Box<dyn Fn(f64, &Vector3, &Vector3) -> Vector3>> = vec![];
        let result = propagate_cowell(&r0, &v0, 600.0, GM_EARTH, &perts, "invalid", None, None);

        assert!(result.is_err());
    }
}

#[cfg(test)]
mod thirdbody_tests {
    use super::*;
    use crate::core::constants::{AU, GM_EARTH, GM_MOON, GM_SUN};
    use approx::assert_relative_eq;

    #[test]
    fn test_sun_position_simple_at_j2000() {
        // At J2000 (t=0), Sun should be at vernal equinox: [1 AU, 0, 0]
        let r_sun = sun_position_simple(0.0);

        assert_relative_eq!(r_sun.x, AU, epsilon = 1.0);
        assert_relative_eq!(r_sun.y, 0.0, epsilon = 1.0);
        assert_relative_eq!(r_sun.z, 0.0, epsilon = 1.0);

        // Magnitude should be 1 AU
        let r_mag = r_sun.norm();
        assert_relative_eq!(r_mag, AU, epsilon = 1.0);
    }

    #[test]
    fn test_sun_position_simple_circular_orbit() {
        use crate::core::constants::DAY_TO_SEC;

        // After 1 year, Sun should complete one orbit
        let t_year = 365.25636 * DAY_TO_SEC;
        let r_sun_0 = sun_position_simple(0.0);
        let r_sun_1yr = sun_position_simple(t_year);

        // Should be approximately back at starting position (within a few km)
        assert_relative_eq!(r_sun_0.x, r_sun_1yr.x, epsilon = 1e6);
        assert_relative_eq!(r_sun_0.y, r_sun_1yr.y, epsilon = 1e6);

        // After quarter year, Sun should be at [0, 1 AU, 0]
        let t_quarter = t_year / 4.0;
        let r_sun_q = sun_position_simple(t_quarter);
        assert_relative_eq!(r_sun_q.x, 0.0, epsilon = 1e6);
        assert_relative_eq!(r_sun_q.y, AU, epsilon = 1e6);
    }

    #[test]
    fn test_moon_position_simple_at_j2000() {
        // At J2000 (t=0), Moon should be at [a_moon, 0, 0]
        let r_moon = moon_position_simple(0.0);

        const A_MOON: f64 = 384_400_000.0;
        assert_relative_eq!(r_moon.x, A_MOON, epsilon = 1.0);
        assert_relative_eq!(r_moon.y, 0.0, epsilon = 1.0);
        assert_relative_eq!(r_moon.z, 0.0, epsilon = 1.0);

        // Magnitude should be ~384,400 km
        let r_mag = r_moon.norm();
        assert_relative_eq!(r_mag, A_MOON, epsilon = 1.0);
    }

    #[test]
    fn test_moon_position_simple_circular_orbit() {
        use crate::core::constants::DAY_TO_SEC;

        // After one sidereal month, Moon should complete one orbit
        let t_month = 27.321661 * DAY_TO_SEC;
        let r_moon_0 = moon_position_simple(0.0);
        let r_moon_1m = moon_position_simple(t_month);

        // Should be approximately back at starting position
        assert_relative_eq!(r_moon_0.x, r_moon_1m.x, epsilon = 1e4);
        assert_relative_eq!(r_moon_0.y, r_moon_1m.y, epsilon = 1e4);
    }

    #[test]
    fn test_third_body_perturbation_sun_magnitude() {
        // Test Sun perturbation magnitude at LEO
        let r_sat = Vector3::new(7000e3, 0.0, 0.0); // LEO satellite
        let r_sun = sun_position_simple(0.0); // Sun at 1 AU

        let a_sun = third_body_perturbation(&r_sat, &r_sun, GM_SUN);

        // Sun perturbation at LEO should be ~0.5-2 × 10⁻⁶ m/s²
        // The magnitude depends on the relative geometry of satellite and sun
        let a_mag = a_sun.norm();
        assert!(
            a_mag > 1e-7 && a_mag < 3e-6,
            "Sun perturbation magnitude: {} m/s²",
            a_mag
        );
    }

    #[test]
    fn test_third_body_perturbation_moon_magnitude() {
        // Test Moon perturbation magnitude at LEO
        let r_sat = Vector3::new(7000e3, 0.0, 0.0); // LEO satellite
        let r_moon = moon_position_simple(0.0); // Moon at mean distance

        let a_moon = third_body_perturbation(&r_sat, &r_moon, GM_MOON);

        // Moon perturbation at LEO should be ~2-4 × 10⁻⁶ m/s²
        let a_mag = a_moon.norm();
        assert!(
            a_mag > 1e-6 && a_mag < 5e-6,
            "Moon perturbation magnitude: {} m/s²",
            a_mag
        );
    }

    #[test]
    fn test_third_body_perturbation_geo_larger() {
        // At GEO, third-body effects are larger than at LEO
        let r_leo = Vector3::new(7000e3, 0.0, 0.0);
        let r_geo = Vector3::new(42164e3, 0.0, 0.0); // GEO altitude

        let r_sun = sun_position_simple(0.0);

        let a_sun_leo = third_body_perturbation(&r_leo, &r_sun, GM_SUN);
        let a_sun_geo = third_body_perturbation(&r_geo, &r_sun, GM_SUN);

        // At GEO, Sun perturbation is relatively larger (distance matters less)
        // Actually, the perturbation magnitude can be larger at GEO
        // because the indirect term becomes more significant
        println!(
            "Sun perturbation at LEO: {} m/s²",
            a_sun_leo.norm()
        );
        println!(
            "Sun perturbation at GEO: {} m/s²",
            a_sun_geo.norm()
        );

        // Both should be reasonable magnitudes
        assert!(a_sun_leo.norm() > 1e-7 && a_sun_leo.norm() < 1e-4);
        assert!(a_sun_geo.norm() > 1e-7 && a_sun_geo.norm() < 1e-4);
    }

    #[test]
    fn test_sun_moon_perturbation_combined() {
        // Test that combined perturbation is sum of individual perturbations
        let r = Vector3::new(7000e3, 0.0, 0.0);
        let t = 0.0;

        let a_combined = sun_moon_perturbation(&r, t);

        // Compute individual perturbations
        let r_sun = sun_position_simple(t);
        let r_moon = moon_position_simple(t);
        let a_sun = third_body_perturbation(&r, &r_sun, GM_SUN);
        let a_moon = third_body_perturbation(&r, &r_moon, GM_MOON);
        let a_manual = a_sun + a_moon;

        // Should be identical
        assert_relative_eq!(a_combined.x, a_manual.x, epsilon = 1e-15);
        assert_relative_eq!(a_combined.y, a_manual.y, epsilon = 1e-15);
        assert_relative_eq!(a_combined.z, a_manual.z, epsilon = 1e-15);
    }

    #[test]
    fn test_third_body_perturbation_direct_indirect_terms() {
        // Verify that direct and indirect terms have correct signs
        let r_sat = Vector3::new(7000e3, 0.0, 0.0); // Satellite along +x
        let r_sun = Vector3::new(AU, 0.0, 0.0); // Sun also along +x (same direction)

        let a_sun = third_body_perturbation(&r_sat, &r_sun, GM_SUN);

        // When satellite and sun are in the same direction:
        // - Direct term pulls satellite toward sun (+x direction)
        // - Indirect term represents sun pulling Earth toward sun (-x from satellite's perspective)
        // Net effect depends on the balance

        // The x-component should be positive (pulled toward sun)
        // Actually, this depends on the exact geometry, but the magnitude should be reasonable
        println!("Sun perturbation when aligned: {:?}", a_sun);
        assert!(a_sun.norm() > 1e-7 && a_sun.norm() < 1e-4);
    }

    #[test]
    fn test_propagate_thirdbody_rk4_sun_only() {
        // Propagate with Sun perturbation only
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0; // 10 minutes
        let t0 = 0.0;

        let result = propagate_thirdbody_rk4(&r0, &v0, dt, GM_EARTH, t0, true, false, Some(10));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Orbit should still be valid
        assert!(r1.norm() > 6000e3); // Still above Earth
        assert!(v1.norm() > 1000.0); // Still has significant velocity
    }

    #[test]
    fn test_propagate_thirdbody_rk4_moon_only() {
        // Propagate with Moon perturbation only
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0;
        let t0 = 0.0;

        let result = propagate_thirdbody_rk4(&r0, &v0, dt, GM_EARTH, t0, false, true, Some(10));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_propagate_thirdbody_rk4_sun_and_moon() {
        // Propagate with both Sun and Moon perturbations
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0;
        let t0 = 0.0;

        let result = propagate_thirdbody_rk4(&r0, &v0, dt, GM_EARTH, t0, true, true, Some(10));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_propagate_thirdbody_dopri5_basic() {
        // Test adaptive integrator
        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0;
        let t0 = 0.0;

        let result = propagate_thirdbody_dopri5(&r0, &v0, dt, GM_EARTH, t0, true, true, Some(1e-8));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 1000.0);
    }

    #[test]
    fn test_thirdbody_vs_twobody_difference() {
        // Third-body effects should cause orbit to differ from pure two-body
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 3600.0; // 1 hour
        let t0 = 0.0;

        // Two-body propagation
        let (r_twobody, _v_twobody) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // Third-body propagation (Sun + Moon)
        let (r_thirdbody, _v_thirdbody) =
            propagate_thirdbody_rk4(&r0, &v0, dt, GM_EARTH, t0, true, true, Some(100)).unwrap();

        // Positions should differ (third-body causes perturbations)
        let pos_diff = (r_twobody - r_thirdbody).norm();
        println!("Position difference after 1 hour: {} m", pos_diff);

        // Difference should be measurable but not huge
        // After 1 hour at LEO, third-body effects should cause ~meters to tens of meters difference
        assert!(pos_diff > 0.1); // At least 10 cm difference
        assert!(pos_diff < 1000.0); // Less than 1 km difference
    }

    #[test]
    fn test_thirdbody_geo_significant() {
        // At GEO, third-body effects are more significant
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(42164e3, 0.0, 0.0); // GEO altitude
        let v0 = Vector3::new(0.0, 3075.0, 0.0); // GEO circular velocity
        let dt = 86400.0; // 1 day
        let t0 = 0.0;

        // Two-body propagation
        let (r_twobody, _v_twobody) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // Third-body propagation
        let (r_thirdbody, _v_thirdbody) =
            propagate_thirdbody_rk4(&r0, &v0, dt, GM_EARTH, t0, true, true, Some(1000)).unwrap();

        // At GEO over 1 day, third-body effects should be significant
        let pos_diff = (r_twobody - r_thirdbody).norm();
        println!("GEO position difference after 1 day: {} m", pos_diff);

        // Difference should be kilometers at GEO over 1 day
        assert!(pos_diff > 100.0); // At least 100 m
        assert!(pos_diff < 1e6); // Less than 1000 km (sanity check)
    }

    #[test]
    fn test_thirdbody_time_dependence() {
        // Third-body perturbations should vary with time as bodies move
        let r = Vector3::new(7000e3, 0.0, 0.0);
        let t0 = 0.0;
        let t1 = 86400.0; // 1 day later

        let a0 = sun_moon_perturbation(&r, t0);
        let a1 = sun_moon_perturbation(&r, t1);

        // Accelerations should be different (Sun and Moon have moved)
        let diff = (a0 - a1).norm();
        println!("Acceleration difference after 1 day: {} m/s²", diff);

        // Should be measurably different
        assert!(diff > 1e-8); // At least some difference
    }

    #[test]
    fn test_shadow_function_full_sunlight() {
        use crate::core::constants::R_EARTH;

        // Satellite on the Sun side of Earth - full sunlight
        let r_sat = Vector3::new(7000e3, 0.0, 0.0);
        let r_sun = Vector3::new(AU, 0.0, 0.0); // Sun in same direction

        let nu = shadow_function(&r_sat, &r_sun, R_EARTH);

        // Should be in full sunlight (nu = 1.0)
        assert_relative_eq!(nu, 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_shadow_function_full_umbra() {
        use crate::core::constants::R_EARTH;

        // Satellite directly behind Earth from Sun - full umbra
        let r_sat = Vector3::new(-7000e3, 0.0, 0.0); // Opposite to Sun
        let r_sun = Vector3::new(AU, 0.0, 0.0);

        let nu = shadow_function(&r_sat, &r_sun, R_EARTH);

        // Should be in full umbra (nu = 0.0)
        assert_relative_eq!(nu, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_shadow_function_penumbra() {
        use crate::core::constants::R_EARTH;

        // Satellite at edge of shadow cone - should be in penumbra
        // Place satellite at angle that puts it in partial shadow
        let r_sat = Vector3::new(-7000e3, 1000e3, 0.0);
        let r_sun = Vector3::new(AU, 0.0, 0.0);

        let nu = shadow_function(&r_sat, &r_sun, R_EARTH);

        // Should be in penumbra (0 < nu < 1)
        // The exact value depends on geometry
        assert!(nu >= 0.0 && nu <= 1.0, "Shadow function out of range: {}", nu);
    }

    #[test]
    fn test_shadow_function_high_altitude_less_shadow() {
        use crate::core::constants::R_EARTH;

        // Higher altitude satellites spend less time in shadow
        let r_sun = Vector3::new(AU, 0.0, 0.0);

        // LEO satellite behind Earth
        let r_leo = Vector3::new(-7000e3, 0.0, 0.0);
        let nu_leo = shadow_function(&r_leo, &r_sun, R_EARTH);

        // GEO satellite behind Earth (further from shadow cone)
        let r_geo = Vector3::new(-42164e3, 0.0, 0.0);
        let nu_geo = shadow_function(&r_geo, &r_sun, R_EARTH);

        // GEO should be more likely to be out of shadow
        // (Earth's shadow cone doesn't extend as far)
        assert!(nu_geo >= nu_leo, "GEO should have >= shadow function than LEO");
    }

    #[test]
    fn test_shadow_function_perpendicular_full_sun() {
        use crate::core::constants::R_EARTH;

        // Satellite perpendicular to Sun-Earth line
        let r_sat = Vector3::new(0.0, 7000e3, 0.0);
        let r_sun = Vector3::new(AU, 0.0, 0.0);

        let nu = shadow_function(&r_sat, &r_sun, R_EARTH);

        // Should be in full sunlight (not behind Earth)
        assert_relative_eq!(nu, 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_shadow_function_symmetry() {
        use crate::core::constants::R_EARTH;

        // Shadow function should be symmetric about Sun-Earth line
        let r_sun = Vector3::new(AU, 0.0, 0.0);

        let r_sat_plus_y = Vector3::new(-7000e3, 500e3, 0.0);
        let r_sat_minus_y = Vector3::new(-7000e3, -500e3, 0.0);
        let r_sat_plus_z = Vector3::new(-7000e3, 0.0, 500e3);

        let nu_plus_y = shadow_function(&r_sat_plus_y, &r_sun, R_EARTH);
        let nu_minus_y = shadow_function(&r_sat_minus_y, &r_sun, R_EARTH);
        let nu_plus_z = shadow_function(&r_sat_plus_z, &r_sun, R_EARTH);

        // Should all be equal (cylindrical symmetry)
        assert_relative_eq!(nu_plus_y, nu_minus_y, epsilon = 1e-10);
        assert_relative_eq!(nu_plus_y, nu_plus_z, epsilon = 1e-10);
    }
}

#[cfg(test)]
mod srp_tests {
    use super::*;
    use crate::core::constants::{AU, GM_EARTH, R_EARTH};
    use approx::assert_relative_eq;

    #[test]
    fn test_propagate_srp_rk4_basic() {
        // Test SRP propagation with RK4
        let r0 = Vector3::new(42164e3, 0.0, 0.0); // GEO altitude
        let v0 = Vector3::new(0.0, 3075.0, 0.0);
        let dt = 600.0; // 10 minutes

        // Typical values for a satellite with solar panels
        let area_mass_ratio = 0.01; // m²/kg
        let C_r = 1.3; // Reflectivity coefficient
        let t0 = 0.0;

        let result = propagate_srp_rk4(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(100));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Orbit should still be valid
        assert!(r1.norm() > 40000e3); // Still near GEO
        assert!(v1.norm() > 2000.0); // Still has orbital velocity
    }

    #[test]
    fn test_propagate_srp_dopri5_basic() {
        // Test SRP propagation with DOPRI5
        let r0 = Vector3::new(42164e3, 0.0, 0.0); // GEO altitude
        let v0 = Vector3::new(0.0, 3075.0, 0.0);
        let dt = 600.0;

        let area_mass_ratio = 0.01;
        let C_r = 1.3;
        let t0 = 0.0;

        let result = propagate_srp_dopri5(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(1e-8));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        assert!(r1.norm() > 40000e3);
        assert!(v1.norm() > 2000.0);
    }

    #[test]
    fn test_propagate_srp_rk4_vs_dopri5() {
        // Both integrators should give similar results
        let r0 = Vector3::new(42164e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 3075.0, 0.0);
        let dt = 3600.0; // 1 hour

        let area_mass_ratio = 0.01;
        let C_r = 1.3;
        let t0 = 0.0;

        let (r_rk4, v_rk4) = propagate_srp_rk4(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(100)).unwrap();
        let (r_dopri5, v_dopri5) = propagate_srp_dopri5(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(1e-8)).unwrap();

        // Results should be close (both accurate integrators)
        let pos_diff = (r_rk4 - r_dopri5).norm();
        let vel_diff = (v_rk4 - v_dopri5).norm();

        // Should agree within reasonable tolerance
        assert!(pos_diff < 100.0, "Position difference: {} m", pos_diff);
        assert!(vel_diff < 0.1, "Velocity difference: {} m/s", vel_diff);
    }

    #[test]
    fn test_propagate_srp_vs_twobody() {
        // SRP should cause orbit to differ from pure two-body
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(42164e3, 0.0, 0.0); // GEO
        let v0 = Vector3::new(0.0, 3075.0, 0.0);
        let dt = 86400.0; // 1 day

        let area_mass_ratio = 0.01; // Relatively large area
        let C_r = 1.3;
        let t0 = 0.0;

        // Two-body propagation
        let (r_twobody, _v_twobody) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // SRP propagation
        let (r_srp, _v_srp) = propagate_srp_rk4(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(1000)).unwrap();

        // Positions should differ (SRP causes perturbations)
        let pos_diff = (r_twobody - r_srp).norm();
        println!("Position difference after 1 day (GEO): {} m", pos_diff);

        // SRP at GEO over 1 day should cause measurable difference
        assert!(pos_diff > 1.0); // At least 1 m difference
        assert!(pos_diff < 100000.0); // Less than 100 km (sanity check)
    }

    #[test]
    fn test_propagate_srp_zero_area() {
        // Zero area/mass ratio should give two-body propagation
        use crate::propagators::keplerian::propagate_state_keplerian;

        let r0 = Vector3::new(42164e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 3075.0, 0.0);
        let dt = 3600.0;

        let area_mass_ratio = 0.0; // No SRP effect
        let C_r = 1.3;
        let t0 = 0.0;

        let (r_srp, v_srp) = propagate_srp_rk4(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(100)).unwrap();
        let (r_twobody, v_twobody) = propagate_state_keplerian(&r0, &v0, dt, GM_EARTH).unwrap();

        // Should be very close to two-body (only numerical errors)
        let pos_diff = (r_srp - r_twobody).norm();
        let vel_diff = (v_srp - v_twobody).norm();

        assert!(pos_diff < 10.0, "Position difference: {} m", pos_diff);
        assert!(vel_diff < 0.01, "Velocity difference: {} m/s", vel_diff);
    }

    #[test]
    fn test_propagate_srp_shadow_effect() {
        // SRP should be reduced in Earth's shadow
        let r0 = Vector3::new(7000e3, 0.0, 0.0); // LEO
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 600.0;

        let area_mass_ratio = 0.02; // High area for LEO
        let C_r = 1.5;
        let t0 = 0.0;

        // Propagate - should handle shadow transitions
        let result = propagate_srp_rk4(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, Some(100));
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // Verify orbit is still reasonable
        assert!(r1.norm() > 6000e3);
        assert!(v1.norm() > 6000.0);
    }

    #[test]
    fn test_propagate_srp_long_duration() {
        // Test longer propagation
        let r0 = Vector3::new(42164e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 3075.0, 0.0);

        // One day
        let dt = 86400.0;
        let area_mass_ratio = 0.01;
        let C_r = 1.3;
        let t0 = 0.0;

        let result = propagate_srp_dopri5(&r0, &v0, dt, GM_EARTH, area_mass_ratio, C_r, R_EARTH, t0, None);
        assert!(result.is_ok());

        let (r1, v1) = result.unwrap();

        // After 1 day at GEO, orbit should still be reasonable
        // Semi-major axis should be roughly preserved
        let a0 = r0.norm();
        let a1 = r1.norm();
        let a_ratio = a1 / a0;

        assert!((a_ratio - 1.0).abs() < 0.01, "Semi-major axis change: {}", a_ratio);

        // Velocity magnitude roughly preserved
        let v_ratio = v1.norm() / v0.norm();
        assert!((v_ratio - 1.0).abs() < 0.05, "Velocity magnitude change: {}", v_ratio);
    }
}

//==============================================================================
// COMPOSABLE PERTURBATION FRAMEWORK (Trait-Based Design)
//==============================================================================

/// Trait for composable perturbation models
///
/// This trait defines the interface for all perturbation accelerations,
/// enabling flexible composition of different force models. All perturbations
/// must be `Send + Sync` to support parallel propagation with rayon.
///
/// # Design Philosophy
///
/// This trait-based design allows:
/// 1. **Composability**: Mix and match different perturbations
/// 2. **Extensibility**: Users can define custom perturbations
/// 3. **Type Safety**: Compile-time guarantees for perturbation combinations
/// 4. **Performance**: Zero-cost abstractions via trait objects
///
/// # Example
///
/// ```ignore
/// use astrora::propagators::perturbations::{Perturbation, J2Perturbation, DragPerturbation};
/// use astrora::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
///
/// // Create individual perturbations
/// let j2 = J2Perturbation::new(J2_EARTH, R_EARTH);
/// let drag = DragPerturbation::new(R_EARTH, 1.225, 8500.0, 100.0);
///
/// // Use them individually
/// let a_j2 = j2.acceleration(0.0, &r, &v, GM_EARTH);
/// let a_drag = drag.acceleration(0.0, &r, &v, GM_EARTH);
///
/// // Or combine them
/// let perts: Vec<Box<dyn Perturbation>> = vec![Box::new(j2), Box::new(drag)];
/// let combined = PerturbationSet::new(perts);
/// ```
///
/// # References
/// - Inspired by nyx-space's ForceModel trait design
/// - Vallado "Fundamentals of Astrodynamics" Ch. 8
/// - Curtis "Orbital Mechanics" Ch. 12
pub trait Perturbation: Send + Sync {
    /// Compute the perturbation acceleration at a given state
    ///
    /// # Arguments
    /// * `t` - Time since epoch (seconds, typically J2000)
    /// * `r` - Position vector in inertial frame (meters)
    /// * `v` - Velocity vector in inertial frame (meters/second)
    /// * `mu` - Standard gravitational parameter of central body (m³/s²)
    ///
    /// # Returns
    /// Perturbation acceleration vector (m/s²)
    ///
    /// # Notes
    /// - The returned acceleration should be in the same inertial frame as position
    /// - Time parameter allows for time-dependent perturbations (e.g., third-body, SRP)
    /// - The `mu` parameter is the central body's GM, not the perturbing body
    fn acceleration(&self, t: f64, r: &Vector3, v: &Vector3, mu: f64) -> Vector3;

    /// Get a human-readable name for this perturbation
    ///
    /// Used for logging, debugging, and user feedback.
    fn name(&self) -> &str;

    /// Check if this perturbation is time-dependent
    ///
    /// Returns true if the acceleration depends on time `t`.
    /// This can be used for optimization (e.g., caching for time-independent forces).
    ///
    /// Default implementation returns false (time-independent).
    fn is_time_dependent(&self) -> bool {
        false
    }
}

//==============================================================================
// CONCRETE PERTURBATION IMPLEMENTATIONS
//==============================================================================

/// J2 oblateness perturbation
///
/// Wraps the J2 perturbation calculation in a trait-based type.
/// This accounts for the equatorial bulge of the central body.
///
/// # Parameters
/// - `j2`: J2 coefficient (dimensionless, ~1.08263e-3 for Earth)
/// - `R`: Equatorial radius (meters, ~6378.137 km for Earth)
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::J2Perturbation;
/// use astrora::core::constants::{J2_EARTH, R_EARTH};
///
/// let j2_pert = J2Perturbation::new(J2_EARTH, R_EARTH);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct J2Perturbation {
    /// J2 oblateness coefficient (dimensionless)
    pub j2: f64,
    /// Equatorial radius (m)
    pub radius: f64,
}

impl J2Perturbation {
    /// Create a new J2 perturbation
    ///
    /// # Arguments
    /// * `j2` - J2 oblateness coefficient (dimensionless)
    /// * `radius` - Equatorial radius of central body (meters)
    pub fn new(j2: f64, radius: f64) -> Self {
        Self { j2, radius }
    }

    /// Create J2 perturbation for Earth (convenience constructor)
    pub fn earth() -> Self {
        use crate::core::constants::{J2_EARTH, R_EARTH};
        Self::new(J2_EARTH, R_EARTH)
    }
}

impl Perturbation for J2Perturbation {
    fn acceleration(&self, _t: f64, r: &Vector3, _v: &Vector3, mu: f64) -> Vector3 {
        j2_perturbation(r, mu, self.j2, self.radius)
    }

    fn name(&self) -> &str {
        "J2 Oblateness"
    }

    fn is_time_dependent(&self) -> bool {
        false
    }
}

/// Atmospheric drag perturbation (exponential atmosphere model)
///
/// Models atmospheric drag using a simple exponential density model.
/// Suitable for altitudes between 100-1000 km.
///
/// # Parameters
/// - `R`: Body radius (m)
/// - `rho0`: Reference density at sea level (kg/m³, ~1.225 for Earth)
/// - `H0`: Atmospheric scale height (m, ~8500 for Earth)
/// - `B`: Ballistic coefficient m/(C_d × A) in kg/m²
///
/// # Limitations
/// - Simple exponential model (constant scale height)
/// - Non-rotating atmosphere assumption
/// - No solar/geomagnetic activity effects
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::DragPerturbation;
/// use astrora::core::constants::{R_EARTH, RHO0_EARTH, H0_EARTH};
///
/// // ISS-like spacecraft: 100 kg/m²
/// let drag = DragPerturbation::new(R_EARTH, RHO0_EARTH, H0_EARTH, 100.0);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct DragPerturbation {
    /// Body radius (m)
    pub radius: f64,
    /// Reference density (kg/m³)
    pub rho0: f64,
    /// Scale height (m)
    pub scale_height: f64,
    /// Ballistic coefficient (kg/m²)
    pub ballistic_coeff: f64,
}

impl DragPerturbation {
    /// Create a new atmospheric drag perturbation
    ///
    /// # Arguments
    /// * `radius` - Body radius (m)
    /// * `rho0` - Reference density at sea level (kg/m³)
    /// * `scale_height` - Atmospheric scale height (m)
    /// * `ballistic_coeff` - Ballistic coefficient B = m/(C_d × A) in kg/m²
    pub fn new(radius: f64, rho0: f64, scale_height: f64, ballistic_coeff: f64) -> Self {
        Self {
            radius,
            rho0,
            scale_height,
            ballistic_coeff,
        }
    }

    /// Create drag perturbation for Earth (convenience constructor)
    ///
    /// # Arguments
    /// * `ballistic_coeff` - Ballistic coefficient in kg/m²
    ///   - Small satellites/CubeSats: 10-50 kg/m²
    ///   - ISS: 50-100 kg/m²
    ///   - Large satellites: 100-500 kg/m²
    pub fn earth(ballistic_coeff: f64) -> Self {
        use crate::core::constants::{H0_EARTH, R_EARTH, RHO0_EARTH};
        Self::new(R_EARTH, RHO0_EARTH, H0_EARTH, ballistic_coeff)
    }
}

impl Perturbation for DragPerturbation {
    fn acceleration(&self, _t: f64, r: &Vector3, v: &Vector3, _mu: f64) -> Vector3 {
        drag_acceleration(
            r,
            v,
            self.radius,
            self.rho0,
            self.scale_height,
            self.ballistic_coeff,
        )
    }

    fn name(&self) -> &str {
        "Atmospheric Drag"
    }

    fn is_time_dependent(&self) -> bool {
        false
    }
}

/// Third-body gravitational perturbation
///
/// Models the gravitational perturbation from a third body (e.g., Sun, Moon).
/// Can use either a simple circular ephemeris or a custom position function.
///
/// # Variants
/// - `Sun`: Simplified Sun ephemeris (1 AU circular orbit)
/// - `Moon`: Simplified Moon ephemeris (384,400 km circular orbit)
/// - `Custom`: User-provided position function and gravitational parameter
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::ThirdBodyPerturbation;
/// use astrora::core::constants::{GM_SUN, GM_MOON};
///
/// // Use built-in Sun perturbation
/// let sun = ThirdBodyPerturbation::sun();
///
/// // Use built-in Moon perturbation
/// let moon = ThirdBodyPerturbation::moon();
///
/// // Or create a custom third body
/// let jupiter = ThirdBodyPerturbation::custom(
///     GM_JUPITER,
///     |t| jupiter_position_function(t),
/// );
/// ```
#[derive(Clone)]
pub enum ThirdBodyPerturbation {
    /// Sun perturbation using simplified circular ephemeris
    Sun,
    /// Moon perturbation using simplified circular ephemeris
    Moon,
    /// Custom third body with user-provided position function
    Custom {
        /// Gravitational parameter of third body (m³/s²)
        mu: f64,
        /// Function to compute third body position at time t
        position_func: fn(f64) -> Vector3,
        /// Name of the third body (for identification)
        body_name: String,
    },
}

impl ThirdBodyPerturbation {
    /// Create Sun perturbation (simplified circular ephemeris)
    pub fn sun() -> Self {
        Self::Sun
    }

    /// Create Moon perturbation (simplified circular ephemeris)
    pub fn moon() -> Self {
        Self::Moon
    }

    /// Create custom third body perturbation
    ///
    /// # Arguments
    /// * `mu` - Gravitational parameter of third body (m³/s²)
    /// * `position_func` - Function to compute position at time t (seconds since J2000)
    /// * `name` - Human-readable name for the body
    pub fn custom(mu: f64, position_func: fn(f64) -> Vector3, name: impl Into<String>) -> Self {
        Self::Custom {
            mu,
            position_func,
            body_name: name.into(),
        }
    }

    /// Get the gravitational parameter for this third body
    fn get_mu(&self) -> f64 {
        use crate::core::constants::{GM_MOON, GM_SUN};
        match self {
            Self::Sun => GM_SUN,
            Self::Moon => GM_MOON,
            Self::Custom { mu, .. } => *mu,
        }
    }

    /// Get the position of the third body at time t
    fn get_position(&self, t: f64) -> Vector3 {
        match self {
            Self::Sun => sun_position_simple(t),
            Self::Moon => moon_position_simple(t),
            Self::Custom { position_func, .. } => position_func(t),
        }
    }
}

impl Perturbation for ThirdBodyPerturbation {
    fn acceleration(&self, t: f64, r: &Vector3, _v: &Vector3, _mu: f64) -> Vector3 {
        let r_third = self.get_position(t);
        let mu_third = self.get_mu();
        third_body_perturbation(r, &r_third, mu_third)
    }

    fn name(&self) -> &str {
        match self {
            Self::Sun => "Third-Body (Sun)",
            Self::Moon => "Third-Body (Moon)",
            Self::Custom { body_name, .. } => body_name,
        }
    }

    fn is_time_dependent(&self) -> bool {
        true // Third body positions change with time
    }
}

impl std::fmt::Debug for ThirdBodyPerturbation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sun => write!(f, "ThirdBodyPerturbation::Sun"),
            Self::Moon => write!(f, "ThirdBodyPerturbation::Moon"),
            Self::Custom { mu, body_name, .. } => {
                f.debug_struct("ThirdBodyPerturbation::Custom")
                    .field("mu", mu)
                    .field("body_name", body_name)
                    .finish()
            }
        }
    }
}

/// Solar radiation pressure perturbation (cannon-ball model)
///
/// Models solar radiation pressure using a simplified cannon-ball model
/// with shadow function (umbra/penumbra). Suitable for spacecraft with
/// simple geometries.
///
/// # Parameters
/// - `area_mass_ratio`: A/m in m²/kg
/// - `reflectivity`: C_r coefficient (1.0-2.0, typically ~1.3)
/// - `body_radius`: Radius of shadowing body (m)
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::SolarRadiationPressure;
/// use astrora::core::constants::R_EARTH;
///
/// // CubeSat: A/m ≈ 0.01 m²/kg, C_r ≈ 1.3
/// let srp = SolarRadiationPressure::new(0.01, 1.3, R_EARTH);
///
/// // Solar sail: A/m ≈ 10 m²/kg, C_r ≈ 2.0
/// let solar_sail = SolarRadiationPressure::new(10.0, 2.0, R_EARTH);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct SolarRadiationPressure {
    /// Area-to-mass ratio (m²/kg)
    pub area_mass_ratio: f64,
    /// Reflectivity coefficient (dimensionless, 1.0-2.0)
    pub reflectivity: f64,
    /// Radius of shadowing body (m)
    pub body_radius: f64,
}

impl SolarRadiationPressure {
    /// Create a new solar radiation pressure perturbation
    ///
    /// # Arguments
    /// * `area_mass_ratio` - A/m in m²/kg
    ///   - CubeSats: ~0.01 m²/kg
    ///   - Typical satellites: 0.01-0.1 m²/kg
    ///   - Solar sails: 1-100 m²/kg
    /// * `reflectivity` - C_r coefficient
    ///   - Perfect absorption: 1.0
    ///   - Typical spacecraft: 1.2-1.5
    ///   - Perfect reflection: 2.0
    /// * `body_radius` - Radius of shadowing body (m)
    pub fn new(area_mass_ratio: f64, reflectivity: f64, body_radius: f64) -> Self {
        Self {
            area_mass_ratio,
            reflectivity,
            body_radius,
        }
    }

    /// Create SRP for Earth-orbiting spacecraft (convenience constructor)
    ///
    /// # Arguments
    /// * `area_mass_ratio` - A/m in m²/kg
    /// * `reflectivity` - C_r coefficient (typically 1.2-1.5)
    pub fn earth(area_mass_ratio: f64, reflectivity: f64) -> Self {
        use crate::core::constants::R_EARTH;
        Self::new(area_mass_ratio, reflectivity, R_EARTH)
    }
}

impl Perturbation for SolarRadiationPressure {
    fn acceleration(&self, t: f64, r: &Vector3, _v: &Vector3, _mu: f64) -> Vector3 {
        let r_sun = sun_position_simple(t);
        srp_acceleration(
            r,
            &r_sun,
            self.area_mass_ratio,
            self.reflectivity,
            self.body_radius,
        )
    }

    fn name(&self) -> &str {
        "Solar Radiation Pressure"
    }

    fn is_time_dependent(&self) -> bool {
        true // Sun position changes with time
    }
}

/// Collection of perturbations that can be applied together
///
/// This type allows combining multiple perturbations into a single
/// unit that can be used with propagators. The total acceleration
/// is the sum of all individual perturbation accelerations.
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::{
///     PerturbationSet, J2Perturbation, DragPerturbation, ThirdBodyPerturbation
/// };
///
/// let mut perts = PerturbationSet::new();
/// perts.add(J2Perturbation::earth());
/// perts.add(DragPerturbation::earth(100.0));
/// perts.add(ThirdBodyPerturbation::sun());
/// perts.add(ThirdBodyPerturbation::moon());
///
/// // Use with propagator
/// let (r, v) = propagate_with_perturbations(&r0, &v0, dt, GM_EARTH, &perts)?;
/// ```
#[derive(Default)]
pub struct PerturbationSet {
    perturbations: Vec<Box<dyn Perturbation>>,
}

impl PerturbationSet {
    /// Create a new empty perturbation set
    pub fn new() -> Self {
        Self {
            perturbations: Vec::new(),
        }
    }

    /// Add a perturbation to the set
    ///
    /// # Arguments
    /// * `perturbation` - Any type implementing the Perturbation trait
    pub fn add<P: Perturbation + 'static>(&mut self, perturbation: P) {
        self.perturbations.push(Box::new(perturbation));
    }

    /// Get the number of perturbations in the set
    pub fn len(&self) -> usize {
        self.perturbations.len()
    }

    /// Check if the set is empty
    pub fn is_empty(&self) -> bool {
        self.perturbations.is_empty()
    }

    /// Get names of all perturbations in the set
    pub fn names(&self) -> Vec<&str> {
        self.perturbations.iter().map(|p| p.name()).collect()
    }

    /// Check if any perturbation is time-dependent
    pub fn is_time_dependent(&self) -> bool {
        self.perturbations.iter().any(|p| p.is_time_dependent())
    }

    /// Compute the total perturbation acceleration from all perturbations
    ///
    /// # Arguments
    /// * `t` - Time since epoch (seconds)
    /// * `r` - Position vector (m)
    /// * `v` - Velocity vector (m/s)
    /// * `mu` - Standard gravitational parameter (m³/s²)
    ///
    /// # Returns
    /// Total perturbation acceleration (m/s²)
    pub fn total_acceleration(&self, t: f64, r: &Vector3, v: &Vector3, mu: f64) -> Vector3 {
        let mut total = Vector3::zeros();
        for pert in &self.perturbations {
            total += pert.acceleration(t, r, v, mu);
        }
        total
    }
}

impl Perturbation for PerturbationSet {
    fn acceleration(&self, t: f64, r: &Vector3, v: &Vector3, mu: f64) -> Vector3 {
        self.total_acceleration(t, r, v, mu)
    }

    fn name(&self) -> &str {
        "Combined Perturbations"
    }

    fn is_time_dependent(&self) -> bool {
        self.is_time_dependent()
    }
}

impl std::fmt::Debug for PerturbationSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PerturbationSet")
            .field("count", &self.len())
            .field("names", &self.names())
            .finish()
    }
}

/// Propagate orbit with trait-based perturbations (new API)
///
/// This is a new, more flexible version of `propagate_cowell` that uses
/// the trait-based perturbation framework. It allows mixing different
/// perturbation types seamlessly.
///
/// # Arguments
/// * `r0` - Initial position (m)
/// * `v0` - Initial velocity (m/s)
/// * `dt` - Time step (seconds)
/// * `mu` - Central body gravitational parameter (m³/s²)
/// * `perturbations` - Perturbation set or any type implementing Perturbation
/// * `method` - Integration method: "rk4" or "dopri5"
/// * `n_steps` - Number of steps for RK4 (None = 100)
/// * `tol` - Tolerance for DOPRI5 (None = 1e-8)
///
/// # Returns
/// Tuple of (final position, final velocity)
///
/// # Example
/// ```ignore
/// use astrora::propagators::perturbations::{
///     propagate_with_perturbations, PerturbationSet,
///     J2Perturbation, DragPerturbation
/// };
/// use astrora::core::constants::GM_EARTH;
///
/// let mut perts = PerturbationSet::new();
/// perts.add(J2Perturbation::earth());
/// perts.add(DragPerturbation::earth(100.0));
///
/// let (r, v) = propagate_with_perturbations(
///     &r0, &v0, 3600.0, GM_EARTH, &perts, "dopri5", None, None
/// )?;
/// ```
pub fn propagate_with_perturbations<P: Perturbation + ?Sized>(
    r0: &Vector3,
    v0: &Vector3,
    dt: f64,
    mu: f64,
    perturbations: &P,
    method: &str,
    n_steps: Option<usize>,
    tol: Option<f64>,
) -> PoliastroResult<(Vector3, Vector3)> {
    use crate::core::numerical::{dopri5_integrate, rk4_step};

    // Create acceleration function combining two-body + perturbations
    let accel_func = |t: f64, state: &nalgebra::DVector<f64>| -> nalgebra::DVector<f64> {
        let r = Vector3::new(state[0], state[1], state[2]);
        let v = Vector3::new(state[3], state[4], state[5]);

        let r_mag = r.norm();

        // Two-body acceleration: -μ/r³ * r
        let a_twobody = -mu / (r_mag * r_mag * r_mag) * r;

        // Add perturbation acceleration
        let a_pert = perturbations.acceleration(t, &r, &v, mu);

        let a_total = a_twobody + a_pert;

        // Return derivative: [vx, vy, vz, ax, ay, az]
        nalgebra::DVector::from_vec(vec![v.x, v.y, v.z, a_total.x, a_total.y, a_total.z])
    };

    // Initial state
    let mut state = nalgebra::DVector::from_vec(vec![r0.x, r0.y, r0.z, v0.x, v0.y, v0.z]);

    // Integrate based on method
    let state_final = match method.to_lowercase().as_str() {
        "rk4" => {
            let steps = n_steps.unwrap_or(100);
            let h = dt / steps as f64;
            let mut t = 0.0;

            // Integrate using multiple RK4 steps
            for _ in 0..steps {
                state = rk4_step(accel_func, t, &state, h);
                t += h;
            }
            state
        }
        "dopri5" => {
            let tolerance = tol.unwrap_or(1e-8);
            let h0 = dt.abs() / 10.0; // Initial step size guess
            dopri5_integrate(accel_func, 0.0, &state, dt, h0, tolerance, None)?
        }
        _ => {
            return Err(PoliastroError::invalid_state(format!(
                "Unknown integration method: {method}. Use 'rk4' or 'dopri5'"
            )))
        }
    };

    // Extract final position and velocity
    let r_final = Vector3::new(state_final[0], state_final[1], state_final[2]);
    let v_final = Vector3::new(state_final[3], state_final[4], state_final[5]);

    Ok((r_final, v_final))
}

//==============================================================================
// TESTS FOR TRAIT-BASED PERTURBATION FRAMEWORK
//==============================================================================

#[cfg(test)]
mod perturbation_trait_tests {
    use super::*;
    use crate::core::constants::{GM_EARTH, J2_EARTH, R_EARTH};
    use approx::assert_relative_eq;

    #[test]
    fn test_j2_perturbation_trait() {
        let j2_pert = J2Perturbation::new(J2_EARTH, R_EARTH);

        let r = Vector3::new(7000e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7546.0, 0.0);

        let a = j2_pert.acceleration(0.0, &r, &v, GM_EARTH);

        // Should match direct function call
        let a_direct = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);

        assert_relative_eq!(a.x, a_direct.x, epsilon = 1e-12);
        assert_relative_eq!(a.y, a_direct.y, epsilon = 1e-12);
        assert_relative_eq!(a.z, a_direct.z, epsilon = 1e-12);

        assert_eq!(j2_pert.name(), "J2 Oblateness");
        assert!(!j2_pert.is_time_dependent());
    }

    #[test]
    fn test_j2_earth_convenience() {
        let j2_pert = J2Perturbation::earth();

        assert_relative_eq!(j2_pert.j2, J2_EARTH, epsilon = 1e-15);
        assert_relative_eq!(j2_pert.radius, R_EARTH, epsilon = 1e-15);
    }

    #[test]
    fn test_drag_perturbation_trait() {
        use crate::core::constants::{H0_EARTH, RHO0_EARTH};

        let drag_pert = DragPerturbation::new(R_EARTH, RHO0_EARTH, H0_EARTH, 100.0);

        let r = Vector3::new(6778e3, 0.0, 0.0); // 400 km altitude
        let v = Vector3::new(0.0, 7670.0, 0.0);

        let a = drag_pert.acceleration(0.0, &r, &v, GM_EARTH);

        // Should match direct function call
        let a_direct = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, 100.0);

        assert_relative_eq!(a.x, a_direct.x, epsilon = 1e-12);
        assert_relative_eq!(a.y, a_direct.y, epsilon = 1e-12);
        assert_relative_eq!(a.z, a_direct.z, epsilon = 1e-12);

        assert_eq!(drag_pert.name(), "Atmospheric Drag");
        assert!(!drag_pert.is_time_dependent());
    }

    #[test]
    fn test_drag_earth_convenience() {
        use crate::core::constants::{H0_EARTH, RHO0_EARTH};

        let drag_pert = DragPerturbation::earth(100.0);

        assert_relative_eq!(drag_pert.radius, R_EARTH, epsilon = 1e-15);
        assert_relative_eq!(drag_pert.rho0, RHO0_EARTH, epsilon = 1e-15);
        assert_relative_eq!(drag_pert.scale_height, H0_EARTH, epsilon = 1e-15);
        assert_relative_eq!(drag_pert.ballistic_coeff, 100.0, epsilon = 1e-15);
    }

    #[test]
    fn test_thirdbody_sun_perturbation() {
        let sun_pert = ThirdBodyPerturbation::sun();

        let r = Vector3::new(42164e3, 0.0, 0.0); // GEO
        let v = Vector3::new(0.0, 3075.0, 0.0);

        let a = sun_pert.acceleration(0.0, &r, &v, GM_EARTH);

        // Should match direct function call
        let r_sun = sun_position_simple(0.0);
        let a_direct = third_body_perturbation(&r, &r_sun, crate::core::constants::GM_SUN);

        assert_relative_eq!(a.x, a_direct.x, epsilon = 1e-12);
        assert_relative_eq!(a.y, a_direct.y, epsilon = 1e-12);
        assert_relative_eq!(a.z, a_direct.z, epsilon = 1e-12);

        assert_eq!(sun_pert.name(), "Third-Body (Sun)");
        assert!(sun_pert.is_time_dependent());
    }

    #[test]
    fn test_thirdbody_moon_perturbation() {
        let moon_pert = ThirdBodyPerturbation::moon();

        let r = Vector3::new(42164e3, 0.0, 0.0); // GEO
        let v = Vector3::new(0.0, 3075.0, 0.0);

        let a = moon_pert.acceleration(0.0, &r, &v, GM_EARTH);

        // Should match direct function call
        let r_moon = moon_position_simple(0.0);
        let a_direct = third_body_perturbation(&r, &r_moon, crate::core::constants::GM_MOON);

        assert_relative_eq!(a.x, a_direct.x, epsilon = 1e-12);
        assert_relative_eq!(a.y, a_direct.y, epsilon = 1e-12);
        assert_relative_eq!(a.z, a_direct.z, epsilon = 1e-12);

        assert_eq!(moon_pert.name(), "Third-Body (Moon)");
        assert!(moon_pert.is_time_dependent());
    }

    #[test]
    fn test_thirdbody_custom_perturbation() {
        fn custom_body_pos(_t: f64) -> Vector3 {
            Vector3::new(1e9, 0.0, 0.0)
        }

        let custom_pert = ThirdBodyPerturbation::custom(1e15, custom_body_pos, "Custom Body");

        let r = Vector3::new(7000e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7546.0, 0.0);

        let a = custom_pert.acceleration(0.0, &r, &v, GM_EARTH);

        // Should be non-zero
        assert!(a.norm() > 0.0);

        assert_eq!(custom_pert.name(), "Custom Body");
        assert!(custom_pert.is_time_dependent());
    }

    #[test]
    fn test_srp_perturbation_trait() {
        let srp_pert = SolarRadiationPressure::new(0.01, 1.3, R_EARTH);

        let r = Vector3::new(42164e3, 0.0, 0.0); // GEO
        let v = Vector3::new(0.0, 3075.0, 0.0);

        let a = srp_pert.acceleration(0.0, &r, &v, GM_EARTH);

        // Should match direct function call
        let r_sun = sun_position_simple(0.0);
        let a_direct = srp_acceleration(&r, &r_sun, 0.01, 1.3, R_EARTH);

        assert_relative_eq!(a.x, a_direct.x, epsilon = 1e-12);
        assert_relative_eq!(a.y, a_direct.y, epsilon = 1e-12);
        assert_relative_eq!(a.z, a_direct.z, epsilon = 1e-12);

        assert_eq!(srp_pert.name(), "Solar Radiation Pressure");
        assert!(srp_pert.is_time_dependent());
    }

    #[test]
    fn test_srp_earth_convenience() {
        let srp_pert = SolarRadiationPressure::earth(0.01, 1.3);

        assert_relative_eq!(srp_pert.area_mass_ratio, 0.01, epsilon = 1e-15);
        assert_relative_eq!(srp_pert.reflectivity, 1.3, epsilon = 1e-15);
        assert_relative_eq!(srp_pert.body_radius, R_EARTH, epsilon = 1e-15);
    }

    #[test]
    fn test_perturbation_set_empty() {
        let perts = PerturbationSet::new();

        assert_eq!(perts.len(), 0);
        assert!(perts.is_empty());
        assert!(!perts.is_time_dependent());

        let r = Vector3::new(7000e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7546.0, 0.0);
        let a = perts.total_acceleration(0.0, &r, &v, GM_EARTH);

        // Empty set should give zero acceleration
        assert_relative_eq!(a.x, 0.0, epsilon = 1e-15);
        assert_relative_eq!(a.y, 0.0, epsilon = 1e-15);
        assert_relative_eq!(a.z, 0.0, epsilon = 1e-15);
    }

    #[test]
    fn test_perturbation_set_single() {
        let mut perts = PerturbationSet::new();
        perts.add(J2Perturbation::earth());

        assert_eq!(perts.len(), 1);
        assert!(!perts.is_empty());
        assert!(!perts.is_time_dependent());

        let names = perts.names();
        assert_eq!(names, vec!["J2 Oblateness"]);

        let r = Vector3::new(7000e3, 0.0, 0.0);
        let v = Vector3::new(0.0, 7546.0, 0.0);
        let a = perts.total_acceleration(0.0, &r, &v, GM_EARTH);

        // Should match J2 perturbation alone
        let a_j2 = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);
        assert_relative_eq!(a.x, a_j2.x, epsilon = 1e-12);
        assert_relative_eq!(a.y, a_j2.y, epsilon = 1e-12);
        assert_relative_eq!(a.z, a_j2.z, epsilon = 1e-12);
    }

    #[test]
    fn test_perturbation_set_multiple() {
        let mut perts = PerturbationSet::new();
        perts.add(J2Perturbation::earth());
        perts.add(DragPerturbation::earth(100.0));
        perts.add(ThirdBodyPerturbation::sun());
        perts.add(ThirdBodyPerturbation::moon());

        assert_eq!(perts.len(), 4);
        assert!(!perts.is_empty());
        assert!(perts.is_time_dependent()); // Sun and Moon are time-dependent

        let names = perts.names();
        assert_eq!(names.len(), 4);
        assert!(names.contains(&"J2 Oblateness"));
        assert!(names.contains(&"Atmospheric Drag"));
        assert!(names.contains(&"Third-Body (Sun)"));
        assert!(names.contains(&"Third-Body (Moon)"));

        let r = Vector3::new(6778e3, 0.0, 0.0); // 400 km altitude
        let v = Vector3::new(0.0, 7670.0, 0.0);
        let a = perts.total_acceleration(0.0, &r, &v, GM_EARTH);

        // Total should be non-zero
        assert!(a.norm() > 0.0);

        // Should be sum of individual accelerations
        use crate::core::constants::{H0_EARTH, RHO0_EARTH};
        let a_j2 = j2_perturbation(&r, GM_EARTH, J2_EARTH, R_EARTH);
        let a_drag = drag_acceleration(&r, &v, R_EARTH, RHO0_EARTH, H0_EARTH, 100.0);
        let r_sun = sun_position_simple(0.0);
        let a_sun = third_body_perturbation(&r, &r_sun, crate::core::constants::GM_SUN);
        let r_moon = moon_position_simple(0.0);
        let a_moon = third_body_perturbation(&r, &r_moon, crate::core::constants::GM_MOON);

        let a_expected = a_j2 + a_drag + a_sun + a_moon;

        assert_relative_eq!(a.x, a_expected.x, epsilon = 1e-10);
        assert_relative_eq!(a.y, a_expected.y, epsilon = 1e-10);
        assert_relative_eq!(a.z, a_expected.z, epsilon = 1e-10);
    }

    #[test]
    fn test_propagate_with_perturbations_j2_only() {
        let mut perts = PerturbationSet::new();
        perts.add(J2Perturbation::earth());

        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);
        let dt = 3600.0;

        let result = propagate_with_perturbations(
            &r0, &v0, dt, GM_EARTH, &perts, "rk4", Some(100), None
        );

        assert!(result.is_ok());
        let (r, v) = result.unwrap();

        // Should match dedicated J2 propagator
        let (r_j2, v_j2) = propagate_j2_rk4(&r0, &v0, dt, GM_EARTH, J2_EARTH, R_EARTH, Some(100)).unwrap();

        assert_relative_eq!(r.x, r_j2.x, epsilon = 1.0);
        assert_relative_eq!(r.y, r_j2.y, epsilon = 1.0);
        assert_relative_eq!(r.z, r_j2.z, epsilon = 1.0);
        assert_relative_eq!(v.x, v_j2.x, epsilon = 0.001);
        assert_relative_eq!(v.y, v_j2.y, epsilon = 0.001);
        assert_relative_eq!(v.z, v_j2.z, epsilon = 0.001);
    }

    #[test]
    fn test_propagate_with_perturbations_combined() {
        let mut perts = PerturbationSet::new();
        perts.add(J2Perturbation::earth());
        perts.add(DragPerturbation::earth(100.0));

        let r0 = Vector3::new(6778e3, 0.0, 0.0); // 400 km altitude
        let v0 = Vector3::new(0.0, 7670.0, 0.0);
        let dt = 600.0; // 10 minutes

        let result = propagate_with_perturbations(
            &r0, &v0, dt, GM_EARTH, &perts, "dopri5", None, Some(1e-8)
        );

        assert!(result.is_ok());
        let (r, v) = result.unwrap();

        // Should still be in orbit with reasonable values
        assert!(r.norm() > 6000e3);
        assert!(r.norm() < 8000e3);
        assert!(v.norm() > 1000.0);
        assert!(v.norm() < 10000.0);

        // Verify the result is different from initial state (perturbations had an effect)
        let pos_diff = (r - r0).norm();
        let vel_diff = (v - v0).norm();
        assert!(pos_diff > 100.0); // Position changed by at least 100 m
        assert!(vel_diff > 0.1); // Velocity changed by at least 0.1 m/s
    }

    #[test]
    fn test_propagate_with_perturbations_invalid_method() {
        let perts = PerturbationSet::new();

        let r0 = Vector3::new(7000e3, 0.0, 0.0);
        let v0 = Vector3::new(0.0, 7546.0, 0.0);

        let result = propagate_with_perturbations(
            &r0, &v0, 600.0, GM_EARTH, &perts, "invalid", None, None
        );

        assert!(result.is_err());
    }
}